当前位置:网站首页>Pytoch implements simple linear regression demo
Pytoch implements simple linear regression demo
2022-07-06 12:00:00 【Want to be a kite】
Pytorch Implement simple linear regression
import numpy as np
x_values = [i for i in range(11)]
x_train = np.array(x_values,dtype=np.float32)
x_train = x_train.reshape(-1,1)
print(x_train.shape)
y_values = [2*i+1 for i in x_values]
y_train = np.array(y_values,dtype=np.float32)
y_train = y_train.reshape(-1,1)
print(y_train.shape)
import torch
import torch.nn as nn
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class LinearRegressionModel(nn.Module):
def __init__(self,input_dim,output_dim):
super(LinearRegressionModel, self).__init__()
self.Linear = nn.Linear(input_dim,output_dim)
def forward(self,x):
out = self.Linear(x)
return out
input_dim = 1
output_dim = 1
model = LinearRegressionModel(input_dim,output_dim)
model.to(device)
losses = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(),lr=0.01)
epochs = 1000
for epoch in range(epochs):
epoch += 1
inputs = torch.from_numpy(x_train).to(device)
outputs = torch.from_numpy(y_train).to(device)
optimizer.zero_grad()
out = model(inputs)
loss = losses(out,outputs)
loss.backward()
optimizer.step()
if epoch % 50 == 0:
print('epoch {},loss {}'.format(epoch,loss))
# forecast
predicted =model(torch.from_numpy(x_train).requires_grad_()).data.numpy()
print(predicted)
# # preservation
# torch.save(model.state_dict(),'model.pkl') # Save the parameters of the model w b
# # load
# model.load_state_dict(torch.load('model.pkl')) # load
边栏推荐
猜你喜欢
高通&MTK&麒麟 手机平台USB3.0方案对比
RT-Thread的main线程“卡死”的一种可能原因及解决方案
共用体(union)详解【C语言】
Stage 4 MySQL database
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
Basic use of pytest
Pytoch Foundation
【CDH】CDH5.16 配置 yarn 任务集中分配设置不生效问题
电商数据分析--用户行为分析
Togglebutton realizes the effect of switching lights
随机推荐
Mysql database interview questions
ESP8266使用arduino连接阿里云物联网
2020网鼎杯_朱雀组_Web_nmap
高通&MTK&麒麟 手機平臺USB3.0方案對比
使用LinkedHashMap实现一个LRU算法的缓存
Kaggle竞赛-Two Sigma Connect: Rental Listing Inquiries(XGBoost)
uCOS-III 的特点、任务状态、启动
冒泡排序【C语言】
arduino JSON数据信息解析
Composition des mots (sous - total)
数据分析之缺失值填充(重点讲解多重插值法Miceforest)
互联网协议详解
Apprentissage automatique - - régression linéaire (sklearn)
Reading notes of difficult career creation
Detailed explanation of Union [C language]
电商数据分析--用户行为分析
Come and walk into the JVM
Unit test - unittest framework
There are three iPhone se 2022 models in the Eurasian Economic Commission database
Common regular expression collation