pytorch-task2

这篇博客对比了使用numpy和PyTorch两种方式实现梯度下降和线性回归,并进一步介绍了如何在PyTorch中构建一个简单的神经网络。作者提供了详细步骤,从numpy的基础操作到PyTorch的高级应用。
摘要由CSDN通过智能技术生成

numpy实现梯度下降

x = 1
learning_rate = 0.1
epochs = 50
y = lambda x : x ** 2 - 1

for epoch in range(epochs):
    print(epoch, x)
    dx = 2 * x
    x = x - learning_rate * dx
print(y(x))

pytorch实现梯度下降

import torch
from torch.autograd import Variable

x = torch.Tensor([1])
#建立一个张量  tensor([1.], requires_grad=True)
x = Variable(x, requires_grad=True)
print('grad', x.grad, 'data', x.data)
learning_rate = 0.1
epochs = 20

for epoch in range(epochs):
    y = x ** 2 - 1
    y.backward()
    print('grad',x.grad.data)
    x.data=x.data-learning_rate*x.grad.data
    x.grad.data.zero_()

print(x.data)
print(y)

numpy实现线性回归

import numpy as np
x_data=np.array([1,2,3])
y_data=np.array([2,4,6])

epochs=10
lr=0.1
w=0
cost=[]

yhat=x_data*w
print(x_data)
print(y_data-yhat)
print(-2*(y_data-yhat))
print(x_data.T)
print(-2*(y_data-yhat)@x_data.T)

for epoch in range(epochs):
    yhat=x_data*w
    loss=np.average((y_data-yhat)**2)
    cost.append(loss)
    dw=-2*(y_data-yhat)@x_data.T/(x_data.shape[0])
    w=w-lr*dw
    print(w)

print(w)

pytorch实现线性回归

torch.manual_seed(2)
x_data=Variable(torch.Tensor([[1.0],[2.0],[3.0]]))
y_data=Variable(torch.Tensor([[2.0],[4.0],[6.0]]))

epochs=10
lr=0.1
w=Variable(torch.FloatTensor([0]),requires_grad=True)
cost=[]

for epoch in range(epochs):
    yhat=x_data*w
    loss=torch.mean((yhat-y_data)**2)
    cost.append(loss.data.numpy())
    loss.backward()
    w.data=w.data-lr*w.grad.data
    print(w.data)
    w.grad.data.zero_()
    
w.data

pytorch实现一个简单的神经网络

上一个任务已经实现:https://blog.csdn.net/zh11403070219/article/details/88092442

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值