Paste: z

Author: z
Mode: python
Date: Tue, 18 Jul 2023 11:29:35
Plain Text |
import tensorflow as tf
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

# 加载数据集
data = np.loadtxt('dianli.csv', delimiter=',')
X = data[:, :-1]  # 特征矩阵
y = data[:, -1]  # 目标变量

# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
X_scaled = scaler.fit_transform(X)

# 划分训练集和测试集
train_size = int(len(X_scaled) * 0.8)
train_X, test_X = X_scaled[:train_size], X_scaled[train_size:]
train_y, test_y = y[:train_size], y[train_size:]

# 创建时间序列数据集
def create_time_series_dataset(X, y, time_steps):
    Xs, ys = [], []
    for i in range(len(X) - time_steps):
        Xs.append(X[i:i+time_steps])
        ys.append(y[i+time_steps])
    return np.array(Xs), np.array(ys)

time_steps = 10  # 设置时间步长
train_X, train_y = create_time_series_dataset(train_X, train_y, time_steps)
test_X, test_y = create_time_series_dataset(test_X, test_y, time_steps)

# 定义LSTM模型
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(64, activation='relu', input_shape=(time_steps, train_X.shape[2])),
    tf.keras.layers.Dense(1)
])

# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')

# 训练模型
model.fit(train_X, train_y, epochs=100, batch_size=32, verbose=0)

# 在测试集上进行预测
y_pred = model.predict(test_X)

# 评估模型
loss = model.evaluate(test_X, test_y, verbose=0)
print("Loss:", loss)

# 打印预测结果
print("Predictions:", y_pred)

New Annotation

Summary:
Author:
Mode:
Body: