当前位置:网站首页>Pytoch temperature prediction
Pytoch temperature prediction
2022-07-06 12:00:00 【Want to be a kite】
pytorch- Temperature prediction
dir = r'E:\PyTorch\02\02.2020 Deep learning -PyTorch actual combat \ Code + Information \ Neural network combat classification and regression task \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 dimension :',Data.shape)
# Processing time data
import datetime
years = Data['year']
months = Data['month']
days = Data['day']
#datetime Format
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])
# mapping
# Specify the default style
# 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 Column A special yes String type
# Hot coding alone
Data = pd.get_dummies(Data)
print(Data.head())
# label
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)
# Build the model
x = torch.tensor(input_Data,dtype=float)
y = torch.tensor(labels,dtype=float)
""" # Customize the calculation method to build the model # Weight parameter initialization 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()) # Print loss value if i % 100 == 0: print('loss:',loss) loss.backward() # Update parameters 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) # Every iteration should clear the gradient weights.grad.data.zero_() biases.grad.data.zero_() weights1.grad.data.zero_() biases1.grad.data.zero_() """
# Concise network model
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))
# Predict training results
x = torch.tensor(input_Data,dtype=torch.float)
predict = my_nn(x).data.numpy()
# Convert date format
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]
# Create a table to store the date and the corresponding tag value
true_data = pd.DataFrame(data={
'date':dates,'actual':labels})
# Then create an incoming date and the predicted value of the corresponding model
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]
# Create a table to store the date and the corresponding tag value
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()
边栏推荐
- JS array + array method reconstruction
- Selective sorting and bubble sorting [C language]
- arduino获取数组的长度
- Bubble sort [C language]
- MongoDB
- Keyword inline (inline function) usage analysis [C language]
- Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
- 分布式節點免密登錄
- Principle and implementation of MySQL master-slave replication
- GNN的第一个简单案例:Cora分类
猜你喜欢

FTP file upload file implementation, regularly scan folders to upload files in the specified format to the server, C language to realize FTP file upload details and code case implementation

MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解

优先级反转与死锁

uCOS-III 的特点、任务状态、启动

Vert. x: A simple login access demo (simple use of router)

R & D thinking 01 ----- classic of embedded intelligent product development process

几个关于指针的声明【C语言】

Linux Yum install MySQL

Small L's test paper

分布式节点免密登录
随机推荐
Contiki source code + principle + function + programming + transplantation + drive + network (turn)
TypeScript
B tree and b+ tree of MySQL index implementation
MySQL START SLAVE Syntax
小天才电话手表 Z3工作原理
电商数据分析--薪资预测(线性回归)
Linux yum安装MySQL
[CDH] cdh5.16 configuring the setting of yarn task centralized allocation does not take effect
关键字 inline (内联函数)用法解析【C语言】
Reno7 60W超级闪充充电架构
[yarn] yarn container log cleaning
{one week summary} take you into the ocean of JS knowledge
Linux Yum install MySQL
Word排版(小计)
[mrctf2020] dolls
Connexion sans mot de passe du noeud distribué
Characteristics, task status and startup of UCOS III
2020网鼎杯_朱雀组_Web_nmap
PyTorch四种常用优化器测试
【presto】presto 参数配置优化