lstm神经网络python
时间: 2023-11-20 19:57:32 浏览: 113
lstm 网络的资源,python实现
LSTM(Long Short-Term Memory)是一种特殊的循环神经网络,它可以更好地处理和预测时间序列数据。下面是一个使用Python实现LSTM神经网络的示例:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载数据
data = pd.read_csv('data.csv', header=None)
dataset = data.values
dataset = dataset.astype('float32')
# 数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# 划分训练集和测试集
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
# 创建数据集
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 1
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# 转换为3D格式 [样本数,时间步长,特征数]
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 = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))
```
这个示例中,我们使用了Keras库来创建LSTM模型。首先,我们加载数据并进行归一化处理。然后,我们将数据集划分为训练集和测试集,并创建数据集。接下来,我们将数据集转换为3D格式,以便可以输入到LSTM模型中。然后,我们创建LSTM模型并训练它。最后,我们使用模型进行预测,并计算误差。
阅读全文