神经网络预测商品销售python代码
时间: 2023-12-01 08:42:15 浏览: 112
基于Python的预测商品销售数据【100010966】
以下是神经网络预测商品销售的Python代码:
```python
# 导入所需的库
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 读取数据
data = pd.read_csv('sales_data.csv', header=None)
# 数据预处理
all_data = data.values.astype('float32')
scaler = MinMaxScaler(feature_range=(0, 1))
all_data_normalized = scaler.fit_transform(all_data)
train_data = all_data_normalized[:900, :]
test_data = all_data_normalized[900:, :]
# 准备训练数据
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 5
trainX, trainY = create_dataset(train_data, look_back)
testX, testY = create_dataset(test_data, look_back)
# 创建模型
my_model = Sequential()
my_model.add(Dense(12, input_dim=look_back, activation='relu'))
my_model.add(Dense(1))
my_model.compile(loss='mean_squared_error', optimizer='adam')
my_model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 预测销售量
prediction = my_model.predict(testX)
print("prediction\n", prediction)
print("\nPrediction Shape-",prediction.shape)
# 对预测进行逆变换
new_array = np.array(all_data)
new_array = new_array.reshape(-1, 1)
prediction_copies_array = np.repeat(new_array, 5, axis=-1)
y_pred_future_30_days = scaler.inverse_transform(np.reshape(prediction_copies_array,(len(new_array),5)))[:,0]
print(y_pred_future_30_days)
```
阅读全文