【深度之眼】Pytorch框架班第五期-深度之眼Week1任务2第一节:张量操作与线性回归

张量操作与线性回归

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

一、张量的拼接与切分

1.1 torch.cat(tensors, dim=0, out=None)
功能:将张量按维度dim进行拼接

  • tensors: 张量序列
  • dim: 要拼接的维度

1.2 torch.stack(tensors, dim=0, out=None)
功能:在新创建的维度dim上进行拼接

  • tensors: 张量序列
  • dim: 要拼接的维度

1.3 torch.chunk(input, chunks, dim=0)
功能: 将张量按维度dim进行平均切分
返回值:张量列表
注意事项:如果不能整除,最后一份张量小于其他张量,向上取整

  • input: 要切分的张量
  • chunks: 要切分的份数
  • dim: 要切分的维度

1.4 torch.split(tensor, split_size_or_sections, dim=0)
功能:将张量按维度dim进行切分
返回值:张量列表

  • tensor: 要切分的张量
  • split_size_or_sections: 为 int 时,表示每一份的长度;为 list 时,按list元素切分
  • dim: 要切分的维度

二、张量的索引

2.1 torch.index_select(input, dim, index, out=None)
功能:在维度 dim 上,按 index 索引数据
返回值:依 index 索引数据拼接的张量

  • input: 要索引的张量
  • dim: 要索引的维度
  • index: 要索引数据的序号,多个序号用list,dtype必需为torch.long

2.2 torch.masked_select(input, mask, out=None)
功能:按mask中的True进行索引
返回值:以为张量

  • input: 要索引的张量
  • mask: 与 input 同形状的布尔类型张量

三、张量变换

3.1 torch.reshape(input, shape)
功能: 变换张量的形状
注意事项:当张量在内存中是连续时, 张量与 input 共享数据内存

  • input: 要变换的张量
  • shape: 新张量的形状

3.2 torch.transpose(input, dim0, dim1)
功能: 交换张量的两个维度

  • input: 要变换的张量
  • dim0: 要交换的维度
  • dim1: 要交换的维度

3.3 torch.t(input)
功能:2维张量转置,对矩阵而言,等价于 torch.transpose(input, 0, 1)

3.4 torch.squeeze(input, dim=None, out=None)
功能:压缩长度维1的维度(轴)

  • dim: 若为None,移除所有长度为1的轴;若指定维度,当且仅当该轴长度为1时,可以被移除;

3.5 torch.unqueeze(input, dim, out=None)
功能:依据dim扩展维度

  • dim: 扩展的维度

张量的数学运算

一、加减乘除

torch.add(input, alpha=1, other, out=None)
功能:逐元素计算input + alpha x other

torch.addcdiv(input, value=1, tensor1, tensor2, out=None)
功能:out = input + value x (tensor1 / tensor2)
torch.addcmul(input, value=1, tensor1, tensor2, out=None)
功能:out = input + value x tensor1 x tensor2
torch.sub()
torch.div()
torch.mul()

二、对数,指数,幂函数

torch.log(input, out=None)
torch.log10(input, out=None)
torch.log2(input, out=None)
torch.exp(input, out=None)
torch.pow()

三、三角函数

torch.abs(input, out=None)
torch.acos(input, out=None)
torch.cosh(input, out=None)
torch.cos(input, out=None)
torch.asin(input, out=None)
torch.atan(input, out=None)
torch.atan2(input, other, out=None)

线性回归

线性回归是分析一个变量与另一(多)个变量之间关系的方法
因变量: y
自变量: x
关系: 线性 y = wx + b
分析:求解w,b

求解步骤:
1、确定模型
Model: y = wx + b
2、选择损失函数
MSE: 在这里插入图片描述
3、求解梯度并更新w, b
w = w - LR * w.grad
b = b - LR * w.grad

作业:调整线性回归模型停止条件以及y = 2*x + (5 + torch.randn(20, 1))中的斜率,训练一个线性回归模型

import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)

lr = 0.01  # 学习率    20191015修改
best_loss = float("inf")

# 创建训练数据
x = torch.rand(200, 1) * 10  # x data (tensor), shape=(20, 1)
y = 2*x + (5 + torch.randn(200, 1))  # y data (tensor), shape=(20, 1)

# 构建线性回归参数
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.2是为了求导时消掉2设置的,没干系
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向传播
    loss.backward()


    current_loss = loss.item()
    if current_loss < best_loss:
        best_loss = current_loss
        best_w = w
        best_b = b


    # 绘图
    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("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

        # 终止条件
        if loss.data.numpy() < 0.55:
            break

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


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

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值