Pytorch

Pytorch框架学习(2)——张量操作与线性回归

2020-01-18  本文已影响0人  aidanmomo

张量操作与线性回归

1. 张量的操作:拼接、切分、索引和变换

1.1 张量的拼接与切分

t = torch.ones(2, 5)
list_of_tensors = torch.split(t, [2, 1, 2], dim=1)
for idx, t in enumerate(list_of_tensors):
    print('第{}个张量:{},shape is {}'.format(idx + 1, t, t.shape))

结果为:

第1个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
第2个张量:tensor([[1.],
[1.]]),shape is torch.Size([2, 1])
第3个张量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])

1.2 张量索引

t = torch.randint(0, 9, size=(3, 3))
idx = torch.tensor([0, 2], dtype=torch.long)
t_select = torch.index_select(t, dim=0, index=idx)
print('t:\n{}\nt_select\n:{}'.format(t, t_select))

结果为:

t:
tensor([[5, 8, 2],
        [1, 3, 0],
        [2, 1, 6]])
t_select
:tensor([[5, 8, 2],
        [2, 1, 6]])
t = torch.randint(0, 9, size=(3, 3))
mask = t.ge(5) # ge is mean greater than or equal.  gt is mean greater than . 还有le和lt
t_select = torch.masked_select(t, mask)
print('t:\n{}\nt_select\n:{}'.format(t, t_select))

结果为:

t:
tensor([[5, 7, 2],
        [1, 6, 6],
        [1, 1, 8]])
t_select
:tensor([5, 7, 6, 6, 8])

1.3 张量变换

        t = torch.randperm(8)
        t_reshape = torch.reshape(t, (2, 4))
        print('t:{}\nt_reshape:\n{}'.format(t, t_reshape))
        print('t.data内存地址:{}\nt_reshape.data内存地址:{}'.format(id(t.data), id(t_reshape.data)))

结果为:

t:tensor([0, 4, 1, 3, 5, 7, 6, 2])
t_reshape:
tensor([[0, 4, 1, 3],
        [5, 7, 6, 2]])
t.data内存地址:2126059754696
t_reshape.data内存地址:2126059754696
        t = torch.rand((1, 2, 3, 1))
        t_sq = torch.squeeze(t)
        t_0 = torch.squeeze(t, dim=0)
        t_1 = torch.squeeze(t, dim=1)
        print(t.shape)
        print(t_sq.shape)
        print(t_0.shape)
        print(t_1.shape)

结果为:

torch.Size([1, 2, 3, 1])
torch.Size([2, 3])
torch.Size([2, 3, 1])
torch.Size([1, 2, 3, 1])

2.张量的数学运算

张量之间可以进行加减乘除,可以进行对数、指数、幂函数运算,可以进行三角函数运算


在这里插入图片描述

这里简单介绍加法运算

除此之外,还有两个加法运算,一个是加法结合除法,另一个是加法结合乘法

3.线性回归

线性回归是分析一个变量与另外一个(多)个变量之间关系的方法。

3.1 求解步骤

  1. 确定模型:
    Model : y = wx + b
  2. 选择损失函数loss:
    一般选择均方误差MSE:\frac{1}{m} \sum_{i=1}^{m}(y_i -\hat{y_i})^2
  3. 求解梯度并更新w,b:
    w = w - LR * w.grad(LR为步长,学习率)
    b = b - LR * w.grad

import torch
import matplotlib.pyplot as plt


def main():

    torch.manual_seed(10)

    # 学习率
    lr = 0.05

    # 创建训练数据
    x = torch.rand(20, 1) * 10
    y = 2*x + (5 + torch.randn(20, 1)) # y值随机加入扰动

    #构建线性回归模型
    w = torch.randn((1), requires_grad=True)
    b = torch.zeros((1), requires_grad=True)

    for iteration in range(1000):

        # 前向传播
        wx = torch.mul(w, x)
        y_pred = torch.add(wx, b)

         # 计算损失函数MSE
        loss = (0.5 * (y - y_pred)**2).mean()

        # 反向传播
        loss.backward()

        #更新参数
        b.data.sub_(lr * b.grad)
        w.data.sub_(lr * w.grad)

        # 清零张量的梯度   20191015增加
        w.grad.zero_()
        b.grad.zero_()

        # 绘图
        if iteration % 20 == 0:
            plt.scatter(x.data.numpy(), y.data.numpy())
            plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
            plt.text(2, 20, 'loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
            plt.xlim(1.5, 10)
            plt.ylim(8, 28)
            plt.title('Iteratiion:{}\nw:{} b:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
            plt.pause(0.5)

            if loss.data.numpy() < 1:
                break


if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读