当前位置:网站首页>Pytorch-温度预测
Pytorch-温度预测
2022-07-06 09:16:00 【想成为风筝】
pytorch-温度预测
dir = r'E:\PyTorch\02\02.2020深度学习-PyTorch实战\代码+资料\神经网络实战分类与回归任务\temps.csv'
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
Data = pd.read_csv(dir)
print(Data)
print(Data.head())
del Data['friend']
print(Data)
print('数据维度:',Data.shape)
#处理时间数据
import datetime
years = Data['year']
months = Data['month']
days = Data['day']
#datetime格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year,month,day in zip(years,months,days)]
dates = [datetime.datetime.strptime(date,'%Y-%m-%d') for date in dates]
print(dates[:5])
#绘图
#指定默认风格
# plt.style.use('fivethirtyeight')
# plt.figure(dpi=400)
# #plt.subplot(2,2,1)
# plt.plot(dates,Data['actual'])
# plt.xlabel('')
# plt.ylabel('Temperature')
# plt.title('Max Temp')
# plt.show()
#
# plt.figure(dpi=400)
# #plt.subplot(2,2,2)
# plt.plot(dates,Data['temp_1'])
# plt.xlabel('')
# plt.ylabel('Temperature')
# plt.title('Previous Max Temp')
# plt.show()
#
# plt.figure(dpi=400)
# #plt.subplot(2,2,3)
# plt.plot(dates,Data['temp_2'])
# plt.xlabel('')
# plt.ylabel('Temperature')
# plt.title('Two Days Prior Max Temp')
#
# plt.show()
# week 列 比较特殊 是 字符串类型
#独热编码
Data = pd.get_dummies(Data)
print(Data.head())
#标签
labels = np.array(Data['actual'])
Data = Data.drop('actual',axis=1)
Data_columns_name = list(Data.columns)
Data = np.array(Data)
print(Data.shape)
from sklearn import preprocessing
input_Data = preprocessing.StandardScaler().fit_transform(Data)
#构建模型
x = torch.tensor(input_Data,dtype=float)
y = torch.tensor(labels,dtype=float)
""" #自定义计算方式构建模型 #权重参数初始化 weights = torch.randn((13,128),dtype=float,requires_grad=True) biases = torch.randn(128,dtype=float,requires_grad=True) weights1 = torch.randn((128,1),dtype=float,requires_grad=True) biases1 = torch.randn(1,dtype=float,requires_grad=True) lr = 0.001 losses = [] for i in range(1000): hidden = x.mm(weights) + biases hidden = torch.relu(hidden) predictions = hidden.mm(weights1) + biases1 loss = torch.mean((predictions-y)**2) losses.append(loss.data.numpy()) #打印损失值 if i % 100 == 0: print('loss:',loss) loss.backward() #更新参数 weights.data.add_(-lr*weights.grad.data) biases.data.add_(-lr*biases.grad.data) weights1.data.add_(-lr*weights1.grad.data) biases1.data.add_(-lr*biases1.grad.data) #每次迭代要清空梯度 weights.grad.data.zero_() biases.grad.data.zero_() weights1.grad.data.zero_() biases1.grad.data.zero_() """
#简洁化网络模型
input_size = input_Data.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,output_size)
)
cost = torch.nn.MSELoss(reduction='mean')
optimizer= torch.optim.Adam(my_nn.parameters(),lr=0.001)
#training
losses = []
for i in range(1000):
batch_loss = []
for start in range(0,len(input_Data),batch_size):
end = start + batch_size if start + batch_size < len(input_Data) else len(input_Data)
xx = torch.tensor(input_Data[start:end],dtype=torch.float,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()
optimizer.step()
batch_loss.append(loss.data.numpy())
if i % 100 ==0:
losses.append(np.mean(batch_loss))
print(i,np.mean(batch_loss))
#预测训练结果
x = torch.tensor(input_Data,dtype=torch.float)
predict = my_nn(x).data.numpy()
#转换日期格式
dates = [str(int(year)) + '-' +str(int(month)) + '-' + str(int(day)) for year,month,day in zip(years,months,days)]
dates = [datetime.datetime.strptime(date,'%Y-%m-%d') for date in dates]
#创建一个表格来存日期和对应的标签数值
true_data = pd.DataFrame(data={
'date':dates,'actual':labels})
#再创建一个来寸日期和对应模型的预测值
months =Data[:,Data_columns_name.index('month')]
days = Data[:,Data_columns_name.index('day')]
years = Data[:,Data_columns_name.index('year')]
test_dates = [str(int(year)) + '-' +str(int(month)) + '-' + str(int(day)) for year,month,day in zip(years,months,days)]
test_dates = [datetime.datetime.strptime(date,'%Y-%m-%d') for date in test_dates]
#创建一个表格来存日期和对应的标签数值
predict_data = pd.DataFrame(data={
'date':test_dates,'prediction':predict.reshape(-1)})
plt.figure(dpi=400)
#True
plt.plot(true_data['date'],true_data['actual'],'b-',label='actual')
#predict
plt.plot(predict_data['date'],predict_data['prediction'],'ro',label='prediction')
plt.xticks()
plt.legend()
plt.xlabel('Date')
plt.ylabel('Maximum Temperature (F)')
plt.title('Actual and Predicted Values')
plt.show()
边栏推荐
- Aborted connection 1055898 to db:
- [yarn] CDP cluster yarn configuration capacity scheduler batch allocation
- 分布式節點免密登錄
- Nanny level problem setting tutorial
- MySQL realizes read-write separation
- 2019 Tencent summer intern formal written examination
- Kaggle竞赛-Two Sigma Connect: Rental Listing Inquiries(XGBoost)
- [Flink] Flink learning
- L2-007 family real estate (25 points)
- DICOM: Overview
猜你喜欢
随机推荐
数据库面试常问的一些概念
About string immutability
2019腾讯暑期实习生正式笔试
机器学习--线性回归(sklearn)
MySQL START SLAVE Syntax
[Kerberos] deeply understand the Kerberos ticket life cycle
ImportError: libmysqlclient. so. 20: Cannot open shared object file: no such file or directory solution
Connexion sans mot de passe du noeud distribué
jS数组+数组方法重构
【Flink】CDH/CDP Flink on Yarn 日志配置
Solution to the practice set of ladder race LV1 (all)
机器学习--决策树(sklearn)
[template] KMP string matching
Kept VRRP script, preemptive delay, VIP unicast details
XML file explanation: what is XML, XML configuration file, XML data file, XML file parsing tutorial
sklearn之feature_extraction.text.CountVectorizer / TfidVectorizer
Gallery之图片浏览、组件学习
搞笑漫画:程序员的逻辑
Learn winpwn (3) -- sEH from scratch
Valentine's Day flirting with girls to force a small way, one can learn







