地震时间序列预测模型代码
时间: 2023-10-01 09:04:25 浏览: 148
下面是一个基于LSTM的地震时间序列预测模型的代码示例。代码使用Python和Keras库编写。
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM
from sklearn.preprocessing import MinMaxScaler
# 读入地震时间序列数据
data = pd.read_csv('earthquake.csv', parse_dates=['date'])
data = data.set_index('date')
data = data.drop(['id', 'latitude', 'longitude', 'depth', 'mag'], axis=1)
# 数据标准化
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data) * 0.7)
test_size = len(data) - train_size
train, test = data[0:train_size,:], data[train_size:len(data),:]
# 将时间序列转换为监督学习问题
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 10
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# 调整输入形状
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))
# 创建LSTM模型
model = Sequential()
model.add(LSTM(4, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 预测并反标准化
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
# 计算均方根误差
trainScore = np.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = np.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))
```
代码中使用了一个10步长的滑动窗口来将时间序列数据转换为监督学习问题,然后使用LSTM模型进行训练和预测。最后计算了训练集和测试集的均方根误差作为模型性能的评估指标。需要注意的是,这只是一个示例代码,实际应用时需要根据具体数据集进行调整。
阅读全文