1、想给遍历数据增加循环,报错
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
for i in range(57, 60):
rows_to_read = i
df = df[:rows_to_read]
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
# 初始化SARIMA模型
# 这里的order和seasonal_order参数需要根据你的数据进行调整
model = SARIMAX(df['销售金额'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
# 训练模型
model_fit = model.fit(disp=False)
# 预测未来12个月的销售金额
forecast = model_fit.predict(start=len(df), end=len(df)+11)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast.values
})
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel('预测销售数据.xlsx', index=False)
2、报错
raise KeyError(key) from err
KeyError: '年月'
这个错误是因为在你的循环中,你在每次迭代时都试图将'年月'列设置为索引。然而,一旦你在第一次迭代中将'年月'列设置为索引,它就不再是数据框的一部分,所以在后续的迭代中,你不能再次将它设置为索引。
你可以通过将读取和预处理数据的步骤移出循环来解决这个问题。这样,你只需要一次读取和预处理数据,然后在循环中进行模型训练和预测。以下是修改后的代码:
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
for i in range(57, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 初始化SARIMA模型
# 这里的order和seasonal_order参数需要根据你的数据进行调整
model = SARIMAX(df_subset['销售金额'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
# 训练模型
model_fit = model.fit(disp=False)
# 预测未来12个月的销售金额
forecast = model_fit.predict(start=len(df_subset), end=len(df_subset)+11)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast.values
})
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
在这个修改后的代码中,我创建了一个新的数据框df_subset
,它包含了你想要在每次迭代中使用的数据的子集。然后,我使用这个子集来训练模型和进行预测。我还修改了保存预测结果的文件名,使其包含当前迭代的编号,这样你可以为每次迭代生成一个新的文件。
情不自禁的用昂贵的GPT4赞美了一下他。。。。。。。。
3、太强了,跑出来了
4、写代码
自适应增强 (AdaBoost)
指数平滑法(ExponentialSmoothing)
移动平均法 (Moving Averages)
机器学习方法
深度学习方法
5、自适应增强 (AdaBoost)
用自适应增强 (AdaBoost)的时间序列预测数据分析方法,改写上面的代码
# -*- coding: utf-8 -*-
"""
Created on Wed May 24 17:32:17 2023
@author: Administrator
"""
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
import numpy as np
from sklearn.ensemble import AdaBoostRegressor
from sklearn.model_selection import train_test_split
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
for i in range(55, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 创建滞后变量
for i in range(1, 13):
df[f'销售金额_lag_{i}'] = df['销售金额'].shift(i)
# 删除含有NaN的行
df = df.dropna()
# 划分训练集和测试集
X = df.drop('销售金额', axis=1)
y = df['销售金额']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化AdaBoost模型
model = AdaBoostRegressor(n_estimators=100, random_state=42)
# 训练模型
model.fit(X_train, y_train)
# 预测未来12个月的销售金额
forecast = model.predict(X_test)
# 打印预测结果
print(forecast)
# # 初始化SARIMA模型
# # 这里的order和seasonal_order参数需要根据你的数据进行调整
# model = SARIMAX(df_subset['销售金额'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
# # 训练模型
# model_fit = model.fit(disp=False)
# # 预测未来12个月的销售金额
# forecast = model_fit.predict(start=len(df_subset), end=len(df_subset)+11)
# # 创建一个新的DataFrame来保存预测结果
# df_forecast = pd.DataFrame({
# '年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
# '预测销售金额': forecast.values
# })
# # 创建一个新的DataFrame来保存预测结果
# df_forecast = pd.DataFrame({
# '年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
# '预测销售金额': forecast
# })
# print(df_forecast)
# # print(df_forecast.style.format({'预测销售金额': '{:.2f}'}))
# # 打印格式化的数据帧
# # print(df_forecast.style.format({'预测销售金额': '{:.2f}'}).render())
# # 将预测结果保存到新的Excel文件中
# df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
6、报错太多,换一个
7、用指数平滑法(ExponentialSmoothing)的时间序列预测数据分析方法,改写上面的代码
你可以使用`statsmodels`库中的`ExponentialSmoothing`类来实现指数平滑法。以下是修改后的代码:
```python
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
for i in range(55, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 初始化ExponentialSmoothing模型
# 这里的trend和seasonal参数需要根据你的数据进行调整
model = ExponentialSmoothing(df_subset['销售金额'], trend='add', seasonal='add', seasonal_periods=12)
# 训练模型
model_fit = model.fit()
# 预测未来12个月的销售金额
forecast = model_fit.predict(start=len(df_subset), end=len(df_subset)+11)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast.values
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
```
请注意,`ExponentialSmoothing`模型的`seasonal_periods`参数需要根据你的数据进行调整。在这个例子中,我假设你的数据具有年度季节性,所以我设置`seasonal_periods=12`。如果你的数据具有其他类型的季节性,你需要相应地调整这个参数。
8、用去年数据测试预测的准确性,与实际的对比,效果不太好
意料之中,指数平滑效果不太好
1月份 | 82.624% |
---|---|
2月份 | 82.057% |
3月份 | 95.739% |
4月份 | 95.931% |
5月份 | 106.503% |
6月份 | 107.516% |
7月份 | 105.668% |
8月份 | 98.078% |
9月份 | 105.330% |
10月份 | 105.226% |
11月份 | 101.830% |
12月份 | 102.693% |
9、用移动平均法 (Moving Averages)的时间序列预测数据分析方法,改写上面的代码
了解,这段代码是用来在不同的时间点进行预测并将结果保存到不同的Excel文件中。以下是将这段代码加入到移动平均法预测中的完整代码:
```python
import pandas as pd
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
for i in range(48, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 计算移动平均
df_subset['移动平均'] = df_subset['销售金额'].rolling(window=12).mean()
# 预测未来12个月的销售金额
forecast = df_subset['移动平均'].iloc[-1]
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': [forecast]*12 # 使用最后一个移动平均值作为所有未来月份的预测值
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
```
请注意,这段代码会在每次循环时都计算移动平均并进行预测,然后将预测结果保存到一个新的Excel文件中。文件名将包含当前循环的索引值,以便你可以区分不同的预测结果。
10、移动平均法预测的数值都一样。。
修改最后36个月的移动平均值来预测未来12个月的预测值
11、
# -*- coding: utf-8 -*-
"""
Created on Thu May 25 10:47:41 2023
@author: Administrator
"""
import pandas as pd
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式
df['年月'] = pd.to_datetime(df['年月'])
# 将年月列设置为索引
df.set_index('年月', inplace=True)
for i in range(48, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 计算移动平均
df_subset['移动平均'] = df_subset['销售金额'].rolling(window=36).mean()
# 预测未来12个月的销售金额
forecast = df_subset['移动平均'].iloc[-1]
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': [forecast]*12 # 使用最后一个移动平均值作为所有未来月份的预测值
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
12、用去年数据测试预测的准确性,与实际的对比,效果不太好
但是正确率可见的提高。。
1月份 | 114.81% |
---|---|
2月份 | 113.45% |
3月份 | 110.41% |
4月份 | 107.72% |
5月份 | 108.48% |
6月份 | 105.97% |
7月份 | 103.17% |
8月份 | 102.22% |
9月份 | 103.81% |
10月份 | 102.86% |
11月份 | 100.57% |
12月份 | 101.31% |
13、用自适应增强 (AdaBoost)的时间序列预测数据分析方法,改写上面的代码
14、
import numpy as np
from sklearn.ensemble import AdaBoostRegressor
from sklearn.model_selection import train_test_split
import pandas as pd
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式,并设为索引
df['年月'] = pd.to_datetime(df['年月'])
df.set_index('年月', inplace=True)
# 为了进行时间序列预测,我们需要为每个日期指定一个整数值
df['时间序列'] = range(0, len(df))
# 将数据集分割为特征和目标值
X = df['时间序列'].values.reshape(-1, 1)
y = df['销售金额'].values
# 使用80%的数据进行训练,其余的用于测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 创建并拟合AdaBoost模型
model = AdaBoostRegressor(n_estimators=100, random_state=0)
model.fit(X_train, y_train)
# 对测试数据集进行预测,并查看预测结果
y_pred = model.predict(X_test)
print(y_pred)
# 预测未来12个月的销售金额
future_months = np.array(range(max(df['时间序列']) + 1, max(df['时间序列']) + 13)).reshape(-1, 1)
forecast = model.predict(future_months)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel('预测销售数据_AdaBoost.xlsx', index=False)
14.1、
您希望在循环内部对每个子集进行训练并进行预测。请参考以下修改后的代码:
```python
from sklearn.ensemble import AdaBoostRegressor
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式,并设为索引
df['年月'] = pd.to_datetime(df['年月'])
df.set_index('年月', inplace=True)
# 为了进行时间序列预测,我们需要为每个日期指定一个整数值
df['时间序列'] = range(0, len(df))
for i in range(48, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 将数据集分割为特征和目标值
X = df_subset['时间序列'].values.reshape(-1, 1)
y = df_subset['销售金额'].values
# 使用80%的数据进行训练,其余的用于测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 创建并拟合AdaBoost模型
model = AdaBoostRegressor(n_estimators=100, random_state=0)
model.fit(X_train, y_train)
# 对测试数据集进行预测,并查看预测结果
y_pred = model.predict(X_test)
print(y_pred)
# 预测未来12个月的销售金额
future_months = np.array(range(max(df_subset['时间序列']) + 1, max(df_subset['时间序列']) + 13)).reshape(-1, 1)
forecast = model.predict(future_months)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_AdaBoost_{i}.xlsx', index=False)
```
在上述代码中,我们将训练和预测的过程放入了一个`for`循环内,这个循环会遍历每个48至60月的子集,并对每个子集进行预测。预测结果保存在一个单独的Excel文件中,文件名依据迭代的`i`值进行标记。
15、上面代码预测的数值都是一样的呢?
在时间序列预测中,使用AdaBoostRegressor可能不是最好的选择。原因在于,它是一种集成学习模型,主要用于解决分类和回归问题,而不是时间序列预测问题。AdaBoostRegressor并不具备处理时间序列数据的特性,如趋势、季节性等。
对于时间序列预测,常用的方法有ARIMA、Exponential Smoothing、Prophet、LSTM等。这些模型都考虑了时间序列的特性,可以更好地预测未来的值。
因此,如果你发现用AdaBoostRegressor预测的未来数值都是一样的,可能是由于模型并不能很好地捕捉时间序列的动态变化,导致预测效果不佳。我建议使用专门用于时间序列预测的模型,如上述的ARIMA、Exponential Smoothing、Prophet、LSTM等。
15、1用去年数据测试预测的准确性,与实际的对比,
1月份 | 106.44% |
---|---|
2月份 | 111.48% |
3月份 | 100.18% |
4月份 | 96.73% |
5月份 | 100.13% |
6月份 | 99.51% |
7月份 | 94.12% |
8月份 | 97.36% |
9月份 | 102.13% |
10月份 | 100.49% |
11月份 | 99.77% |
12月份 | 101.31% |
16、用LSTM的时间序列预测数据分析方法,改写上面的代码
首先,你需要安装`tensorflow`和`keras`这两个Python库,因为LSTM是由它们提供的。
以下是一个使用LSTM进行时间序列预测的简单示例。在这个示例中,我会创建一个函数来预处理数据,然后使用一个简单的LSTM网络进行预测。
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式,并设为索引
df['年月'] = pd.to_datetime(df['年月'])
df.set_index('年月', inplace=True)
# 将销售数据归一化到0-1之间
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(df)
# 创建LSTM输入数据(时序数据)
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 3
trainX, trainY = create_dataset(dataset, look_back)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
# 创建并拟合LSTM网络
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 预测未来12个月的销售金额
inputs = np.array([i for i in range(len(df)-look_back, len(df)+12)]).reshape(-1,1)
inputs = scaler.transform(inputs)
testX = np.reshape(inputs, (inputs.shape[0], 1, inputs.shape[1]))
predictions = model.predict(testX)
predictions = scaler.inverse_transform(predictions)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': predictions[-12:].ravel() # 使用LSTM预测值
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel('预测销售数据_LSTM.xlsx', index=False)
```
这个示例的主要部分是创建和训练一个LSTM模型。这个模型有一个LSTM层和一个密集输出层。我们使用mean_squared_error作为损失函数,优化器使用adam。训练周期数(epochs)和批量大小(batch_size)可能需要根据你的具体数据进行调整。
此外,我也创建了一个新的数据处理函数,用于生成LSTM模型需要的数据格式。
最后,我使用训练好的模型进行
预测,预测的结果需要使用之前的归一化对象进行反归一化,恢复到原始的销售额级别。
17、用Exponential Smoothing指数平滑的时间序列预测数据分析方法,改写下面的代码
你可以使用`statsmodels`库中的`ExponentialSmoothing`类来执行指数平滑预测。请注意,该库可能需要首先安装。这里是如何修改你的代码来使用Exponential Smoothing:
```python
import pandas as pd
from statsmodels.tsa.api import ExponentialSmoothing
# 读取Excel文件
df = pd.read_excel('销售数据.xlsx')
# 将年月列转换为时间格式,并设为索引
df['年月'] = pd.to_datetime(df['年月'])
df.set_index('年月', inplace=True)
for i in range(48, 60):
rows_to_read = i
df_subset = df[:rows_to_read]
# 创建并拟合ExponentialSmoothing模型
model = ExponentialSmoothing(df_subset['销售金额'], trend='add', seasonal='add', seasonal_periods=12)
model_fit = model.fit()
# 预测未来12个月的销售金额
forecast = model_fit.forecast(steps=12)
# 创建一个新的DataFrame来保存预测结果
df_forecast = pd.DataFrame({
'年月': pd.date_range(start=df_subset.index[-1] + pd.DateOffset(months=1), periods=12, freq='MS'),
'预测销售金额': forecast
})
print(df_forecast)
# 将预测结果保存到新的Excel文件中
df_forecast.to_excel(f'预测销售数据_{i}.xlsx', index=False)
```
这段代码假设你的数据具有趋势和季节性,因此在`ExponentialSmoothing`的初始化参数中,设置了`trend='add'`和`seasonal='add'`,同时设定`seasonal_periods=12`代表一年的季节性周期。如果你的数据没有明显的趋势或季节性,你可能需要调整这些参数。这是一个比较基础的Exponential Smoothing模型,更复杂的模型可能需要更多的参数调整。
18、计算一下财务平均算法
19、汇总几种预测的正确率
财务平均 | auto_arima | Prophet | SARIMAX | 指数平滑 | 移动平均 | AdaBoost回归器 | |
---|---|---|---|---|---|---|---|
1月 | 125.99% | 111.33% | 89.96% | 104.03% | 82.62% | 114.81% | 106.44% |
2月 | 101.72% | 114.09% | 91.14% | 104.32% | 82.06% | 113.45% | 111.48% |
3月 | 95.11% | 106.62% | 94.35% | 108.11% | 95.74% | 110.41% | 100.18% |
4月 | 100.20% | 102.77% | 95.11% | 92.55% | 95.93% | 107.72% | 96.73% |
5月 | 96.73% | 105.11% | 100.86% | 111.29% | 106.50% | 108.48% | 100.13% |
6月 | 95.29% | 103.00% | 102.17% | 107.02% | 107.52% | 105.97% | 99.51% |
7月 | 96.89% | 99.50% | 100.96% | 98.15% | 105.67% | 103.17% | 94.12% |
8月 | 101.24% | 99.93% | 97.97% | 92.77% | 98.08% | 102.22% | 97.36% |
9月 | 101.26% | 105.69% | 101.45% | 109.29% | 105.33% | 103.81% | 102.13% |
10月 | 99.67% | 102.78% | 102.15% | 105.27% | 105.23% | 102.86% | 100.49% |
11月 | 101.08% | 99.30% | 101.21% | 98.02% | 101.83% | 100.57% | 99.77% |
12月 | 100.00% | 101.39% | 102.10% | 102.61% | 102.69% | 101.31% | 101.31% |
标准差 | 8.15% | 4.62% | 4.50% | 6.18% | 8.79% | 4.76% | 4.52% |
平均值 | 101.27% | 104.29% | 98.29% | 102.79% | 99.10% | 106.23% | 100.81% |