# -*- coding: utf-8 -*-
import random
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
x_train = np.array([range(20)], dtype=np.float32).T
y_train = x_train * 4.5 + 3 * np.array([[random.random() for i in range(20)]], dtype=np.float32).T
x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
out = self.linear(x)
return out
if torch.cuda.is_available():
model = LinearRegression().cuda()
else:
model = LinearRegression()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=1e-4)
num_epochs = 2000
for epoch in range(num_epochs):
if torch.cuda.is_available():
inputs
pytorch实现一阶线性回归
最新推荐文章于 2024-08-01 21:08:58 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)