Let's train some data. I'm Jesper and I have no clue what I'm doing but I'm having fun. Most texts are still from the original notebook from Brandon Hall. As well as the basis for the code.
In [1]:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pandas import set_option
set_option("display.max_rows", 10)
pd.set_option('display.width', 1000)
pd.options.mode.chained_assignment = None
def distance(latlon1,latlon2):
lat1 = np.deg2rad(latlon1[0])
lon1 = np.deg2rad(latlon1[1])
lat2 = np.deg2rad(latlon2[0])
lon2 = np.deg2rad(latlon2[1])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2)**2
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
return (6371 * c)
facies_labels = ['SS','CSiS','FSiS','SiSh','MS','WS','D','PS','BS']
facies = pd.DataFrame({'ShortName': pd.Series(facies_labels,index=facies_labels),'Facies' : pd.Series(['Nonmarine sandstone', 'Nonmarine coarse siltstone', 'Nonmarine fine siltstone ', 'Marine siltstone and shale', 'Mudstone (limestone)', 'Wackestone (limestone)', 'Dolomite', 'Packstone-grainstone (limestone)','Phylloid-algal bafflestone (limestone)'],index=facies_labels), 'Neighbours' : pd.Series(['CSiS',['SS','FSiS'],'CSiS','MS',['SiSh','WS'],['MS','D'],['WS','PS'],['WS','D','BS'],['D','PS']],index=facies_labels), 'Colors' : pd.Series(['#F4D03F', '#F5B041','#DC7633','#6E2C00',
'#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D'],index=facies_labels)})
filename = '../facies_vectors.csv'
training_data = pd.read_csv(filename)
training_data
Out[1]:
Verbatim from Brendon Hall:
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:
In [2]:
facies[['Facies']]
Out[2]:
These facies gradually blend into one another. We can see a marine non-marine neighbourhood already.
In [3]:
pd.DataFrame({'Neighbours' : [facies.ShortName[x] for x in facies.Neighbours]},index=facies_labels)
Out[3]:
The 'Well Name' and 'Formation' columns can be turned into a categorical data type.
In [4]:
training_data['Well Name'] = training_data['Well Name'].astype('category')
training_data['Formation'] = training_data['Formation'].astype('category')
training_data['Well Name'].unique()
Out[4]:
Shrimplin:
ALEXANDER D
SHANKLE
LUKE G U
KIMZEY A
CROSS H CATTLE
NOLAN
Recruit F9
NEWBY
CHURCHMAN BIBLE
STUART
CRAWFORD
In [5]:
latlong = pd.DataFrame({"SHRIMPLIN": [37.98126,-100.98329], "ALEXANDER D": [37.6607787,-95.3534525], "SHANKLE": [38.0633727,-101.3891894], "LUKE G U": [37.4537739,-101.6073725], "KIMZEY A": [37.12289,-101.39697], "CROSS H CATTLE": [37.9105826,-101.6464517], "NOLAN": [37.7866294,-101.0451641], "NEWBY": [37.5406739,-101.5847635], "CHURCHMAN BIBLE": [37.3497658,-101.1060761], "STUART": [37.4857262,-101.1391063], "CRAWFORD": [37.1893654,-101.1494994], "Recruit F9": [37.4,-101]})
#distance([37.660779,-95.353453],[37.349766,-101.106076])
dist_mat= pd.DataFrame(np.zeros((latlong.shape[1],latlong.shape[1])))
#dist_mat = np.zeros(len(latlong.index),len(latlong.index))
for i,x in enumerate(latlong):
for j,y in enumerate(latlong):
if i > j:
dist_mat[i][j] = (distance(latlong[x].values,latlong[y].values))
dist_mat[j][i] = dist_mat[i][j]
dist_mat
Out[5]:
In [6]:
training_data.describe()
Out[6]:
The new data set contains about 1000 data points or 33% more than the original one. Rejoice!
In [7]:
#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'] ]
training_data['Facies'] = training_data['Facies']-1
training_data.loc[:,'FaciesLabels'] = training_data.apply(lambda row: label_facies(row, facies_labels), axis=1)
rows = len(training_data.index)
processed_data = training_data.copy()
Let's take a look at the data from individual wells in a more familiar log plot form. We will create plots for the five well log variables, as well as a log for facies labels. The plots are based on the those described in Alessandro Amato del Monte's excellent tutorial.
In [109]:
def make_facies_log_plot(logs, facies_colors):
#make sure logs are sorted by depth
logs = logs.sort_values(by='Depth')
cmap_facies = colors.ListedColormap(
facies.Colors[0:len(facies.Colors)], 'indexed')
cmap_coarse = colors.ListedColormap(['#c0c0c0','#000000'])
ztop=logs.Depth.min(); zbot=logs.Depth.max()
cluster=np.repeat(np.expand_dims(logs['Facies'].values,1), 100, 1)
clustercoarse=np.repeat(np.expand_dims(logs['NM_M'].values,1), 100, 1)
f, ax = plt.subplots(nrows=1, ncols=7, figsize=(8, 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')
im1 = ax[5].imshow(cluster, interpolation='none', aspect='auto',
cmap=cmap_facies,vmin=0,vmax=8)
im2 = ax[6].imshow(clustercoarse, interpolation='none', aspect='auto',
cmap=cmap_coarse,vmin=0,vmax=1)
divider = make_axes_locatable(ax[6])
cax = divider.append_axes("right", size="20%", pad=0.05)
cbar=plt.colorbar(im1, cax=cax)
cbar.set_label((18*' ').join(facies.index))
cbar.set_ticks(range(0,1)); cbar.set_ticklabels('')
for i in range(len(ax)-2):
ax[i].set_ylim(ztop,zbot)
ax[i].invert_yaxis()
ax[i].grid()
ax[i].locator_params(axis='x', nbins=3)
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('Facies')
ax[6].set_xlabel('NM_M')
ax[1].set_yticklabels([]); ax[2].set_yticklabels([]); ax[3].set_yticklabels([])
ax[4].set_yticklabels([]); ax[5].set_yticklabels([]); ax[6].set_yticklabels([])
ax[5].set_xticklabels([]); ax[6].set_xticklabels([])
f.suptitle('Well: %s'%logs.iloc[0]['Well Name'], fontsize=14,y=0.94)
plt.show()
Here's the SHRIMPLIN
well for your vieling pleasure.
In [9]:
make_facies_log_plot(
processed_data[processed_data['Well Name'] == 'SHRIMPLIN'],
facies.Colors)
In addition to individual wells, we can look at how the various facies are represented by the entire training set. Let's plot a histogram of the number of training examples for each facies class.
In [10]:
#count the number of unique entries for each facies, sort them by
#facies number (instead of by number of entries)
facies_counts = processed_data['Facies'].value_counts().sort_index()
tmp = processed_data.query('NM_M==1')
facies_counts0 = tmp['Facies'].value_counts().sort_index()
tmp = processed_data.query('NM_M==2')
facies_counts1 = tmp['Facies'].value_counts().sort_index()
#use facies labels to index each count
facies_counts.index = facies_labels
facies_counts.plot(kind='bar',color=facies.Colors,
title='Distribution of Training Data by Facies')
pd.DataFrame(facies_counts).T
Out[10]:
This shows the distribution of examples by facies for the examples in the training set. Dolomite (facies 7) has the fewest with 81 examples. Depending on the performance of the classifier we are going to train, we may consider getting more examples of these facies.
Crossplots are a familiar tool in the geosciences to visualize how two properties vary with rock type. This dataset contains 5 log variables, and scatter matrix can help to quickly visualize the variation between the all the variables in the dataset. We can employ the very useful Seaborn library to quickly create a nice looking scatter matrix. Each pane in the plot shows the relationship between two of the variables on the x and y axis, with each point is colored according to its facies. The same colormap is used to represent the 9 facies.
In [11]:
#save plot display settings to change back to when done plotting with seaborn
inline_rc = dict(mpl.rcParams)
import seaborn as sns
sns.set()
plotdata=processed_data.drop(['Well Name','Formation','Depth','RELPOS'],axis=1).dropna()
sns.pairplot(plotdata.drop(['Facies','NM_M'],axis=1),
hue='FaciesLabels', palette=facies_color_map,
hue_order=list(reversed(facies_labels)))
Out[11]:
At this point I woult like to take a look at the separated main classes.
In [12]:
facies_counts0.plot(kind='bar',color=facies.Colors,
title='Distribution of Training Data by Facies')
pd.DataFrame(facies_counts0).T
Out[12]:
In [13]:
facies_counts1.plot(kind='bar',color=facies.Colors,
title='Distribution of Training Data by Facies')
pd.DataFrame(facies_counts1).T
Out[13]:
In [81]:
from sklearn import preprocessing
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from scipy import signal
enc = preprocessing.OneHotEncoder()
processed_data['NM_M'] = enc.fit(processed_data[['NM_M']]).transform(processed_data[['NM_M']]).toarray()
feature_vectors = processed_data.drop(['Formation', 'Well Name','Depth','Facies','FaciesLabels'], axis=1)
training_data= training_data[training_data['PE'].notnull().values]
correct_facies_labels = processed_data['Facies'].values
correct_facies_labels_comp = training_data['Facies'].values
feature_vectors_comp = training_data.drop(['Formation', 'Well Name','Depth','Facies','FaciesLabels'], axis=1)
#combined_features = FeatureUnion([("original_data", orig_feature_vectors), ("univ_select", selection)])
preping = Pipeline([("imputer", preprocessing.Imputer(missing_values='NaN',strategy="mean",axis=0)),
("scaling", preprocessing.StandardScaler()),
("trees", RandomForestClassifier())])
preping.set_params(trees__random_state=42).fit(orig_feature_vectors,correct_facies_labels)
score = cross_val_score(preping, orig_feature_vectors, correct_facies_labels).mean()
print("Score after preprocessing: {0}".format(score))
In [36]:
processed_data.describe()
Out[36]:
In [37]:
#scaler = preprocessing.StandardScaler().fit(feature_vectors)
#scaled_features = scaler.transform(feature_vectors)
scaler_comp = preprocessing.StandardScaler().fit(feature_vectors_comp)
scaled_features_comp = scaler_comp.transform(feature_vectors_comp)
Scikit includes a preprocessing module that can 'standardize' the data (giving each variable zero mean and unit variance, also called whitening). Many machine learning algorithms assume features will be standard normally distributed data (ie: Gaussian with zero mean and unit variance). The factors used to standardize the training set must be applied to any subsequent feature set that will be input to the classifier. The StandardScalar
class can be fit to the training set, and later used to standardize any training data.
Scikit also includes a handy function to randomly split the training data into training and test sets. The test set contains a small subset of feature vectors that are not used to train the network. Because we know the true facies labels for these examples, we can compare the results of the classifier to the actual facies and determine the accuracy of the model. Let's use 20% of the data for the test set.
In [38]:
from sklearn.ensemble import RandomForestClassifier
clf = preping
clf_comp = RandomForestClassifier()
Now we can train the classifier using the training set we created above.
In [39]:
clf_comp.fit(scaled_features_comp,correct_facies_labels_comp)
Out[39]:
Now that the model has been trained on our data, we can use it to predict the facies of the feature vectors in the test set. Because we know the true facies labels of the vectors in the test set, we can use the results to evaluate the accuracy of the classifier.
In [51]:
predicted_labels = clf.predict(feature_vectors)
predicted_labels_comp = clf_comp.predict(scaled_features_comp)
We need some metrics to evaluate how good our classifier is doing. A confusion matrix is a table that can be used to describe the performance of a classification model. Scikit-learn allows us to easily create a confusion matrix by supplying the actual and predicted facies labels.
The confusion matrix is simply a 2D array. The entries of confusion matrix C[i][j]
are equal to the number of observations predicted to have facies j
, but are known to have facies i
.
To simplify reading the confusion matrix, a function has been written to display the matrix along with facies labels and various error metrics. See the file classification_utilities.py
in this repo for the display_cm()
function.
In [52]:
from sklearn.metrics import confusion_matrix,f1_score, accuracy_score, make_scorer
from classification_utilities import display_cm, display_adj_cm
In [53]:
conf = confusion_matrix(correct_facies_labels, predicted_labels)
display_cm(conf, facies_labels, hide_zeros=True)
In [54]:
conf_comp = confusion_matrix(correct_facies_labels_comp, predicted_labels_comp)
display_cm(conf_comp, facies_labels, hide_zeros=True)
The rows of the confusion matrix correspond to the actual facies labels. The columns correspond to the labels assigned by the classifier. For example, consider the first row. For the feature vectors in the test set that actually have label SS
, 23 were correctly indentified as SS
, 21 were classified as CSiS
and 2 were classified as FSiS
.
The entries along the diagonal are the facies that have been correctly classified. Below we define two functions that will give an overall value for how the algorithm is performing. The accuracy is defined as the number of correct classifications divided by the total number of classifications.
In [45]:
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
As noted above, the boundaries between the facies classes are not all sharp, and some of them blend into one another. The error within these 'adjacent facies' can also be calculated. We define an array to represent the facies adjacent to each other. For facies label i
, adjacent_facies[i]
is an array of the adjacent facies labels.
In [46]:
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,offset):
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-offset]
return total_correct / sum(sum(conf))
In [47]:
print('Processed Full')
print('Facies classification accuracy = %f' % accuracy(conf))
print('Adjacent facies classification accuracy = %f' % accuracy_adjacent(conf, adjacent_facies,0))
In [48]:
print('Non-processed')
print('Facies classification accuracy = %f' % accuracy(conf_comp))
print('Adjacent facies classification accuracy = %f' % accuracy_adjacent(conf_comp, adjacent_facies,0))
The classifier so far has been built with the default parameters. However, we may be able to get improved classification results with optimal parameter choices.
We will consider two parameters. The parameter C
is a regularization factor, and tells the classifier how much we want to avoid misclassifying training examples. A large value of C will try to correctly classify more examples from the training set, but if C
is too large it may 'overfit' the data and fail to generalize when classifying new data. If C
is too small then the model will not be good at fitting outliers and will have a large error on the training set.
The SVM learning algorithm uses a kernel function to compute the distance between feature vectors. Many kernel functions exist, but in this case we are using the radial basis function rbf
kernel (the default). The gamma
parameter describes the size of the radial basis functions, which is how far away two vectors in the feature space need to be to be considered close.
We will train a series of classifiers with different values for C
and gamma
. Two nested loops are used to train a classifier for every possible combination of values in the ranges specified. The classification accuracy is recorded for each combination of parameter values. The results are shown in a series of plots, so the parameter values that give the best classification accuracy on the test set can be selected.
This process is also known as 'cross validation'. Often a separate 'cross validation' dataset will be created in addition to the training and test sets to do model selection. For this tutorial we will just use the test set to choose model parameters.
In [58]:
from sklearn.model_selection import RandomizedSearchCV,LeaveOneGroupOut
from scipy.stats import randint as sp_randint
Fscorer = make_scorer(f1_score, average = 'micro')
Ascorer = make_scorer(accuracy_score)
clf = Pipeline([("imputer", preprocessing.Imputer(missing_values='NaN',strategy="mean",axis=0)),
("scaling", preprocessing.StandardScaler()),
("trees", RandomForestClassifier())])
clf_comp = RandomForestClassifier()
n_iter_search = 30
param_dist = {"trees__max_depth": [np.sqrt(feature_vectors.shape[1]),np.log2(feature_vectors.shape[1]),None],
"trees__n_estimators": sp_randint(30,200),
"trees__max_features": sp_randint(3,feature_vectors.shape[1]),
"trees__min_samples_split": sp_randint(10,100),
"trees__min_samples_leaf": sp_randint(2,30)}
param_dist_comp = {"max_depth": [np.sqrt(scaled_features_comp.shape[1]),np.log2(scaled_features_comp.shape[1]),None],
"n_estimators": sp_randint(30,200),
"max_features": sp_randint(3,scaled_features_comp.shape[1]),
"min_samples_split": sp_randint(10,100),
"min_samples_leaf": sp_randint(2,30)}
In [60]:
random_search = RandomizedSearchCV(clf, param_distributions=param_dist,scoring = Fscorer,n_iter=n_iter_search)
random_search.fit(feature_vectors,correct_facies_labels)
print('Best score for combo: {}'.format(random_search.best_score_))
print('Best parameters for combo: {}'.format(random_search.best_params_))
clf = random_search.best_estimator_
random_search.best_estimator_
Out[60]:
In [61]:
random_search_comp = RandomizedSearchCV(clf_comp, param_distributions=param_dist_comp,scoring = Fscorer,n_iter=n_iter_search)
random_search_comp.fit(scaled_features_comp,correct_facies_labels_comp)
print('Best score for unprocessed: {}'.format(random_search_comp.best_score_))
print('Best parameters for unprocessed: {}'.format(random_search_comp.best_params_))
clf_comp = random_search_comp.best_estimator_
random_search_comp.best_estimator_
Out[61]:
Okay, take it up a notch.
In [62]:
clf.fit(feature_vectors, correct_facies_labels)
Out[62]:
In [63]:
clf_comp.fit(scaled_features_comp, correct_facies_labels_comp)
Out[63]:
In [65]:
cv_conf = confusion_matrix(correct_facies_labels, clf.predict(feature_vectors))
cv_conf_comp = confusion_matrix(correct_facies_labels_comp, clf_comp.predict(scaled_features_comp))
In [66]:
print('Preprocessed')
print('Optimized facies classification accuracy = %.2f' % accuracy(cv_conf))
print('Optimized adjacent facies classification accuracy = %.2f' % accuracy_adjacent(cv_conf, adjacent_facies,0))
In [67]:
print('Unprocessed')
print('Optimized facies classification accuracy = %.2f' % accuracy(cv_conf_comp))
print('Optimized adjacent facies classification accuracy = %.2f' % accuracy_adjacent(cv_conf_comp, adjacent_facies,0))
Precision and recall are metrics that give more insight into how the classifier performs for individual facies. Precision is the probability that given a classification result for a sample, the sample actually belongs to that class. Recall is the probability that a sample will be correctly classified for a given class.
Precision and recall can be computed easily using the confusion matrix. The code to do so has been added to the display_confusion_matrix()
function:
In [68]:
print('Pre-processed')
display_cm(cv_conf, facies_labels,
display_metrics=True, hide_zeros=True)
In [69]:
print('Un-processed')
display_cm(cv_conf_comp, facies_labels,
display_metrics=True, hide_zeros=True)
To interpret these results, consider facies SS
. In our test set, if a sample was labeled SS
the probability the sample was correct is 0.8 (precision). If we know a sample has facies SS
, then the probability it will be correctly labeled by the classifier is 0.78 (recall). It is desirable to have high values for both precision and recall, but often when an algorithm is tuned to increase one, the other decreases. The F1 score combines both to give a single measure of relevancy of the classifier results.
These results can help guide intuition for how to improve the classifier results. For example, for a sample with facies MS
or mudstone, it is only classified correctly 57% of the time (recall). Perhaps this could be improved by introducing more training samples. Sample quality could also play a role. Facies BS
or bafflestone has the best F1
score and relatively few training examples. But this data was handpicked from other wells to provide training examples to identify this facies.
We can also consider the classification metrics when we consider misclassifying an adjacent facies as correct:
In [70]:
display_adj_cm(cv_conf, facies_labels, adjacent_facies,
display_metrics=True, hide_zeros=True)
In [71]:
display_adj_cm(cv_conf_comp, facies_labels, adjacent_facies,
display_metrics=True, hide_zeros=True)
Considering adjacent facies, the F1
scores for all facies types are above 0.9, except when classifying SiSh
or marine siltstone and shale. The classifier often misclassifies this facies (recall of 0.66), most often as wackestone.
These results are comparable to those reported in Dubois et al. (2007).
In [77]:
wells = processed_data["Well Name"].values
wells_comp = training_data["Well Name"].values
logo = LeaveOneGroupOut()
logo_comp = LeaveOneGroupOut()
In [95]:
f1_SVC = []
pred = {}
X = feature_vectors.as_matrix()
for train, test in logo.split(feature_vectors, correct_facies_labels, groups=wells):
well_name = wells[test[0]]
clf.fit(X[train], correct_facies_labels[train])
pred[well_name] = clf.predict(X[test])
sc = f1_score(correct_facies_labels[test], pred[well_name], labels = np.arange(10), average = 'micro')
print("{:>20s} {:.3f}".format(well_name, sc))
f1_SVC.append(sc)
print("-Average leave-one-well-out F1 Score: {0}".format(sum(f1_SVC)/(1.0*(len(f1_SVC)))))
In [96]:
f1_SVC_comp = []
pred_comp = {}
for train, test in logo_comp.split(scaled_features_comp, correct_facies_labels_comp, groups=wells_comp):
well_name = wells_comp[test[0]]
clf_comp.fit(scaled_features_comp[train], correct_facies_labels_comp[train])
pred_comp[well_name] = clf_comp.predict(scaled_features_comp[test])
sc = f1_score(correct_facies_labels_comp[test], pred_comp[well_name], labels = np.arange(10), average = 'micro')
print("{:>20s} {:.3f}".format(well_name, sc))
f1_SVC_comp.append(sc)
print("-Average leave-one-well-out F1 Score: {0}".format(sum(f1_SVC_comp)/(1.0*(len(f1_SVC_comp)))))
Now that we have a trained facies classification model we can use it to identify facies in wells that do not have core data. In this case, we will apply the classifier to two wells, but we could use it on any number of wells for which we have the same set of well logs for input.
This dataset is similar to the training data except it does not have facies labels. It is loaded into a dataframe called test_data
.
In [100]:
well_data = pd.read_csv('../validation_data_nofacies.csv')
well_data['Well Name'] = well_data['Well Name'].astype('category')
well_data['NM_M'] = enc.fit(well_data[['NM_M']]).transform(well_data[['NM_M']]).toarray()
well_features = well_data.drop(['Formation', 'Well Name','Depth'], axis=1)
The data needs to be scaled using the same constants we used for the training data.
In [103]:
well_features.describe()
Out[103]:
Finally we predict facies labels for the unknown data, and store the results in a Facies
column of the test_data
dataframe.
In [104]:
#predict facies of unclassified data
y_unknown = clf.predict(well_features)
well_data['Facies'] = y_unknown
well_data
Out[104]:
In [105]:
well_data['Well Name'].unique()
Out[105]:
We can use the well log plot to view the classification results along with the well logs.
In [110]:
make_facies_log_plot(
well_data[well_data['Well Name'] == 'STUART'],
facies_colors=facies.Colors)
In [111]:
make_facies_log_plot(
well_data[well_data['Well Name'] == 'CRAWFORD'],
facies_colors=facies.Colors)
Finally we can write out a csv file with the well data along with the facies classification results.
In [112]:
well_data['Facies'] = y_unknown+1
well_data.to_csv('well_data_with_facies.csv')
Amato del Monte, A., 2015. Seismic Petrophysics: Part 1, The Leading Edge, 34 (4). doi:10.1190/tle34040440.1
Bohling, G. C., and M. K. Dubois, 2003. An Integrated Application of Neural Network and Markov Chain Techniques to Prediction of Lithofacies from Well Logs, KGS Open-File Report 2003-50, 6 pp. pdf
Dubois, M. K., G. C. Bohling, and S. Chakrabarti, 2007, Comparison of four approaches to a rock facies classification problem, Computers & Geosciences, 33 (5), 599-617 pp. doi:10.1016/j.cageo.2006.08.011