pytorch linear regression

import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F


x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x**2 + 0.2*torch.rand(x.shape)

#output to see the figure
# plt.scatter(x,y)
# plt.show()

class Net(torch.nn.Module):
    def __init__(self,n_features,n_hidden,n_output):
        super(Net,self).__init__() #继承
        self.hidden = torch.nn.Linear(n_features, n_hidden)
        self.predict = torch.nn.Linear(n_hidden,n_output)

    def forward(self,x):
        x = self.hidden(x)
        x = F.relu(x)
        x = self.predict(x)
        return x

net = Net(1,10,1)
optimizer = torch.optim.SGD(net.parameters(),lr=0.2)
loss_func = torch.nn.MSELoss() #MSE : mean square error

for t in range(100):
    #forward
    prediction = net.forward(x)
    #get loss
    loss = loss_func(prediction, y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if t%5 == 0:
        x_test = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
        prediction = net.forward(x_test)
        # prediction = net(x)
        plt.cla()
        plt.scatter(x_test.data.numpy(), y.data.numpy())
        plt.plot(x_test.data.numpy(), prediction.data.numpy())
        # plt.show()
        plt.pause(0.1)

references

Here is an example implementation of a linear regression model using PyTorch and Autograd for optimization: ```python import torch import numpy as np # Generate some random data np.random.seed(42) x = np.random.rand(100, 1) y = 2 + 3 * x + 0.1 * np.random.randn(100, 1) # Convert data to PyTorch tensors x_tensor = torch.from_numpy(x).float() y_tensor = torch.from_numpy(y).float() # Define the model class LinearRegression(torch.nn.Module): def __init__(self): super(LinearRegression, self).__init__() self.linear = torch.nn.Linear(1, 1) def forward(self, x): return self.linear(x) model = LinearRegression() # Define the loss function criterion = torch.nn.MSELoss() # Define the optimizer optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # Train the model num_epochs = 1000 for epoch in range(num_epochs): # Forward pass y_pred = model(x_tensor) loss = criterion(y_pred, y_tensor) # Backward pass and optimization optimizer.zero_grad() loss.backward() optimizer.step() # Print progress if (epoch+1) % 100 == 0: print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item())) # Print the learned parameters w, b = model.parameters() print('w =', w.item()) print('b =', b.item()) ``` In this example, we define a linear regression model as a subclass of `torch.nn.Module`, with a single linear layer. We use the mean squared error loss function and stochastic gradient descent optimizer to train the model on the randomly generated data. The model parameters are learned through backpropagation using the `backward()` method, and are optimized using the `step()` method of the optimizer. After training, we print the learned values of the slope and intercept parameters.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值