赞
踩
generate_sin_wave
函数生成一个正弦波数据序列。X.append(df["Value"][i:i+seq_length].values)
确保提取的是序列的值。完整代码 import numpy as np import pandas as pd import matplotlib.pyplot as plt from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense # 生成正弦波数据 def generate_sin_wave(seq_length, num_sequences): x = np.linspace(0, 100, seq_length * num_sequences) y = np.sin(x) return y seq_length = 50 # 每个序列的长度 num_sequences = 100 # 序列数量 data = generate_sin_wave(seq_length, num_sequences) # 转换为 DataFrame df = pd.DataFrame(data, columns=["Value"]) # 创建输入和输出 X = [] y = [] for i in range(len(df) - seq_length): X.append(df["Value"][i:i+seq_length].values) # 改动在这里,确保提取的是值 y.append(df["Value"][i+seq_length]) X = np.array(X) y = np.array(y) # 数据形状调整 X = np.reshape(X, (X.shape[0], X.shape[1], 1)) # 构建LSTM模型 model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(seq_length, 1))) model.add(LSTM(50)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') # 打印模型结构 model.summary() # 拆分训练和测试数据 train_size = int(len(X) * 0.8) X_train, X_test = X[:train_size], X[train_size:] y_train, y_test = y[:train_size], y[train_size:] # 训练模型 model.fit(X_train, y_train, epochs=20, batch_size=32, validation_data=(X_test, y_test)) # 预测 predictions = model.predict(X_test) # 绘制结果 plt.figure(figsize=(12, 6)) plt.plot(y_test, label='True Values') plt.plot(predictions, label='Predictions') plt.legend() plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。