最近开始学习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绘制散点图的功能可以说还是非常强大的,但是这里主要是对这些函数有一个的大致的了解,所以不做深入的讨论。