In this article, I will show you how to build a model for the earthquake prediction task with machine learning and the Python programming language. Earthquake prediction is one of the biggest unsolved problems in the earth sciences.
As the use of technology has grown, many more seismic monitoring stations have appeared, so we can use machine learning and other data-driven methods to predict earthquakes.
An earthquake prediction model with machine learning
It is well known that if a disaster occurs in an area, it is likely to occur again. Some areas have frequent earthquakes, but this is only a relative quantity compared with other areas.
So predicting an earthquake from the date, time, latitude and longitude of past data is not a trend that follows like other things; it happens naturally.
I will start this task of building an earthquake prediction model by importing the necessary Python libraries:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Now let's load and read the dataset. The dataset I am using here can be downloaded easily from here:
</p>
data = pd.read_csv("database.csv")
data.columns
<p></p>
Index(['Date', 'Time', 'Latitude', 'Longitude', 'Type', 'Depth', 'Depth Error',
'Depth Seismic Stations', 'Magnitude', 'Magnitude Type',
'Magnitude Error', 'Magnitude Seismic Stations', 'Azimuthal Gap',
'Horizontal Distance', 'Horizontal Error', 'Root Mean Square', 'ID',
'Source', 'Location Source', 'Magnitude Source', 'Status'],
dtype='object')
<p>Now let's look at the main attributes of the earthquake data and create an object from these attributes, namely date, time, latitude, longitude, depth and magnitude:
</p>
data = data [['Date', 'Time', 'Latitude', 'Longitude', 'Depth', 'Magnitude']]
data.head ()
<p>
Because the data is random, we need to scale it according to the model inputs. Here we convert the given date and time to Unix time, which is in seconds and is a number. This can easily be used as input to the network we built:
</p>
import datetime
import time
timestamp = []
for d, t in zip(data['Date'], data['Time']):
try:
ts = datetime.datetime.strptime(d+' '+t, '%m/%d/%Y %H:%M:%S')
timestamp.append(time.mktime(ts.timetuple()))
except ValueError:
# print('ValueError')
timestamp.append('ValueError')
timeStamp = pd.Series(timestamp)
data['Timestamp'] = timeStamp.values
final_data = data.drop(['Date', 'Time'], axis=1)
final_data = final_data[final_data.Timestamp != 'ValueError']
final_data.head()
<p>
Visualizing the data
Now, before building the earthquake prediction model, let's plot the data on a world map that gives a clear picture of where earthquakes are frequent:
</p>
from mpl_toolkits.basemap import Basemap
m = Basemap(projection='mill',llcrnrlat=-80,urcrnrlat=80, llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')
longitudes = data["Longitude"].tolist()
latitudes = data["Latitude"].tolist()
#m = Basemap(width=12000000,height=9000000,projection='lcc',
#resolution=None,lat_1=80.,lat_2=55,lat_0=80,lon_0=-107.)
x,y = m(longitudes,latitudes)
fig = plt.figure(figsize=(12,10))
plt.title("All affected areas")
m.plot(x, y, "o", markersize = 2, color = 'blue')
m.drawcoastlines()
m.fillcontinents(color='coral',lake_color='aqua')
m.drawmapboundary()
m.drawcountries()
plt.show()
<p>
Splitting the dataset
Now, to build the earthquake prediction model, we need to split the data into Xs and ys, which will be fed into the model as inputs and outputs respectively.
The inputs here are TImestamp, Latitude and Longitude, and the outputs are Magnitude and Depth. I will split x and y into train and test with validation. The training set contains 80% and the test set contains 20%:
</p>
X = final_data[['Timestamp', 'Latitude', 'Longitude']]
y = final_data[['Magnitude', 'Depth']]
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape, y_train.shape, X_test.shape)
<p></p>
(18727, 3) (4682, 3) (18727, 2) (4682, 3)
<p>A neural network for earthquake prediction
Now I will create a neural network to fit the data from the training set. Our neural network will consist of three dense layers with 16, 16 and 2 nodes respectively. Relu and softmax will be used as activation functions:
</p>
from keras.models import Sequential
from keras.layers import Dense
def create_model(neurons, activation, optimizer, loss):
model = Sequential()
model.add(Dense(neurons, activation=activation, input_shape=(3,)))
model.add(Dense(neurons, activation=activation))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])
<p>I will now define the hyperparameters with two or more options to find the best fit:
</p>
from keras.wrappers.scikit_learn import KerasClassifier
model = KerasClassifier(build_fn=create_model, verbose=0)
# neurons = [16, 64, 128, 256]
neurons = [16]
# batch_size = [10, 20, 50, 100]
batch_size = [10]
epochs = [10]
# activation = ['relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear', 'exponential']
activation = ['sigmoid', 'relu']
# optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']
optimizer = ['SGD', 'Adadelta']
loss = ['squared_hinge']
param_grid = dict(neurons=neurons, batch_size=batch_size, epochs=epochs, activation=activation, optimizer=optimizer, loss=loss)
<p>Now we need to find the best-fitting model for the model above and get the mean test score and standard deviation of the best-fitting model:
</p>
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
grid_result = grid.fit(X_train, y_train)
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
<p></p>
Best: 0.957655 using {'activation': 'relu', 'batch_size': 10, 'epochs': 10, 'loss': 'squared_hinge', 'neurons': 16, 'optimizer': 'SGD'} 0.333316 (0.471398) with: {'activation': 'sigmoid', 'batch_size': 10, 'epochs': 10, 'loss': 'squared_hinge', 'neurons': 16, 'optimizer': 'SGD'} 0.000000 (0.000000) with: {'activation': 'sigmoid', 'batch_size': 10, 'epochs': 10, 'loss': 'squared_hinge', 'neurons': 16, 'optimizer': 'Adadelta'} 0.957655 (0.029957) with: {'activation': 'relu', 'batch_size': 10, 'epochs': 10, 'loss': 'squared_hinge', 'neurons': 16, 'optimizer': 'SGD'} 0.645111 (0.456960) with: {'activation': 'relu', 'batch_size': 10, 'epochs': 10, 'loss': 'squared_hinge', 'neurons': 16, 'optimizer': 'Adadelta'}
<p>In the step below, the best-fitting parameters are used with the same model to compute the score on the training data and the test data:
</p>
model = Sequential()
model.add(Dense(16, activation='relu', input_shape=(3,)))
model.add(Dense(16, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='SGD', loss='squared_hinge', metrics=['accuracy'])
model.fit(X_train, y_train, batch_size=10, epochs=20, verbose=1, validation_data=(X_test, y_test))
[test_loss, test_acc] = model.evaluate(X_test, y_test)
print("Evaluation result on Test Data : Loss = {}, accuracy = {}".format(test_loss, test_acc))
<p></p>
Evaluation result on Test Data : Loss = 0.5038455790406056, accuracy = 0.9241777017858995
<p>So we can see in the output above that our neural network model for earthquake prediction performs well. I hope you liked this article on how to build an earthquake prediction model with machine learning and the Python programming language.


Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.