学习笔记1-线性回归练习

1、动手学深度学习笔记-线性回归

1.1、课后习题错题总结

第一题 :假如你正在实现一个全连接层,全连接层的输入形状是7×8,输出形状是7×1,其中7是批量大小,
则权重参数w和偏置参数b的形状分别是____和____。

答案:w:1x8 ,b:1x1

第三题 :在线性回归模型中,对于某个大小为3的批量,标签的预测值和真实值如下表所示:

y_haty
2.333.14
1.070.98
1.231.32

该批量的损失函数的平均值为:

答案:解题程序如下

def squared_loss(y_hat, y): 
    return (y_hat - y.view(y_hat.shape))**2 / 2
y_hat = torch.tensor([2.33, 1.07, 1.23])
print(y_hat)
y = torch.tensor([3.14, 0.98, 1.32])
a = squared_loss(y_hat,y)
print(a.sum())

错误原因:没有仔细审题,题目问的是损失函数的平均值。

2、单输入线性回归练习

2.1.导入需要用的模块

# import packages and modules
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random

2.2.初始化参数

注意:初始化参数时要初始化为向量,例如初始化为x = torch.randn(n)就是错误的。

#初始化参数
n = 1000
x = torch.randn(n,1)
w = 3.4
b = 2
y = torch.zeros(n,1)

2.3.生成数据集

注意:生成数据集时,后面的随机生成的数字要为和y一样的随机向量,而不能是一个数字。

#2.生成数据集
y = w*x + b + torch.tensor(np.random.normal(0, 0.5, size=y.size()))
print(y[0:10])
print(x.shape,y.shape)
plt.scatter(x.numpy(), y.numpy(),1);

2.4.初始化参数

注意:w.requires_grad_(requires_grad=True) 默认的requires_grad=False(自动求导)

#初始化训练参数 / 读取数据
X = x
w = torch.randn(1)
b = torch.zeros(1)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
print(w,b,x_len)

2.5.分批次读取数据

注意:random.shuffle(indices) 函数表示打乱列表的循序。
torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) :构建多个(1*batch_size) Long类型的张量。

#分批次读取数据
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)

#前向传播
def forword(X,w,b):
    w=w.view(len(w),1) # 可以不加,目的是为了确保w为相对于的矩阵。
    b=b.view(len(b),1)
    return torch.mm(X, w) + b
    
#损失函数
def squared_loss(y_hat, y): 
    return (y_hat - y.view(y_hat.size())) ** 2 / 2
    
#反向传播
def sgd(params, lr, batch_size): 
    for param in params:
        param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track

# super parameters init
lr = 0.03
num_epochs = 5000

net = forword
loss = squared_loss

# training
for epoch in range(num_epochs):  # training repeats num_epochs times
    # in each epoch, all the samples in dataset will be used once
    
    # X is the feature and y is the label of a batch sample
    for X, y in data_iter(batch_size, X, y):
        #print(X.shape,w.shape,b)
        l = loss(net(X, w, b), y).sum()  
        # calculate the gradient of batch sample loss 
        l.backward()  
        # using small batch random gradient descent to iter model parameters
        sgd([w, b], lr, batch_size)  
        # reset parameter gradient
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(X, w, b), y)
    #print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(w,b)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值