import pandas as pd
import numpy as np
# 商品名
stuff_name = "Feeder40"
# 读取数据
data = pd.read_csv("老师原数据.csv")
# 时间里有0000异常值,删除
data = data[data["Date Invoiced"] != "0000-00-00"]
# 转为时间类型
data["Date Invoiced"] = pd.to_datetime(data["Date Invoiced"])
data = data.set_index("Date Invoiced")
data = data[data["Order Line SKU"] == stuff_name]
# 按周分组计数
data = data.resample("W").sum()["Order Line Qty"]
data = pd.DataFrame(data)
# 标准化
from sklearn.preprocessing import StandardScaler
ss_x = StandardScaler()
data = ss_x.fit_transform(data)
# 构造时间序列
def series_to_supervised(data, n_in, n_out, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, names = list(), list()
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
for i in range(0, n_out, 1):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
agg = pd.concat(cols, axis=1)
agg.columns = names
if dropnan:
agg.dropna(inplace=True)
return agg
# 前7天预测后1天
data_series = series_to_supervised(data, 7, 1)
x = data_series.iloc[:, :-1]
y = pd.DataFrame(data_series.iloc[:, -1])
'''from sklearn.preprocessing import StandardScaler
ss_x = StandardScaler()
x = ss_x.fit_transform(x)
ss_y = StandardScaler()
y = ss_y.fit_transform(y)'''
# 10%训练集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1)
x_train = np.array(x_train).reshape(x_train.shape[0], 1, x_train.shape[1])
x_test = np.array(x_test).reshape(x_test.shape[0], 1, x_test.shape[1])
# 用tensorflow keras搭建lstm神经网络
from keras.callbacks import EarlyStopping
from keras.layers import *
from keras import Input
from keras import Model
es = EarlyStopping(monitor="val_loss", patience=5)
x = Input(shape=(1, x.shape[1]))
lstm_structure = LSTM(1, input_shape=(1, x.shape[1]))(x)
lstm_structure = Dense(32, activation='relu')(lstm_structure)
lstm_structure = Dense(32, activation='relu')(lstm_structure)
output = Dense(1)(lstm_structure)
model = Model(x, output)
model.compile(optimizer='rmsprop', loss='mae', metrics=['mse'])
history = model.fit(x_train, y_train, epochs=200, batch_size=5, validation_split=0.2, callbacks=[es])
y_pred = model.predict(x_test)
# 画图
from matplotlib import pyplot as plt
plt.plot(ss_x.inverse_transform(y_test))
plt.plot(ss_x.inverse_transform(y_pred.reshape(-1, 1)))
'''plt.plot(np.array(y_test))
plt.plot(np.array(y_pred))'''
plt.title(stuff_name)
plt.xlabel("sample")
plt.ylabel("amount")
plt.legend(["true value", "predicted value"])
plt.savefig(stuff_name + ".png")
plt.show()
# 未来14天
future_days = 14
amounts = data.flatten()
for i in range(future_days):
last_days = amounts[-7:]
next_day = model.predict(last_days.reshape(1, 1, -1)).flatten()[0]
# next_day = ss_x.inverse_transform(next_day).round()
amounts = np.append(amounts, next_day)
result = list(ss_x.inverse_transform(amounts.reshape(-1, 1)).flatten())
result = [int(round(i)) for i in result]
print(result[-future_days:])
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
Python 计算机毕业设计 基于深度学习的商品销量LSTM时间序列预测 根据地点品牌时间等信息预测未来的商品销量 matplotlib统计图 折线图 tensorflow keras Order Line SKU Order Line Qty Sales Channel Ship Country Ship City Ship Post Code Ship State Ship State Name Brand Date Invoiced numpy pandas matplotlib 人工智能 机器学习 深度学习 数据分析 数据挖掘 包含可用数据
资源推荐
资源详情
资源评论
收起资源包目录
902.rar (7个子文件)
RH01.png 16KB
老师原数据.csv 10.46MB
ST-25.png 18KB
code接口.py 3KB
code.ipynb 54KB
Feeder40.png 19KB
codepy.py 3KB
共 7 条
- 1
HinomotoOniko
- 粉丝: 1883
- 资源: 139
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页