pycharm用lstm预测,csv文件中,输入为x、y两列,输出为z,并图表展示loss和预测效果
时间: 2023-12-20 13:06:33 浏览: 72
好的,首先我们需要导入一些必要的库:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
```
然后读取csv文件:
```python
data = pd.read_csv('data.csv')
```
接着将x、y列作为输入数据,z列作为输出数据:
```python
x = data[['x', 'y']].values
y = data['z'].values
```
将数据集划分为训练集和测试集:
```python
train_size = int(len(x) * 0.7)
test_size = len(x) - train_size
x_train, x_test = x[0:train_size,:], x[train_size:len(x),:]
y_train, y_test = y[0:train_size], y[train_size:len(y)]
```
对输入数据进行归一化处理:
```python
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
```
我们现在可以定义LSTM模型了:
```python
model = Sequential()
model.add(LSTM(50, input_shape=(2, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
```
训练模型:
```python
history = model.fit(x_train.reshape(-1, 2, 1), y_train, epochs=100, batch_size=32, validation_data=(x_test.reshape(-1, 2, 1), y_test))
```
绘制模型的训练和验证集的loss曲线:
```python
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()
```
最后预测结果并将其与真实值绘制在同一张图上:
```python
train_predict = model.predict(x_train.reshape(-1, 2, 1))
test_predict = model.predict(x_test.reshape(-1, 2, 1))
train_predict = scaler.inverse_transform(train_predict)
y_train = scaler.inverse_transform([y_train])
test_predict = scaler.inverse_transform(test_predict)
y_test = scaler.inverse_transform([y_test])
plt.plot(y_train[0], label='train')
plt.plot(train_predict[:,0], label='train predict')
plt.plot(y_test[0], label='test')
plt.plot(test_predict[:,0], label='test predict')
plt.legend()
plt.show()
```
这样就完成了用LSTM预测并绘制图表的任务。
阅读全文