论文写完了也不让实习,糟糕的环境就不用吐槽了,感觉被生活蹂躏的我身心疲惫,能做的只有忍下去,每天一个人这么将就的活着。没事我还能忍,既然如此,暑假的我还是踏踏实实学习,只希望将来能不辜负自己受的这些苦难,让我爱的人都能幸福的活着,加油。
#1.神将网络天气预测,线性回归 import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.optim as optim import warnings warnings.filterwarnings('ignore') %matplotlib inline features=pd.read_csv('temps.csv') features.head() print('数据维度:',features.shape) #处理时间数据 import datetime years=features['year'] months=features['month'] days=featuures['day'] dates=[str(int(year))+'-'+str(int(month))+'-'+str(int(day)) for year,month,day in zip(years,month,days)] dates=[datetime.datetime.strptime(date,'%Y=%m-%d') for date in dates] #画图展示 plt.style.use('fivethirtyeight')#指定默认风格 fig,((ax1,ax2,ax3,ax4))=plt.subplot(nrows=2,ncols=2,figsize=(10,10)) fig.autofmt_xdate(rotation=45)#设置布局 #画出4个子图 ax1.plot(dates,features['actual']) ax1.set_xlabel('');ax1.set_ylabel('Temperature');ax1.set_title('Max Temp') ax2.plot(dates,features['temp_1']) ax2.set_xlabel('');ax2.set_ylabel('Temperature');ax2.set_title('Previous Max Temp') ax3.plot(dates,features['temp_2']) ax3.set_xlabel('Date');ax3.set_ylabel('Temperature');ax3.set_title('Two Days Prior Max Temp') ax4.plot(dates,features['friend']) ax4.set_xlabel('Date');ax4.set_ylabel('Temperature');ax4.set_title('Friend Estimate') plt.tight_layout(pad=2) #独热编码 features=pd.get_dummies(features)#自动将字符串形式的换成独热编码 labels=np.array(features['actual'])#标签 features=features.drop('actual',axis=1)#特征 features=np.array(features)#datafrom>>>>ndarray feature_list=list(features.columns)#名字 from sklearn import preprocessing input_features=preprocessing.StandardScalar().fit_transform(features)#特征数据标准化 #构建模型 x=torch.tensor(input_features,dtype=float) y=torch.tensor(labels,dtype=float) weights=torch.randn((14,128),dtype=float,requires_grad=True) biases=torch.randn(128,dtype=float,requires_grad=True) weights2=torch.randn((128,1),dtype=float,requires_grad=True) biases2=torch.randn(1,dtype=float,requires_grad=True) learning_rate=0.01 losses=[] for i in range(1000): hidden=x.mm(weights)+biases#计算隐层 hidden=torch.relu(hidden)#加入激活层 prediction=hidden.mm(weights)+biases2#预测结果 loss=torch.mean((predictions-y)**2)#计算损失 losses.append(loss.data.numpy()) if i%100==0: print('loss',loss) loss.backward()#反向传播 #更新参数 weights.data.add_(-learning_rate*weights.grad.data) biases.data.add_(-learning_rate*biases.grad.data) weights2.data.add_(-learning_rate*weights.grad.data) biases2.data.add_(-learning_rate*biases.grad.data) #每次迭代完都记得清空 weights.grad.data.zero_() biases.grad.data.zero_() weights2.grad.data.zero_() biases2.grad.data.zero_() #2.更简单的方式构建网络 input_size=input_features.shape[1] hidden_size=128 output_size=1 batch_size=16 my_nn=torch.nn.Sequential(torch.nn.Linear(input_size,hidden_size), torch.nn.Sigmoid(), torch.nn.Linear(hidden_size,out_size))#定义网络结构 cost=torch.nn.MSELoss(reduction='mean')#均方误差 optimizer=torch.optim.Adam(my_nn.parameters(),lr=0.001)#对网络参数进行优化的优化器设置 #训练网络 losses=[] for i in range(1000): batch_loss=[] for start in range(0.len(input_features),batch_size): end=start+batch_size if star+batch_size<len(inpu_features) else len(input_featurs) xx=torch.tensor(input_features[start:end],dtype=torch.flaot,requires_grad=True) yy=torch.tensor(labels[start:end],dtype=torch.float,requires_grad=True) prediction=my_nn(xx) loss=cost(prediction,yy) optimizer.zero_grad() loss.backward(retain_graph=True)#表示此代码可以重复执行 optimizer.step()#更新操作 batch_loss.append(loss,data.numpy()) if i%100==0: losses.append(np.mean(batch_loss)) print(i,np.mean(batch_loss))