Pytorch系列:Pytorch的简单操作(三) ---- 张量的基础操作

一、张量的拼接与切分
1. torch.cat(tensor, dim=0, out=None)

功能: 将张量按维度dim进行拼接
参数:

  • tensors:张量序列
  • dim:要拼接的维度
>>> t = torch.ones((2, 3))
>>> torch.cat([t, t], dim=0)
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
>>> torch.cat([t, t], dim=1)
tensor([[1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1.]])
2. torch.stack(tensors, dim=0, out=None)

功能: 在新创建的维度dim上进行拼接,如果维度已经存在,则将存在的维度向后移动。然后新建维度进行拼接。
参数:

  • tensors:张量序列
  • dim:要拼接的维度
>>> t = torch.ones((2, 3))
>>> t_stack = torch.stack([t, t], dim=2)
>>> t_stack
tensor([[[1., 1.],
         [1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.],
         [1., 1.]]])
>>> t_stack.shape
torch.Size([2, 3, 2])
>>> t.shape
torch.Size([2, 3])
>>> t_stack = torch.stack([t, t], dim=0)
>>> t_stack.shape
torch.Size([2, 2, 3])
3. torch.chunk(input, chunks, dim=0)

功能: 将张量按维度dim进行平均切分
返回值: 张量列表
注意事项: 若不能整除,最后一份张量小于其他张量
参数:

  • input:要切分的张量
  • chunks:要切分的份数
  • dim:要切分的维度
>>> a = torch.ones((2, 5))
>>> list_of_tensors = torch.chunk(a, dim=1, chunks=2)
>>>> for idx, t in enumerate(list_of_tensors):
...     print("第{}个张量:{},shape is {}".format(idx+1, t, t.shape))
...
第1个张量:tensor([[1., 1., 1.],
        [1., 1., 1.]]),shape is torch.Size([2, 3])
第2个张量:tensor([[1., 1.],
        [1., 1.]]),shape is torch.Size([2, 2])
4. torch.split(tensor, split_size_or_sections, dim=0)

功能: 将张量按维度dim进行切分
参数:

  • tensor:要切分的张量
  • split_size_or_sections:为int时,表示每一份的长度;为list时,按list元素切分
  • dim:要切分的维度
>>> t = torch.ones((2, 5))
>>> torch.split(t, 2, dim=1)
(tensor([[1., 1.],
        [1., 1.]]), 
 tensor([[1., 1.],
        [1., 1.]]), 
 tensor([[1.],
        [1.]]))

>>> torch.split(t, [2, 1, 2], dim=1)
(tensor([[1., 1.],
        [1., 1.]]), tensor([[1.],
        [1.]]), tensor([[1., 1.],
        [1., 1.]]))
二、张量的索引
1. torch.index_select(input, dim, index, out=None)

功能: 在维度dim上,按index索引数据
返回值: 依index索引数据拼接的张量
参数:

  • input:要索引的张量
  • dim:要索引的维度
  • index:要索引数据的序号
>>> t = torch.randint(0, 9, size=(3, 3))
>>> idx = torch.tensor([0, 2], dtype=torch.long)
>>> torch.index_select(t, dim=0, index=idx)
tensor([[3, 0, 8],
        [5, 3, 4]])
>>> t
tensor([[3, 0, 8],
        [4, 3, 8],
        [5, 3, 4]])
2. torch.masked_select(input, mask, out=None)

功能: 按mask中的True进行索引
返回值: 一维张量
参数:

  • input:要索引的张量
  • mask:与input同形状的布尔类型张量
>>> t = torch.randint(0, 9, size=(3, 3))
>>> mask = t.ge(5)
>>> torch.masked_select(t, mask)
tensor([7, 5, 6, 7, 5])
>>> mask
tensor([[1, 0, 1],
        [1, 1, 0],
        [0, 1, 0]], dtype=torch.uint8)
>>> t
tensor([[7, 3, 5],
        [6, 7, 2],
        [1, 5, 4]])
三、张量变换
1. torch.reshape(input, shape)

功能: 变换张量形状
注意事项: 当张量在内存中是连续时,新张量与input共享数据内存
参数:

  • input:要变换的张量
  • shape:新张量的形状
>>> t = torch.randperm(8)
>>> t
tensor([1, 7, 3, 6, 4, 5, 2, 0])
>>> torch.reshape(t, (2, 4))
tensor([[1, 7, 3, 6],
        [4, 5, 2, 0]])
2. torch.transpose(input, dim0, dim1)

功能: 交换张量的两个维度
参数:

  • input:要变换的张量
  • dim0:要交换的维度
  • dim1:要交换的维度
>>> t = torch.rand((2, 3, 4))
>>> t0 = torch.transpose(t, dim0=1, dim1=2)
>>> t0.shape
torch.Size([2, 4, 3])
3. torch.t(input)

功能: 2维张量转置。

4. torch.squeeze(input, dim=None, out=None)

功能: 压缩长度为1的维度
参数:

  • input:输入的张量
  • dim:若为None,移除所有长度为1的轴;若指定维度,当且仅当该轴长度为1时,可以被移除。
>>> t = torch.rand((1, 2, 3, 1))
>>> torch.squeeze(t).shape
torch.Size([2, 3])
>>> torch.squeeze(t, dim=0).shape
torch.Size([2, 3, 1])
>>> torch.squeeze(t, dim=1).shape
torch.Size([1, 2, 3, 1])
5. torch.unsqueeze(input, dim, out=None)

功能: 依据dim扩展维度
参数:

  • dim:扩展的维度
四、张量的数学运算

        张量的数学运算包括:加减乘除、对数、指数、幂函数和三角函数等。常用的函数如下:

  1. torch.add()
  2. torch.sub()
  3. torch.div()
  4. torch.mul()
  5. torch.log(input)
  6. torch.log10(input)
  7. torch.exp(input)
  8. torch.abs(input)
  9. torch.cos(input)
五、线性回归
import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)

lr = 0.05  # 学习率    

# 创建训练数据
x = torch.rand(20, 1) * 10  
y = 2*x + (5 + torch.randn(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
    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("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        # plt.pause(0.5)
        plt.show()

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

1

80

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值