Pytorch学习(一)--线性回归

最近开始学习pytorch了,计划一周之内看个大概。

Pytorch学习系列(一)至(四)均摘自《深度学习框架PyTorch入门与实践》陈云

这里把自己觉得比较重要并且具有代表性的代码贴出来,做一下记录。

#-----------------------------------------------------------------------------
#---------------------------线性回归------------------------------------
#-----------------------------------------------------------------------------

import torch as t
from matplotlib import pyplot as plt
from IPython import display

t.manual_seed(1000)

def get_fake_data(batch_size=8):
    x=t.rand(batch_size,1)*20
    y=x*2+(1+t.randn(batch_size,1))*3
    return x,y

x,y=get_fake_data()
plt.scatter(x.squeeze().numpy(),y.squeeze().numpy())

w=t.rand(1,1)
b=t.zeros(1,1)
lr=0.001

for ii in range(20000):
    x,y=get_fake_data()
    
    y_pred=x.mm(w)+b.expand_as(y)
    loss=0.5*(y_pred-y)**2
    loss=loss.sum()
    
    dloss=1
    dy_pred=dloss*(y_pred-y)
    
    dw=x.t().mm(dy_pred)
    db=dy_pred.sum()
    
    w.sub_(lr*dw)
    b.sub_(lr*db)
    
    if ii%1000==0:
        
        display.clear_output(wait=True)
        x=t.arange(0,20).view(-1,1)
        y=x.mm(w)+b.expand_as(x)
        plt.plot(x.numpy(),y.numpy())
        
        x2,y2=get_fake_data(batch_size=20)
        plt.scatter(x2.numpy(),y2.numpy())
        
        plt.xlim(0,20)
        plt.ylim(0,41)
        plt.show()
        plt.pause(0.5)
        
        print(w.squeeze()[0],b.squeeze()[0])

1.t.manual_seed()

参考:http://pytorch.org/docs/master/torch.html?highlight=manual_seed#random-sampling

Sets the seed for generating random numbers. And returns atorch._C.Generator object.

参考:https://discuss.pytorch.org/t/what-is-manual-seed/5939/4

来自网友fmassa的回答:

You just need to call torch.manual_seed(seed), and it will set the seed of the random number generator to a fixed value, so that when you call for example torch.rand(2), the results will be reproducible.
An example

import torch

torch.manual_seed(2)
print(torch.rand(2))

gives you

 0.4360
 0.1851
[torch.FloatTensor of size 2]

Try now without the torch.manual_seed, and you’ll see that it changes over time.

2.plt.scatter()

scatter绘制散点图的功能可以说还是非常强大的,但是这里主要是对这些函数有一个的大致的了解,所以不做深入的讨论。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值