pytorch学习笔记(2):tensor的操作 以及简单的线性回归 一定坚持学完啊!!

张量的操作与线性回归

1.张量的拼接torch.cat() torch.stack()

torch.cat( 不会扩张张量的维度
tensors,张量序列
dim, 要拼接的维度
out
)
torch.stack(
tensors,张量序列
dim, 要拼接的维度
out
)
t = torch.ones((2, 3))
t1 = torch.cat([t, t], dim=0)
t2 = torch.cat([t, t, t], dim=1)
print('t0:{} shape:{} \n t1:{} shape:{} \nt2:{} shape:{}\n'.format(t, t.shape, t1, t1.shape, t2, t2.shape))
t3 = torch.stack([t, t], dim=2)
print(t3, t3.shape)

输出结果:
t0:tensor([[1., 1., 1.],
        [1., 1., 1.]]) shape:torch.Size([2, 3]) 
 t1:tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]) shape:torch.Size([4, 3]) 
t2:tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1., 1., 1., 1.]]) shape:torch.Size([2, 9])

tensor([[[1., 1.],
         [1., 1.],
         [1., 1.]],

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

2.张量的切分torch.chunk() torch.split()

"""
torch.chunk( 将张量平均切分  返回张量列表  
input, 要切分的向量
chunks, 要切分的份数
dim=0 要切分的维度
)
"""
t = torch.ones((2, 5))
list_t = torch.chunk(t,  chunks=3,dim=1)
for idx, t1 in enumerate(list_t):
    print('第{}个张量:{},shape is {}'.format(idx + 1, t1, t1.shape))

"""
torch.split(
tensor, 要切分的张量
split_size_or_sections,int时表示每一份的长度,为list时表示按list元素切分
dim=0 要切分的维度
)
"""
t = torch.ones((2, 5))
list_t = torch.split(t,  [2,3],dim=1)
for idx, t1 in enumerate(list_t):
    print('第{}个张量:{},shape is {}'.format(idx + 1, t1, t1.shape))

3.张量的索引 torch.index_select() torch.masked_select()

"""
torch.index_select( 在维度dim上,按index索引数据   返回index索引数据拼接的张量
input, 要索引的张量
dim, 要索引的维度
index, 要索引数据的序号
out
)
"""
t=torch.randint(0,9,size=(3,3))
idx=torch.tensor([0,2]) #必须是dtype=torch.long否则会报错
t_select=torch.index_select(t,dim=1,index=idx)
print("t:{}\n t_select:{}\n".format(t,t_select))

"""
torch.masked_select( #返回的是一个一维数组
input, 要是索引的张量
mask,与input同形状的布尔类型张量
out
)
"""
t=torch.randint(0,9,size=(3,3))
mask=t.ge(5) #大于等于5的挑出来
t_select=torch.masked_select(t,mask)
print("t:{}\n t_select:{}\n".format(t,t_select))

3.张量的变换 torch.reshape() torch.transpose() torch.t() torch.squeeze() torch.unsqueeze()

"""
torch.reshape(
input, 要变换的张量
shape 新张量的形状
)
"""
t=torch.randint(0,8,size=(1,8))
t1=torch.reshape(t,(2,4)) #有时一个shape(a,b)有一个为1 表示有个由另一个变换计算而来
print(t)
print(t1)
"""
torch.transpose( 交换张量的两个维度
input,
dim0,
dim1
)
"""
"""
torch.t(input)
2维张量转置
"""
t=torch.randint(0,8,size=(1,8))
t1=torch.t(t)
print(t1)

"""
torch.squeeze( 压缩长度为1的维度
input,
dim, 若为None,移除所有长度为1的轴,若指定维度,当且仅当该轴长度为1时可以被移除
out
)

torch.unsqueeze( 依据dim扩展维度
input,
dim, 扩展的维度
out
)
"""
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)

4.张量的运算

大概分类:

1.加减乘除
torch.add()
torch.addcdiv()
torch.addcmul()
torch.sub()
torch.div()
torch.mul()

2.对数指数幂函数
torch.log(input,out)
torch.log10(input,out)
torch.log2(input,out)
torch.exp(input,out)
torch.pow()

3.三角函数
torch.abs(input,out)
torch.acos(input,out)
torch.cosh(input,out)
torch.cos(input,out)
torch.asin(input,out)
torch.atan(input,out)
torch.atan2(input,other,out)

对于加法

torch.add(  input+alpha*other
input, 第一个张量
alpha=1, 乘项因子
other,第二个张量
out
)

torch.addcmul(  out=input+value*tensor1*tensor2
input,
value,
tensor1,
tensor2,
out
)

torch.addcdiv() out=input+value*(tensor1/tensor2)
t = torch.randn((3, 3))
print(t)
t1 = torch.ones_like(t)
print(t1)
t_add=torch.add(t,10,t1)
print(t_add)

5.简单的线性回归

import torch
import matplotlib.pyplot as plt

torch.manual_seed(10) #随机种子 使得每次运行的结果一样
# 线性回归
lr = 0.05
# 1.创建训练数据
x = torch.randn(20, 1) * 10
y = 2 * x + (5 + torch.randn(20, 1))

# 2.初始化w b
w = torch.randn((1), requires_grad=True)
b = torch.zeros((1), requires_grad=True)

for i in range(1000):
    wx = torch.mul(w, x)
    y_pred = torch.add(wx, b)

    # 计算loss
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向传播
    loss.backward()

    # 更新
    b.data.sub_(lr * b.grad)
    w.data.sub_(lr * w.grad)
    
    #把梯度置0
    w.grad.zero_()
    b.grad.zero_()

    if i % 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=%0.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
        plt.xlim(1.5, 10)
        plt.ylim(8, 28)
        plt.title("i:{}\n w:{} b:{}".format(i, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

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

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值