import pandas as pd from pyecharts import options as opts from pyecharts.charts import Line # 读取Excel文件 data = pd.read_excel('6004020918.xlsx') # 提取数据 week = data['week'] need = data['need'] # 定义三步指数平滑函数 def triple_exponential_smoothing(series, alpha, beta, gamma, n_preds): result = [series[0]] season_length = len(series) // n_preds # 初始化水平、趋势和季节性指数 level, trend, season = series[0], series[1] - series[0], sum(series[:season_length]) / season_length for i in range(1, len(series) + n_preds): if i >= len(series): # 预测新值 m = i - len(series) + 1 result.append(level + m * trend + season) else: # 更新水平、趋势和季节性指数 value = series[i] last_level, level = level, alpha * (value - season) + (1 - alpha) * (level + trend) trend = beta * (level - last_level) + (1 - beta) * trend season = gamma * (value - level) + (1 - gamma) * season result.append(level + trend + season) return result # 设置三步指数平滑法参数 alpha = 0.2 beta = 0.5 gamma = 0.4 n_preds = 177 # 预测的值数量 # 进行三步指数平滑预测 predictions = triple_exponential_smoothing(need[:177], alpha, beta, gamma, n_preds) # 创建折线图对象 line = Line() line.set_global_opts( title_opts=opts.TitleOpts(title='时间序列预测分析'), legend_opts=opts.LegendOpts(pos_top='5%'), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross") ) # 添加预测值数据 line.add_xaxis(week[:177]) line.add_yaxis('预测值', predictions, is_smooth=True, label_opts=opts.LabelOpts(is_show=False)) # 添加实际值数据 line.add_yaxis('实际值', need[:177], is_smooth=True, label_opts=opts.LabelOpts(is_show=False)) # 生成HTML文件 line.render('time_series_forecast.html')修改代码,使预测出的为负的数据取0
时间: 2024-04-17 21:26:03 浏览: 98
你可以在三步指数平滑预测的结果中添加一个条件判断语句,将负值改为0。修改后的代码如下所示:
```python
# 进行三步指数平滑预测
predictions = triple_exponential_smoothing(need[:177], alpha, beta, gamma, n_preds)
# 将负值改为0
predictions = [max(0, pred) for pred in predictions]
# 创建折线图对象
line = Line()
line.set_global_opts(
title_opts=opts.TitleOpts(title='时间序列预测分析'),
legend_opts=opts.LegendOpts(pos_top='5%'),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross")
)
# 添加预测值数据
line.add_xaxis(week[:177])
line.add_yaxis('预测值', predictions, is_smooth=True, label_opts=opts.LabelOpts(is_show=False))
# 添加实际值数据
line.add_yaxis('实际值', need[:177], is_smooth=True, label_opts=opts.LabelOpts(is_show=False))
# 生成HTML文件
line.render('time_series_forecast.html')
```
这样就可以将预测出的负值改为0,并生成对应的HTML文件。
阅读全文