《动手学》Pytorch版课程笔记——第一期

《动手学》Pytorch版课程笔记——第一期

概述

在疫情期间宅在家中,偶然得到伯禹教育公益课程,整个课程体系非常系统地介绍了深度学习的体系,但最吸引我的还是pytorch的教学和使用,因为之前因为torch不太会,在看nlp竞赛开源方案时有点麻烦。一次开了一个小小的专题,记录一下为期14天的课程,系统巩固一下知识。整个课程的参考书籍为《动手学深度学习》
第一期笔记主要是前三讲线性回归、softmax和多层感知器,主要从非库函数版和库函数版两个角度来分别呈现算法的原理和工程实践。

1.线性回归

针对这方面知识,举个简单例子,这里我们假设价格只取决于房屋状况的两个因素,即面积(平方米)和房龄(年)。接下来我们希望探索价格与这两个因素的具体关系。线性回归假设输出与各个输入之间是线性关系:
p r i c e = w a r e a ⋅ a r e a + w a g e ⋅ a g e + b \mathrm{price} = w_{\mathrm{area}} \cdot \mathrm{area} + w_{\mathrm{age}} \cdot \mathrm{age} + b price=wareaarea+wageage+b
然后就是损失函数和优化方式,这里分别列出数据生成、网络搭建,损失函数与SGD的非库函数版实现:

  • 数据随机生成
    这里介绍如何随机生成可验证模型的随机数据,方便测自己搭建模型是否有效。
# set input feature number 
num_inputs = 2
# set example number
num_examples = 1000

# set true weight and bias in order to generate corresponded label
true_w = [2, -3.4]
true_b = 4.2

features = torch.randn(num_examples, num_inputs,
                      dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()),
                       dtype=torch.float32)

可视化一下随机生成数据

plt.scatter(features[:, 1].numpy(), labels.numpy(), 1);

在这里插入图片描述
生成完数据就是加载数据环节了,为了增加读取效率和节约空间,这里用生成器来读取

def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)  # random read 10 samples
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
        yield  features.index_select(0, j), labels.index_select(0, j)
  • 定义模型版
    1 损失函数
    l ( i ) ( w , b ) = 1 2 ( y ^ ( i ) − y ( i ) ) 2 , l^{(i)}(\mathbf{w}, b) = \frac{1}{2} \left(\hat{y}^{(i)} - y^{(i)}\right)^2, l(i)(w,b)=21(y^(i)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值