PyTorch学习之路:多项式回归

本文基于PyTorch实现多项式回归,通过复现《深度学习入门之PyTorch》中的代码,详细探讨了如何使用Python和PyTorch进行数据拟合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文代码参考廖星宇《深度学习入门之PyTorch》中的示例代码,手动复现而来,仅供个人使用,侵删。

import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt

#Define Model
class poly_model(nn.Module):
    def __init__(self):
        super(poly_model, self).__init__()
        self.poly = nn.Linear(3, 1)

    def forward(self, x):
        out = self.poly(x)
        return out

#Build features-> a matrix with columns [x,x^2,x^3]
def make_feature(x):
    x= x.unsqueeze(1)
    return torch.cat([x ** i for i in range(1,4)], 1)

#Approximated function
def f(x):
    return x.mm(W_target) + b_target[0]

#Build a batch->(x,f(x)) pair
def get_batch(batch_size=32):
    random = torch.randn(batch_size)
    random = np.sort(random)
    random = torch.Tensor(random)
    x = make_feature(random)
    y = f(x)
    if torch.cuda.is_available():
        return Variable(x).cuda(), Variable(y).cuda()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值