Tensor的基本操作

张量操作

张量的拼接和切分

在这里插入图片描述
cat不会扩张维度,stack会在新创建的维度上拼接

切分

在这里插入图片描述
在这里插入图片描述

张量的索引

在这里插入图片描述
索引要为torch.long
在这里插入图片描述
通过.ge.gt的方法生成布尔张量

张量变换

在这里插入图片描述
-1表明该维的变换根据其他维度
在这里插入图片描述
在这里插入图片描述

数学运算

在这里插入图片描述

实现线性回归

在这里插入图片描述

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

lr = 0.1

#创建训练数据
x = torch.rand(20,1)*10
y = 2*x +(2+torch.rand(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.5*(y-y_pred)**2).mean()
    #反向传播(自动求导)
    loss.backward()
    #更新参数
    b.data.sub_(lr*b.grad)
    w.data.sub_(lr*w.grad)

    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,20)
        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()<1:
            break
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值