import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
# 1.数据处理
data = [
[23067, 1, 3, 12, 19, 28, 32, 14],
[23066, 2, 7, 8, 10, 26, 31, 6],
[23065, 2, 14, 17, 20, 26, 33, 14],
[23064, 1, 7, 11, 12, 16, 18, 4],
[23063, 4, 8, 17, 20, 22, 27, 13],
]
data = np.array(data)
num_periods = 5 # 目标预测的期数
def preprocess_data(data, num_periods):
x_data, y_data = data[:, 1:], []
x_data = x_data / 33.0 - 0.5 # 归一化
for i in range(len(x_data)-num_periods):
y_data.append(x_data[i:i+num_periods].flatten())
x_data = x_data[:-num_periods]
return np.array(x_data).reshape((-1, 1, 7)), np.array(y_data)
x_train, y_train = preprocess_data(data, num_periods)
# 2.构建和训练LSTM模型
model = Sequential()
model.add(LSTM(32, input_shape=(1, 7), return_sequences=True))
model.add(LSTM(16))
model.add(Dense(35, activation='sigmoid'))
model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=100, verbose=1)
# 3.进行预测
def predict_next_periods(model, last_period, num_periods):
predictions = []
for _ in range(num_periods):
next_period = model.predict(last_period[np.newaxis])
predictions.append(next_period[0])
last_period = np.roll(last_period, -7)
last_period[-7:] = next_period
return predictions
predicted_next_periods = predict_next_periods(model, x_train[-1], 5)
# 4.输出预测结果
for period in predicted_next_periods:
period = (period + 0.5) * 33.0
red = np.sort(period[:6].astype(int))
blue = period[6].astype(int)
print("Predicted Red Balls: {} Blue Ball: {}".format(red, blue))