# 设置迭代器 classMyDataSet(object): def__init__(self,seq,ws=6): # ws是滑动窗口大小 self.ori=[i for i in seq[:ws]] self.label=[i for i in seq[ws:]] self.reset() self.ws=ws
train_data.reset() if total_loss.tolist()<Mloss: Mloss=total_loss.tolist() torch.save(model.state_dict(),path) print("Saving") print(f'Epoch: {epoch+1:2} Mean Loss: {total_loss.tolist()/len(train_data):10.8f}') return model
from pyecharts.charts import * from pyecharts import options as opts from pyecharts.globalsimport CurrentConfig
1 2 3 4 5 6
pre,ppre=[i.item() for i in x[:ws]],[] # pre 是用原始数据做预测 # ppre 用预测数据做预测 for i inrange(len(x)-ws+1): ppre.append(d(torch.FloatTensor(x[i:i+ws]).unsqueeze(dim=0))) pre.append(d(torch.FloatTensor(pre[-ws:]).unsqueeze(dim=0)).item())
1 2 3 4 5 6 7 8 9
l=Line() l.add_xaxis([i for i inrange(len(x))]) l.add_yaxis("Original Data",x.tolist()) l.add_yaxis("Pred Data(Using Raw Datas)",x[:ws].tolist()+[i.item() for i in ppre]) l.add_yaxis("Pred Data(Using Pred Datas)",pre) l.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) l.set_global_opts(title_opts=opts.TitleOpts(title='LSTM CNN'))
l.render_notebook()
根据时间窗口的不同,可以得到不同的结果。
窗口大小为4
窗口大小为5
窗口大小为6
从结果上来看,在一定范围内,时间窗口越大,损失误差越小。
至于验证,我们可以选Rice做验证:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
x=torch.FloatTensor(pp_c[pp_c['Item']=="Rice"]['Value'].tolist()) pre,ppre=[i.item() for i in x[:ws]],[] for i inrange(len(x)-ws+1): ppre.append(d(torch.FloatTensor(x[i:i+ws]).unsqueeze(dim=0))) pre.append(d(torch.FloatTensor(pre[-ws:]).unsqueeze(dim=0)).item()) l=Line() l.add_xaxis([i for i inrange(len(x))]) l.add_yaxis("Original Data",x.tolist()) l.add_yaxis("Pred Data(Using Raw Datas)",x[:ws].tolist()+[i.item() for i in ppre]) l.add_yaxis("Pred Data(Using Pred Datas)",pre) l.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) l.set_global_opts(title_opts=opts.TitleOpts(title='LSTM CNN'))
pre_data=pp_c[pp_c['Item']=='Sorghum']['Value'].tolist() l=pre_data[:] for i inrange(len(x)-ws+1): l.append(d(torch.FloatTensor(l[-ws:]).unsqueeze(dim=0)).item()) L=Line() L.add_xaxis([i for i inrange(len(x))]) L.add_yaxis("Pred",l) L.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) L.set_global_opts(title_opts=opts.TitleOpts(title='sorghum production forecasts') )
L.render_notebook() l.to_csv("path")
高粱价格拟合曲线
将结果数据更新。
1 2
for i inrange(1,len(x)-ws): pp_c=pp_c.append({"Unnamed: 0":91+i,"Year":2006+i,"Value":l[5+i],"Item":"Sorghum",'Unit':"卢比/kg"},ignore_index=True)
AT=[] tab=os.listdir(path) tables=[i for i in tab if i.endswith("t.csv")] # ['2017t.csv', '2018t.csv', '2019t.csv', '2020t.csv', '2021t.csv', '2022t.csv'] for i inrange(len(tables)): newT=defaultdict(int) year=tables[i].split('.')[0] tb=pd.read_csv(os.path.join(path,tables[i])) for i inrange(len(tb)): if (k:=mapTable[tb["Value"][i]]) in v["Unnamed: 0"].unique(): _=tb['Count'][i]/100 for n,g inenumerate(v.columns[2:].tolist(),2): # 每一项都等于 每种类型的像元乘以该像元在该项之下的价值之和 newT[g]+=_/1e10*v[v["Unnamed: 0"]==k].iloc[0,n] AT.append(newT) d=pd.DataFrame(AT,index=["%s"%i for i inrange(2017,2023)])
newD=pd.DataFrame([],columns=["供给服务","调节服务","支持服务","文化服务"]) newD["供给服务"]=d.iloc[:,0]+d.iloc[:,1]+d.iloc[:,2] x=d.iloc[:,3] for i inrange(4,7): x+=d.iloc[:,i] newD["调节服务"]=x x=d.iloc[:,7] for i inrange(8,10): x+=d.iloc[:,i] newD['支持服务']=x newD['文化服务']=d.iloc[:,-1]
defgetValue(year): deff(tem): Sum=0 for i inrange(len(tem)): # 若映射存在 if(k:=mapTable[tem['Value'][i]]) in v['Unnamed: 0'].unique(): _=tem['Count'][i]/100# 换算成公顷 Sum+=v[v['Unnamed: 0']==k].iloc[0,1:].sum()*_ # 总价值=\sum c_i*v_i return Sum dicT=defaultdict(int) tabs=os.listdir(path+r"\%sTabs"%year) total_esv=0 for i in tabs: tb=pd.read_excel(path+r"\%sTabs\\"%year+i) total_esv+=(k:=f(tb)) dicT[i.split("_")[0]]=k/1e10 return total_esv/1e10,dicT
Stable=[getValue(i) for i inrange(2017,2023)] DataShow=pd.DataFrame([],columns=[str(i) for i inrange(2017,2023)]) # 实际上,DF可以直接传入一个Dict,Key将作为Index,value将作为列值 for i inrange(2017,2023):DataShow[str(i)]=Stable[i-2017][1]
各县市年总ESV量表
我们将这个结果表导出,下一步便是在ArcGIS中绘制地图。
通过属性表的连接操作,可以将导出的表添加到矢量图中,然后就是对其进行地图制作,这方面不再赘述。
制图结果
再进一步,我们将利用imageio模块绘制动态图。
1 2 3 4 5 6 7 8
import imageio defcreate_gif(filelist,name,dur=1.5): IMG=[] for i in filelist: IMG.append(imageio.imread(i)) return imageio.mimsave(name,IMG,'GIF',duration=dur) path=[os.path.join(r"E:\Sri Lanka\Res\Img",i) for i in os.listdir(r"E:\Sri Lanka\Res\Img")] create_gif(path,r"E:\Sri Lanka\Res\Img\res.gif")