请利用Python绘制出极限学习机预测太阳黑子数的图
时间: 2024-03-22 08:38:14 浏览: 124
好的,以下是利用Python绘制出极限学习机预测太阳黑子数的图的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from elm import ELMRegressor
# 加载数据
data = np.loadtxt('sunspot.txt', delimiter=',', usecols=[3])
# 数据归一化
scaler = MinMaxScaler(feature_range=(-1, 1))
data = scaler.fit_transform(data.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 构建特征和标签
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset) - look_back):
X.append(dataset[i:i+look_back, 0])
Y.append(dataset[i+look_back, 0])
return np.array(X), np.array(Y)
look_back = 12
X_train, Y_train = create_dataset(train_data, look_back)
X_test, Y_test = create_dataset(test_data, look_back)
# 构建ELM模型
elm = ELMRegressor(n_hidden=20)
elm.fit(X_train, Y_train)
# 预测
train_predict = elm.predict(X_train)
test_predict = elm.predict(X_test)
# 反归一化
train_predict = scaler.inverse_transform(train_predict.reshape(-1, 1))
Y_train = scaler.inverse_transform(Y_train.reshape(-1, 1))
test_predict = scaler.inverse_transform(test_predict.reshape(-1, 1))
Y_test = scaler.inverse_transform(Y_test.reshape(-1, 1))
# 计算均方误差
train_rmse = np.sqrt(mean_squared_error(Y_train, train_predict))
test_rmse = np.sqrt(mean_squared_error(Y_test, test_predict))
print('Train RMSE: %.3f' % train_rmse)
print('Test RMSE: %.3f' % test_rmse)
# 绘制图像
train_predict_plot = np.empty_like(data)
train_predict_plot[:, :] = np.nan
train_predict_plot[look_back:len(train_predict)+look_back, :] = train_predict
test_predict_plot = np.empty_like(data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict)+(look_back*2)+1:len(data)-1, :] = test_predict
plt.plot(scaler.inverse_transform(data))
plt.plot(train_predict_plot)
plt.plot(test_predict_plot)
plt.show()
```
其中,代码中使用了`elm`库,该库提供了极限学习机的实现。在代码中,我们首先加载了太阳黑子数的数据,并对其进行了归一化处理。然后,将数据划分为训练集和测试集,并使用`create_dataset`函数构建特征和标签。接着,我们使用`ELMRegressor`构建了ELM模型,并对其进行了训练和预测。最后,我们反归一化预测结果,并计算了均方误差。最后,通过`matplotlib`库绘制了训练集、测试集和预测结果的图像。
阅读全文