当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
几个关于指针的声明【C语言】
MATLAB学习和实战 随手记
Contiki source code + principle + function + programming + transplantation + drive + network (turn)
Variable star user module
C语言函数之可变参数原理:va_start、va_arg及va_end
【CDH】CDH5.16 配置 yarn 任务集中分配设置不生效问题
Principle and implementation of MySQL master-slave replication
机器学习--线性回归(sklearn)
[mrctf2020] dolls
ESP8266通过arduino IED连接巴法云(TCP创客云)
MySQL数据库面试题
Pytorch实现简单线性回归Demo
高通&MTK&麒麟 手机平台USB3.0方案对比
【yarn】CDP集群 Yarn配置capacity调度器批量分配
Stage 4 MySQL database
B tree and b+ tree of MySQL index implementation
Reno7 60W超级闪充充电架构
高通&MTK&麒麟 手機平臺USB3.0方案對比
电商数据分析--薪资预测(线性回归)
2020 WANGDING cup_ Rosefinch formation_ Web_ nmap




![C language callback function [C language]](/img/7b/910016123738240e24549ddea8a162.png)


