太阳黑子lstm时间序列预测python
时间: 2023-12-04 11:41:38 浏览: 112
太阳黑子是指太阳表面上的黑色斑点,它们的数量和活动程度与太阳活动周期有关。LSTM是一种递归神经网络,可以用于时间序列预测。因此,可以使用LSTM来预测太阳黑子的数量。以下是使用Python进行太阳黑子LSTM时间序列预测的示例代码:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
# 读取数据
df = pd.read_csv('sunspots.csv')
# 将数据转换为numpy数组
data = df['Monthly Mean Total Sunspot Number'].values
data = data.reshape(-1, 1)
# 将数据缩放到0和1之间
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 将数据分为训练集和测试集
train_size = int(len(data) * 0.67)
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 = 12
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# 将数据重塑为LSTM的输入格式
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# 创建LSTM模型
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
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))
# 绘制预测结果
trainPredictPlot = np.empty_like(data)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
testPredictPlot = np.empty_like(data)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(data)-1, :] = testPredict
plt.plot(scaler.inverse_transform(data))
plt.plot(trainPredictPlot)
plt.plot(testPredictPlot)
plt.show()
```
阅读全文