极限学习机股票预测的Python代码
时间: 2024-04-17 07:22:29 浏览: 97
极限学习机(Extreme Learning Machine,ELM)是一种机器学习算法,可以用于股票预测。下面是一个简单的使用Python实现的ELM股票预测代码示例:
```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Ridge
# 极限学习机类
class ELM:
def __init__(self, hidden_size):
self.hidden_size = hidden_size
def fit(self, X, y):
self.X = X
self.y = y
self.input_size = X.shape
self.output_size = y.shape
self.W = np.random.randn(self.input_size, self.hidden_size)
self.b = np.random.randn(self.hidden_size)
H = np.dot(X, self.W) + self.b
self.beta = np.dot(np.linalg.pinv(H), y)
def predict(self, X):
H = np.dot(X, self.W) + self.b
y_pred = np.dot(H, self.beta)
return y_pred
# 加载数据
data = np.loadtxt('stock_data.csv', delimiter=',')
X = data[:, :-1]
y = data[:, -1:]
# 数据归一化
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
y_scaled = scaler.fit_transform(y)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size=0.2, random_state=42)
# 构建ELM模型并训练
elm = ELM(hidden_size=100)
elm.fit(X_train, y_train)
# 预测并计算均方误差
y_pred = elm.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("均方误差:", mse)
# 反归一化
y_pred = scaler.inverse_transform(y_pred)
y_test = scaler.inverse_transform(y_test)
# 输出预测结果
print("预测结果:")
for i in range(len(y_pred)):
print("预测值:", y_pred[i], "真实值:", y_test[i])
```
这段代码使用了`numpy`、`sklearn`库来实现ELM算法。首先,加载股票数据并进行数据归一化处理。然后,将数据划分为训练集和测试集。接下来,构建ELM模型并使用训练集进行训练。最后,使用测试集进行预测,并计算均方误差。最后,将预测结果反归一化,并输出预测值和真实值。
阅读全文