当前位置:网站首页>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
边栏推荐
- Some concepts often asked in database interview
- Wangeditor rich text reference and table usage
- JS array + array method reconstruction
- GNN的第一个简单案例:Cora分类
- Reno7 60W super flash charging architecture
- Bubble sort [C language]
- 列表的使用
- 机器学习--线性回归(sklearn)
- [Flink] cdh/cdp Flink on Yan log configuration
- MySQL主从复制的原理以及实现
猜你喜欢
随机推荐
Contiki源码+原理+功能+编程+移植+驱动+网络(转)
机器学习--线性回归(sklearn)
mysql实现读写分离
[template] KMP string matching
MATLAB学习和实战 随手记
选择法排序与冒泡法排序【C语言】
Keyword inline (inline function) usage analysis [C language]
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
分布式節點免密登錄
Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
RT-Thread 线程的时间片轮询调度
Wangeditor rich text reference and table usage
2019腾讯暑期实习生正式笔试
JS object and event learning notes
MySQL realizes read-write separation
PyTorch四种常用优化器测试
Connexion sans mot de passe du noeud distribué
列表的使用
I2C bus timing explanation
[Kerberos] deeply understand the Kerberos ticket life cycle