Facies classification using Convolutional Neural Networks

Team StoDIG - Statoil Deep-learning Interest Group

David Wade, John Thurmond & Eskil Kulseth Dahl

In this python notebook we propose a facies classification model, building on the simple Neural Network solution proposed by LA_Team in order to outperform the prediction model proposed in the predicting facies from well logs challenge.

Given the limited size of the training data set, Deep Learning is not likely to exceed the accuracy of results from refined Machine Learning techniques (such as Gradient Boosted Trees). However, we chose to use the opportunity to advance our understanding of Deep Learning network design, and have enjoyed participating in the contest. With a substantially larger training set and perhaps more facies ambiguity, Deep Learning could be a preferred approach to this sort of problem.

We use three key innovations:

  • Inserting a convolutional layer as the first layer in the Neural Network
  • Initializing the weights of this layer to detect gradients and extrema
  • Adding Dropout regularization to prevent overfitting

Since our submission #2 we have:

  • Added the distance to the next NM_M transition as a feature (thanks to geoLEARN where we spotted this)
  • Removed Recruit F9 from training

... and since our submission #3 we have:

  • Included training/predicting on the Formation categories
  • Made our facies plot better, including demonstrating our confidence in each prediction

Problem Modeling


The dataset we will use comes from a class excercise from The University of Kansas on Neural Networks and Fuzzy Systems. This exercise is based on a consortium project to use machine learning techniques to create a reservoir model of the largest gas fields in North America, the Hugoton and Panoma Fields. For more info on the origin of the data, see Bohling and Dubois (2003) and Dubois et al. (2007).

The dataset we will use is log data from nine wells that have been labeled with a facies type based on oberservation of core. We will use this log data to train a classifier to predict facies types.

This data is from the Council Grove gas reservoir in Southwest Kansas. The Panoma Council Grove Field is predominantly a carbonate gas reservoir encompassing 2700 square miles in Southwestern Kansas. This dataset is from nine wells (with 4149 examples), consisting of a set of seven predictor variables and a rock facies (class) for each example vector and validation (test) data (830 examples from two wells) having the same seven predictor variables in the feature vector. Facies are based on examination of cores from nine wells taken vertically at half-foot intervals. Predictor variables include five from wireline log measurements and two geologic constraining variables that are derived from geologic knowledge. These are essentially continuous variables sampled at a half-foot sample rate.

The seven predictor variables are:

The nine discrete facies (classes of rocks) are:

  1. Nonmarine sandstone
  2. Nonmarine coarse siltstone
  3. Nonmarine fine siltstone
  4. Marine siltstone and shale
  5. Mudstone (limestone)
  6. Wackestone (limestone)
  7. Dolomite
  8. Packstone-grainstone (limestone)
  9. Phylloid-algal bafflestone (limestone)

These facies aren't discrete, and gradually blend into one another. Some have neighboring facies that are rather close. Mislabeling within these neighboring facies can be expected to occur. The following table lists the facies, their abbreviated labels and their approximate neighbors.

Facies Label Adjacent Facies
1 SS 2
2 CSiS 1,3
3 FSiS 2
4 SiSh 5
5 MS 4,6
6 WS 5,7
7 D 6,8
8 PS 6,7,9
9 BS 7,8

Setup


Check we have all the libraries we need, and import the modules we require. Note that we have used the Theano backend for Keras, and to achieve a reasonable training time we have used an NVidia K20 GPU.


In [1]:
%%sh
pip install pandas
pip install scikit-learn
pip install keras
pip install sklearn


Requirement already satisfied: pandas in /home/dawad/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: python-dateutil>=2 in /home/dawad/anaconda3/lib/python3.5/site-packages (from pandas)
Requirement already satisfied: pytz>=2011k in /home/dawad/anaconda3/lib/python3.5/site-packages (from pandas)
Requirement already satisfied: numpy>=1.7.0 in /home/dawad/anaconda3/lib/python3.5/site-packages (from pandas)
Requirement already satisfied: six>=1.5 in /home/dawad/anaconda3/lib/python3.5/site-packages (from python-dateutil>=2->pandas)
Requirement already satisfied: scikit-learn in /home/dawad/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: keras in /home/dawad/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: six in /home/dawad/anaconda3/lib/python3.5/site-packages (from keras)
Requirement already satisfied: theano in /home/dawad/anaconda3/lib/python3.5/site-packages (from keras)
Requirement already satisfied: pyyaml in /home/dawad/anaconda3/lib/python3.5/site-packages (from keras)
Requirement already satisfied: scipy>=0.11 in /home/dawad/anaconda3/lib/python3.5/site-packages (from theano->keras)
Requirement already satisfied: numpy>=1.7.1 in /home/dawad/anaconda3/lib/python3.5/site-packages (from theano->keras)
Requirement already satisfied: sklearn in /home/dawad/anaconda3/lib/python3.5/site-packages
Requirement already satisfied: scikit-learn in /home/dawad/anaconda3/lib/python3.5/site-packages (from sklearn)

In [2]:
from __future__ import print_function
import time
import numpy as np
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from keras.preprocessing import sequence
from keras.models import Model, Sequential
from keras.constraints import maxnorm, nonneg
from keras.optimizers import SGD, Adam, Adamax, Nadam
from keras.regularizers import l2, activity_l2
from keras.layers import Input, Dense, Dropout, Activation, Convolution1D, Cropping1D, Cropping2D, Permute, Flatten, MaxPooling1D, merge
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold , StratifiedKFold
from classification_utilities import display_cm, display_adj_cm
from sklearn.metrics import confusion_matrix, f1_score
from sklearn import preprocessing
from sklearn.model_selection import GridSearchCV


Using Theano backend.
Using gpu device 0: Tesla K20c (CNMeM is enabled with initial size: 80.0% of memory, cuDNN 5105)
/home/dawad/anaconda3/lib/python3.5/site-packages/theano/sandbox/cuda/__init__.py:600: UserWarning: Your cuDNN version is more recent than the one Theano officially supports. If you see any problems, try updating Theano or downgrading cuDNN to version 5.
  warnings.warn(warn)

Data ingest


We load the training and testing data to preprocess it for further analysis, filling the missing data values in the PE field with zero and proceeding to normalize the data that will be fed into our model. We now incorporate the Imputation from Paolo Bestagini via LA_Team's Submission 5.


In [3]:
data = pd.read_csv('train_test_data.csv')

# Set 'Well Name' and 'Formation' fields as categories
data['Well Name'] = data['Well Name'].astype('category')
data['Formation'] = data['Formation'].astype('category')

def coding(col, codeDict):
    colCoded = pd.Series(col, copy=True)
    for key, value in codeDict.items():
        colCoded.replace(key, value, inplace=True)
    return colCoded

data['Formation_coded'] = coding(data['Formation'], {'A1 LM':1,'A1 SH':2,'B1 LM':3,'B1 SH':4,'B2 LM':5,'B2 SH':6,'B3 LM':7,'B3 SH':8,'B4 LM':9,'B4 SH':10,'B5 LM':11,'B5 SH':12,'C LM':13,'C SH':14})
formation = data['Formation_coded'].values[:,np.newaxis]

# Parameters
feature_names = ['Depth', 'GR', 'ILD_log10', 'DeltaPHI', 'PHIND', 'PE', 'NM_M', 'RELPOS']
facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS','WS', 'D','PS', 'BS']
facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D']
well_names_test = ['SHRIMPLIN', 'ALEXANDER D', 'SHANKLE', 'LUKE G U', 'KIMZEY A', 'CROSS H CATTLE', 'NOLAN', 'Recruit F9', 'NEWBY', 'CHURCHMAN BIBLE']
well_names_validate = ['STUART', 'CRAWFORD']

data_vectors = data[feature_names].values
correct_facies_labels = data['Facies'].values

nm_m = data['NM_M'].values
nm_m_dist = np.zeros((nm_m.shape[0],1), dtype=int)

for i in range(nm_m.shape[0]):
    count=1
    while (i+count<nm_m.shape[0]-1 and nm_m[i+count] == nm_m[i]):
        count = count+1
    nm_m_dist[i] = count
    
nm_m_dist.reshape(nm_m_dist.shape[0],1)

well_labels = data[['Well Name', 'Facies']].values
depth = data['Depth'].values

# Fill missing values and normalize for 'PE' field
imp = preprocessing.Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit(data_vectors)
data_vectors = imp.transform(data_vectors)

data_vectors = np.hstack([data_vectors, nm_m_dist, formation])

scaler = preprocessing.StandardScaler().fit(data_vectors)
scaled_features = scaler.transform(data_vectors)
data_out = np.hstack([well_labels, scaled_features])

Split data into training data and blind data, and output as Numpy arrays


In [4]:
def preprocess(data_out):
    
    data = data_out
      
    X = data[0:4149,0:12]
    
    y = np.concatenate((data[0:4149,0].reshape(4149,1), np_utils.to_categorical(correct_facies_labels[0:4149]-1)), axis=1)
    X_test = data[4149:,0:12]

    return X, y, X_test

X_train_in, y_train, X_test_in = preprocess(data_out)

print(X_train_in.shape)


(4149, 12)

Data Augmentation


We expand the input data to be acted on by the convolutional layer.


In [5]:
conv_domain = 11

# Reproducibility
np.random.seed(7) 
# Load data

def expand_dims(input):
    r = int((conv_domain-1)/2)
    l = input.shape[0]
    n_input_vars = input.shape[1]
    output = np.zeros((l, conv_domain, n_input_vars))
    for i in range(l):
        for j in range(conv_domain):
            for k in range(n_input_vars):
                output[i,j,k] = input[min(i+j-r,l-1),k]
    return output

X_train = np.empty((0,conv_domain,10), dtype=float)
X_test  = np.empty((0,conv_domain,10), dtype=float)
y_select = np.empty((0,9), dtype=int)

well_names_train = ['SHRIMPLIN', 'ALEXANDER D', 'SHANKLE', 'LUKE G U', 'KIMZEY A', 'CROSS H CATTLE', 'NOLAN', 'NEWBY', 'CHURCHMAN BIBLE']

for wellId in well_names_train:
    X_train_subset = X_train_in[X_train_in[:, 0] == wellId][:,2:12]
    X_train_subset = expand_dims(X_train_subset)
    X_train = np.concatenate((X_train,X_train_subset),axis=0)
    y_select = np.concatenate((y_select, y_train[y_train[:, 0] == wellId][:,1:11]), axis=0)
    
for wellId in well_names_validate:
    X_test_subset = X_test_in[X_test_in[:, 0] == wellId][:,2:12]
    X_test_subset = expand_dims(X_test_subset)
    X_test = np.concatenate((X_test,X_test_subset),axis=0)

y_train = y_select
    
print(X_train.shape)
print(X_test.shape)
print(y_select.shape)


(4069, 11, 10)
(830, 11, 10)
(4069, 9)

Convolutional Neural Network

We build a CNN with the following layers (no longer using Sequential() model):

  • Dropout layer on input
  • One 1D convolutional layer (7-point radius)
  • One 1D cropping layer (just take actual log-value of interest)
  • Series of Merge layers re-adding result of cropping layer plus Dropout & Fully-Connected layers

Instead of running CNN with gradient features added, we initialize the Convolutional layer weights to achieve this

  • This allows the CNN to reject them, adjust them or turn them into something else if required

In [6]:
# Set parameters
input_dim = 10
output_dim = 9
n_per_batch = 128
epochs = 100
crop_factor = int(conv_domain/2)
filters_per_log = 11
n_convolutions = input_dim*filters_per_log

starting_weights = [np.zeros((conv_domain, 1, input_dim, n_convolutions)), np.ones((n_convolutions))]

norm_factor=float(conv_domain)*2.0


for i in range(input_dim):
    for j in range(conv_domain):
        starting_weights[0][j, 0, i, i*filters_per_log+0]  = j/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+1]  = j/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+2]  = (conv_domain-j)/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+3]  = (conv_domain-j)/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+4]  = (2*abs(crop_factor-j))/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+5]  = (conv_domain-2*abs(crop_factor-j))/norm_factor
        starting_weights[0][j, 0, i, i*filters_per_log+6]  = 0.25
        starting_weights[0][j, 0, i, i*filters_per_log+7]  = 0.5  if (j%2 == 0) else 0.25
        starting_weights[0][j, 0, i, i*filters_per_log+8]  = 0.25 if (j%2 == 0) else 0.5
        starting_weights[0][j, 0, i, i*filters_per_log+9]  = 0.5  if (j%4 == 0) else 0.25
        starting_weights[0][j, 0, i, i*filters_per_log+10] = 0.25 if (j%4 == 0) else 0.5

def dnn_model(init_dropout_rate=0.5, main_dropout_rate=0.5,
              hidden_dim_1=24, hidden_dim_2=40, 
              max_norm=10, nb_conv=n_convolutions):
    # Define the model
    inputs = Input(shape=(conv_domain,input_dim,))
    inputs_dropout = Dropout(init_dropout_rate)(inputs)

    x1 = Convolution1D(nb_conv, conv_domain, border_mode='valid', weights=starting_weights, activation='tanh', input_shape=(conv_domain,input_dim), input_length=input_dim, W_constraint=nonneg())(inputs_dropout)
    x1 = Flatten()(x1)   

    xn = Cropping1D(cropping=(crop_factor,crop_factor))(inputs_dropout)
    xn = Flatten()(xn)

    xA = merge([x1, xn], mode='concat')    
    xA = Dropout(main_dropout_rate)(xA)
    xA = Dense(hidden_dim_1, init='uniform', activation='relu', W_constraint=maxnorm(max_norm))(xA)
    
    x = merge([xA, xn], mode='concat')    
    x = Dropout(main_dropout_rate)(x)
    x = Dense(hidden_dim_2, init='uniform', activation='relu', W_constraint=maxnorm(max_norm))(x)
    
    predictions = Dense(output_dim, init='uniform', activation='softmax')(x)
    
    model = Model(input=inputs, output=predictions)
    
    optimizerNadam = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004)
    model.compile(loss='categorical_crossentropy', optimizer=optimizerNadam, metrics=['accuracy'])
    return model

# Load the model
t0 = time.time()
model_dnn = dnn_model()
model_dnn.summary()
t1 = time.time()
print("Load time = %d" % (t1-t0) )

def plot_weights(n_convs_disp=input_dim):
    layerID=2

    print(model_dnn.layers[layerID].get_weights()[0].shape)
    print(model_dnn.layers[layerID].get_weights()[1].shape)

    fig, ax = plt.subplots(figsize=(12,10))

    for i in range(n_convs_disp):
        plt.subplot(input_dim,1,i+1)
        plt.imshow(model_dnn.layers[layerID].get_weights()[0][:,0,i,:], interpolation='none')

    plt.show()
    
plot_weights(1)


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_1 (InputLayer)             (None, 11, 10)        0                                            
____________________________________________________________________________________________________
dropout_1 (Dropout)              (None, 11, 10)        0           input_1[0][0]                    
____________________________________________________________________________________________________
convolution1d_1 (Convolution1D)  (None, 1, 110)        12210       dropout_1[0][0]                  
____________________________________________________________________________________________________
cropping1d_1 (Cropping1D)        (None, 1, 10)         0           dropout_1[0][0]                  
____________________________________________________________________________________________________
flatten_1 (Flatten)              (None, 110)           0           convolution1d_1[0][0]            
____________________________________________________________________________________________________
flatten_2 (Flatten)              (None, 10)            0           cropping1d_1[0][0]               
____________________________________________________________________________________________________
merge_1 (Merge)                  (None, 120)           0           flatten_1[0][0]                  
                                                                   flatten_2[0][0]                  
____________________________________________________________________________________________________
dropout_2 (Dropout)              (None, 120)           0           merge_1[0][0]                    
____________________________________________________________________________________________________
dense_1 (Dense)                  (None, 24)            2904        dropout_2[0][0]                  
____________________________________________________________________________________________________
merge_2 (Merge)                  (None, 34)            0           dense_1[0][0]                    
                                                                   flatten_2[0][0]                  
____________________________________________________________________________________________________
dropout_3 (Dropout)              (None, 34)            0           merge_2[0][0]                    
____________________________________________________________________________________________________
dense_2 (Dense)                  (None, 40)            1400        dropout_3[0][0]                  
____________________________________________________________________________________________________
dense_3 (Dense)                  (None, 9)             369         dense_2[0][0]                    
====================================================================================================
Total params: 16,883
Trainable params: 16,883
Non-trainable params: 0
____________________________________________________________________________________________________
Load time = 0
(11, 1, 10, 110)
(110,)

We train the CNN and evaluate it on precision/recall.


In [7]:
#Train model
t0 = time.time()
model_dnn.fit(X_train, y_train, batch_size=n_per_batch, nb_epoch=epochs, verbose=2)
t1 = time.time()
print("Train time = %d seconds" % (t1-t0) )


# Predict Values on Training set
t0 = time.time()
y_predicted = model_dnn.predict( X_train , batch_size=n_per_batch, verbose=2)
t1 = time.time()
print("Test time = %d seconds" % (t1-t0) )

# Print Report

# Format output [0 - 8 ]
y_ = np.zeros((len(y_train),1))
for i in range(len(y_train)):
    y_[i] = np.argmax(y_train[i])

y_predicted_ = np.zeros((len(y_predicted), 1))
for i in range(len(y_predicted)):
    y_predicted_[i] = np.argmax( y_predicted[i] )
    
# Confusion Matrix
conf = confusion_matrix(y_, y_predicted_)

def accuracy(conf):
    total_correct = 0.
    nb_classes = conf.shape[0]
    for i in np.arange(0,nb_classes):
        total_correct += conf[i][i]
    acc = total_correct/sum(sum(conf))
    return acc

adjacent_facies = np.array([[1], [0,2], [1], [4], [3,5], [4,6,7], [5,7], [5,6,8], [6,7]])

def accuracy_adjacent(conf, adjacent_facies):
    nb_classes = conf.shape[0]
    total_correct = 0.
    for i in np.arange(0,nb_classes):
        total_correct += conf[i][i]
        for j in adjacent_facies[i]:
            total_correct += conf[i][j]
    return total_correct / sum(sum(conf))

# Print Results
print ("\nModel Report")
print ("-Accuracy: %.6f" % ( accuracy(conf) ))
print ("-Adjacent Accuracy: %.6f" % ( accuracy_adjacent(conf, adjacent_facies) ))
print ("\nConfusion Matrix")
display_cm(conf, facies_labels, display_metrics=True, hide_zeros=True)


Epoch 1/100
0s - loss: 1.8855 - acc: 0.2986
Epoch 2/100
0s - loss: 1.4205 - acc: 0.4030
Epoch 3/100
0s - loss: 1.3556 - acc: 0.4308
Epoch 4/100
0s - loss: 1.3168 - acc: 0.4404
Epoch 5/100
0s - loss: 1.2814 - acc: 0.4635
Epoch 6/100
0s - loss: 1.2592 - acc: 0.4783
Epoch 7/100
0s - loss: 1.2316 - acc: 0.4999
Epoch 8/100
0s - loss: 1.2360 - acc: 0.4940
Epoch 9/100
0s - loss: 1.2010 - acc: 0.4947
Epoch 10/100
0s - loss: 1.1999 - acc: 0.5009
Epoch 11/100
0s - loss: 1.2022 - acc: 0.5043
Epoch 12/100
0s - loss: 1.2038 - acc: 0.4932
Epoch 13/100
0s - loss: 1.1610 - acc: 0.5200
Epoch 14/100
0s - loss: 1.1756 - acc: 0.5163
Epoch 15/100
0s - loss: 1.1699 - acc: 0.5200
Epoch 16/100
0s - loss: 1.1612 - acc: 0.5299
Epoch 17/100
0s - loss: 1.1623 - acc: 0.5139
Epoch 18/100
0s - loss: 1.1727 - acc: 0.5166
Epoch 19/100
0s - loss: 1.1448 - acc: 0.5205
Epoch 20/100
0s - loss: 1.1798 - acc: 0.5272
Epoch 21/100
0s - loss: 1.1540 - acc: 0.5276
Epoch 22/100
0s - loss: 1.1333 - acc: 0.5308
Epoch 23/100
0s - loss: 1.1563 - acc: 0.5272
Epoch 24/100
0s - loss: 1.1502 - acc: 0.5318
Epoch 25/100
0s - loss: 1.1515 - acc: 0.5173
Epoch 26/100
0s - loss: 1.1504 - acc: 0.5284
Epoch 27/100
0s - loss: 1.1473 - acc: 0.5257
Epoch 28/100
0s - loss: 1.1376 - acc: 0.5299
Epoch 29/100
0s - loss: 1.1349 - acc: 0.5198
Epoch 30/100
0s - loss: 1.1466 - acc: 0.5240
Epoch 31/100
0s - loss: 1.1308 - acc: 0.5161
Epoch 32/100
0s - loss: 1.1343 - acc: 0.5321
Epoch 33/100
0s - loss: 1.1218 - acc: 0.5456
Epoch 34/100
0s - loss: 1.1020 - acc: 0.5382
Epoch 35/100
0s - loss: 1.1250 - acc: 0.5375
Epoch 36/100
0s - loss: 1.1161 - acc: 0.5385
Epoch 37/100
0s - loss: 1.1245 - acc: 0.5331
Epoch 38/100
0s - loss: 1.1150 - acc: 0.5331
Epoch 39/100
0s - loss: 1.1089 - acc: 0.5387
Epoch 40/100
0s - loss: 1.1322 - acc: 0.5321
Epoch 41/100
0s - loss: 1.1137 - acc: 0.5272
Epoch 42/100
0s - loss: 1.1290 - acc: 0.5284
Epoch 43/100
0s - loss: 1.1076 - acc: 0.5446
Epoch 44/100
0s - loss: 1.1198 - acc: 0.5402
Epoch 45/100
0s - loss: 1.1018 - acc: 0.5468
Epoch 46/100
0s - loss: 1.1184 - acc: 0.5304
Epoch 47/100
0s - loss: 1.1305 - acc: 0.5254
Epoch 48/100
0s - loss: 1.1180 - acc: 0.5421
Epoch 49/100
0s - loss: 1.1139 - acc: 0.5402
Epoch 50/100
0s - loss: 1.1131 - acc: 0.5407
Epoch 51/100
0s - loss: 1.1073 - acc: 0.5468
Epoch 52/100
0s - loss: 1.0888 - acc: 0.5554
Epoch 53/100
0s - loss: 1.0983 - acc: 0.5451
Epoch 54/100
0s - loss: 1.1083 - acc: 0.5407
Epoch 55/100
0s - loss: 1.0901 - acc: 0.5507
Epoch 56/100
0s - loss: 1.1002 - acc: 0.5436
Epoch 57/100
0s - loss: 1.1097 - acc: 0.5431
Epoch 58/100
0s - loss: 1.1039 - acc: 0.5402
Epoch 59/100
0s - loss: 1.1102 - acc: 0.5414
Epoch 60/100
0s - loss: 1.1103 - acc: 0.5358
Epoch 61/100
0s - loss: 1.1021 - acc: 0.5456
Epoch 62/100
0s - loss: 1.1022 - acc: 0.5500
Epoch 63/100
0s - loss: 1.1118 - acc: 0.5434
Epoch 64/100
0s - loss: 1.1103 - acc: 0.5463
Epoch 65/100
0s - loss: 1.1055 - acc: 0.5483
Epoch 66/100
0s - loss: 1.0937 - acc: 0.5338
Epoch 67/100
0s - loss: 1.0819 - acc: 0.5517
Epoch 68/100
0s - loss: 1.0831 - acc: 0.5503
Epoch 69/100
0s - loss: 1.1081 - acc: 0.5485
Epoch 70/100
0s - loss: 1.0736 - acc: 0.5608
Epoch 71/100
0s - loss: 1.0855 - acc: 0.5439
Epoch 72/100
0s - loss: 1.0951 - acc: 0.5566
Epoch 73/100
0s - loss: 1.0928 - acc: 0.5476
Epoch 74/100
0s - loss: 1.0893 - acc: 0.5478
Epoch 75/100
0s - loss: 1.0881 - acc: 0.5468
Epoch 76/100
0s - loss: 1.1021 - acc: 0.5493
Epoch 77/100
0s - loss: 1.0918 - acc: 0.5500
Epoch 78/100
0s - loss: 1.0777 - acc: 0.5608
Epoch 79/100
0s - loss: 1.0788 - acc: 0.5628
Epoch 80/100
0s - loss: 1.0828 - acc: 0.5476
Epoch 81/100
0s - loss: 1.0842 - acc: 0.5505
Epoch 82/100
0s - loss: 1.0920 - acc: 0.5539
Epoch 83/100
0s - loss: 1.0755 - acc: 0.5498
Epoch 84/100
0s - loss: 1.0801 - acc: 0.5657
Epoch 85/100
0s - loss: 1.0885 - acc: 0.5532
Epoch 86/100
0s - loss: 1.0805 - acc: 0.5483
Epoch 87/100
0s - loss: 1.0913 - acc: 0.5522
Epoch 88/100
0s - loss: 1.0893 - acc: 0.5490
Epoch 89/100
0s - loss: 1.0731 - acc: 0.5611
Epoch 90/100
0s - loss: 1.0670 - acc: 0.5559
Epoch 91/100
0s - loss: 1.0512 - acc: 0.5724
Epoch 92/100
0s - loss: 1.0752 - acc: 0.5549
Epoch 93/100
0s - loss: 1.0733 - acc: 0.5569
Epoch 94/100
0s - loss: 1.0915 - acc: 0.5525
Epoch 95/100
0s - loss: 1.0676 - acc: 0.5532
Epoch 96/100
0s - loss: 1.0880 - acc: 0.5500
Epoch 97/100
0s - loss: 1.0787 - acc: 0.5488
Epoch 98/100
0s - loss: 1.0856 - acc: 0.5525
Epoch 99/100
0s - loss: 1.0713 - acc: 0.5638
Epoch 100/100
0s - loss: 1.0699 - acc: 0.5729
Train time = 28 seconds
Test time = 1 seconds

Model Report
-Accuracy: 0.673138
-Adjacent Accuracy: 0.931679

Confusion Matrix
     Pred    SS  CSiS  FSiS  SiSh    MS    WS     D    PS    BS Total
     True
       SS   216    47     5                                       268
     CSiS    71   661   205                 1           2         940
     FSiS     4   176   586     4           2           8         780
     SiSh           4     1   213     8    39     1     5         271
       MS           6    10    61    66    84     3    66         296
       WS                 3    52    26   362     7   132         582
        D                 1     8     4     9    84    35         141
       PS                14     9    11   137     4   507     4   686
       BS           3                      12     1    45    44   105

Precision  0.74  0.74  0.71  0.61  0.57  0.56  0.84  0.63  0.92  0.68
   Recall  0.81  0.70  0.75  0.79  0.22  0.62  0.60  0.74  0.42  0.67
       F1  0.77  0.72  0.73  0.69  0.32  0.59  0.70  0.68  0.58  0.66

We display the learned 1D convolution kernels


In [8]:
plot_weights()


(11, 1, 10, 110)
(110,)

In order to avoid overfitting, we evaluate our model by running a 5-fold stratified cross-validation routine.


In [9]:
# Cross Validation
def cross_validate():
    t0 = time.time()
    estimator = KerasClassifier(build_fn=dnn_model, nb_epoch=epochs, batch_size=n_per_batch, verbose=0)
    skf = StratifiedKFold(n_splits=5, shuffle=True)
    results_dnn = cross_val_score(estimator, X_train, y_train, cv= skf.get_n_splits(X_train, y_train))
    t1 = time.time()
    print("Cross Validation time = %d" % (t1-t0) )
    print(' Cross Validation Results')
    print( results_dnn )
    print(np.mean(results_dnn))

cross_validate()


Cross Validation time = 109
 Cross Validation Results
[ 0.5970516   0.55773956  0.53685504  0.48280098  0.43050431]
0.520990296458

Prediction


To predict the STUART and CRAWFORD blind wells we do the following:

Set up a plotting function to display the logs & facies.


In [11]:
# 1=sandstone  2=c_siltstone   3=f_siltstone 
# 4=marine_silt_shale 5=mudstone 6=wackestone 7=dolomite
# 8=packstone 9=bafflestone
facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D']

#facies_color_map is a dictionary that maps facies labels
#to their respective colors
facies_color_map = {}
for ind, label in enumerate(facies_labels):
    facies_color_map[label] = facies_colors[ind]

def label_facies(row, labels):
    return labels[ row['Facies'] -1]

def make_facies_log_plot(logs, facies_colors, y_test=None, wellId=None):
    #make sure logs are sorted by depth
    logs = logs.sort_values(by='Depth')
    cmap_facies = colors.ListedColormap(
            facies_colors[0:len(facies_colors)], 'indexed')
    
    ztop=logs.Depth.min(); zbot=logs.Depth.max()

    facies = np.zeros(2*(int(zbot-ztop)+1))
    
    shift = 0
    depth = ztop
    for i in range(logs.Depth.count()-1):
        while (depth < logs.Depth.values[i] + 0.25 and depth < zbot+0.25):
            if (i<logs.Depth.count()-1):
                new = logs['Facies'].values[i]
                facies[shift] = new
                depth += 0.5
                shift += 1
    facies = facies[0:facies.shape[0]-1]
    cluster=np.repeat(np.expand_dims(facies,1), 100, 1)
    
    f, ax = plt.subplots(nrows=1, ncols=8, gridspec_kw={'width_ratios':[1,1,1,1,1,1,2,2]}, figsize=(10, 12))
    ax[0].plot(logs.GR, logs.Depth, '-g')
    ax[1].plot(logs.ILD_log10, logs.Depth, '-')
    ax[2].plot(logs.DeltaPHI, logs.Depth, '-', color='0.5')
    ax[3].plot(logs.PHIND, logs.Depth, '-', color='r')
    ax[4].plot(logs.PE, logs.Depth, '-', color='black')
    ax[5].plot(logs.NM_M, logs.Depth, '-', color='black')
    
    if (y_test is not None):
        for i in range(9):
            if (wellId == 'STUART'):
                ax[6].plot(y_test[0:474,i], logs.Depth, color=facies_colors[i], lw=1.5)
            else:
                ax[6].plot(y_test[474:,i], logs.Depth, color=facies_colors[i], lw=1.5)
                
    im=ax[7].imshow(cluster, interpolation='none', aspect='auto',
                    cmap=cmap_facies,vmin=1,vmax=9)
    
    divider = make_axes_locatable(ax[7])
    cax = divider.append_axes("right", size="20%", pad=0.05)
    cbar=plt.colorbar(im, cax=cax)
    cbar.set_label((17*' ').join([' SS ', 'CSiS', 'FSiS', 
                                'SiSh', ' MS ', ' WS ', ' D  ', 
                                ' PS ', ' BS ']))
    cbar.set_ticks(range(0,1)); cbar.set_ticklabels('')
    
    for i in range(len(ax)-1):
        ax[i].set_ylim(ztop,zbot)
        ax[i].invert_yaxis()
        ax[i].grid()
        ax[i].locator_params(axis='x', nbins=5)
    
    ax[0].set_xlabel("GR")
    ax[0].set_xlim(logs.GR.min(),logs.GR.max())
    ax[1].set_xlabel("ILD_log10")
    ax[1].set_xlim(logs.ILD_log10.min(),logs.ILD_log10.max())
    ax[2].set_xlabel("DeltaPHI")
    ax[2].set_xlim(logs.DeltaPHI.min(),logs.DeltaPHI.max())
    ax[3].set_xlabel("PHIND")
    ax[3].set_xlim(logs.PHIND.min(),logs.PHIND.max())
    ax[4].set_xlabel("PE")
    ax[4].set_xlim(logs.PE.min(),logs.PE.max())
    ax[5].set_xlabel("NM_M")
    ax[5].set_xlim(logs.NM_M.min()-1.,logs.NM_M.max()+1.)
    ax[6].set_xlabel("Facies Prob")
    ax[6].set_xlim(0.0,1.0)
    ax[7].set_xlabel('Facies')
    
    ax[0].set_yticklabels([]);
    ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([])
    ax[4].set_yticklabels([]); ax[5].set_yticklabels([])
    ax[6].set_xticklabels([]); ax[7].set_xticklabels([]);
    f.suptitle('Well: %s'%logs.iloc[0]['Well Name'], fontsize=14,y=0.94)

Run the model on the blind data

  • Output a CSV
  • Plot the wells in the notebook

In [12]:
# DNN model Prediction
y_test = model_dnn.predict( X_test , batch_size=n_per_batch, verbose=0)
predictions_dnn = np.zeros((len(y_test),1))
for i in range(len(y_test)):
    predictions_dnn[i] = np.argmax(y_test[i]) + 1 
predictions_dnn = predictions_dnn.astype(int)
# Store results
train_data = pd.read_csv('train_test_data.csv')
test_data = pd.read_csv('../validation_data_nofacies.csv')
test_data['Facies'] = predictions_dnn
test_data.to_csv('Prediction_StoDIG_3.csv')


for wellId in well_names_validate:
    make_facies_log_plot( test_data[test_data['Well Name'] == wellId], facies_colors=facies_colors, y_test=y_test, wellId=wellId)
    
#for wellId in well_names_test:
#    make_facies_log_plot( train_data[train_data['Well Name'] == wellId], facies_colors=facies_colors)