Pytorch 张量部分小总结

Pytorch 张量学习小结

 

1、张量的创建和维度 2、张量的运算

 

一、创建张量有4中方法:1、由torch.tensor()方法创建 2、由Pytorch内置的函数创建 3、由已知的张量创建形状一致的张量 4、由通过已知的张量创建形状不一致的张量

 

1、由torch.tensor()方法创建

import torch 
import numpy as np

t1 = torch.tensor([1,2,3,4])
print(t1.dtype)
t2 = torch.tensor([1,2,3,4], dtype=torch.int32)
print(t2.dtype)
print(t1.to(torch.int32)) #可以使用to内置方法对张量进行类型转换

t3 = torch.tensor(np.arange(10))
print(t3)
t4 = torch.tensor(range(10))
print("t4 is {}, dtype={}".format(t4, t4.dtype))  #pytorch的整型默认为int64,np的整型默认为in32

t5 = torch.tensor([1.0,2.0,3.0,4.0])
print("t5 is {}, dtype={}".format(t5, t5.dtype))  

t6 = torch.tensor(np.array([1.0,2.0,3.0,4.0]))
print("t6 is {}, dtype={}".format(t6, t6.dtype))  #pytorch的默认浮点类型为float32(单精度),numpy默认为(float64)双精度

t7 = torch.tensor([[1,2,3],[4,5,6]]) #列表嵌套创建
print(t7)

结果:

torch.int64
torch.int32
tensor([1, 2, 3, 4], dtype=torch.int32)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int32)
t4 is tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), dtype=torch.int64
t5 is tensor([1., 2., 3., 4.]), dtype=torch.float32
t6 is tensor([1., 2., 3., 4.], dtype=torch.float64), dtype=torch.float64
tensor([[1, 2, 3],
        [4, 5, 6]]

2、pytorch内置函数创建

torch.rand(), torch.randn(), torch.zeros(), torch.ones(), torch.eye(), torch.randint()等

n1 = torch.rand(3,3) #生成3x3的矩阵,服从[0,1)上的均匀分布
print(n1)
n2 = torch.randn(2,3,3) #生成2x3x3的矩阵,服从标准正态分布
print(n2)
n3 = torch.zeros(2,2) #全零
print(n3)
n4 = torch.ones(2,2,1)
print(n4)
n5 = torch.eye(3) #单位阵
print(n5)
n6 = torch.randint(0,10,(3,3)) #生成3x3矩阵,值从[0,10)均匀分布
print(n6)

结果:

tensor([[0.4672, 0.0484, 0.0256],
        [0.4547, 0.8642, 0.9526],
        [0.4009, 0.2858, 0.3133]])
tensor([[[-0.1942, -1.8865,  0.3309],
         [ 0.8023,  0.1170, -0.1000],
         [ 0.1931,  0.0472,  1.8049]],

        [[ 0.4596,  0.2676,  0.2857],
         [-2.9891,  1.6126, -0.2666],
         [-0.5891, -2.4039, -0.9180]]])
tensor([[0., 0.],
        [0., 0.]])
tensor([[[1.],
         [1.]],

        [[1.],
         [1.]]])
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
tensor([[6, 5, 9],
        [7, 9, 2],
        [2, 2, 4]])

3、由已知张量创建形状相同的张量

torch.zeros_like(), torch.ones_like(), torch.rand_like()

m = torch.zeros_like(n1)
print(m)
m1 = torch.ones_like(n2)
print(m1)
m2 = torch.rand_like(n3)
print(m2)

结果:

tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])
tensor([[[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]],

        [[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]]])
tensor([[0.1613, 0.7150],
        [0.5519, 0.4913]])

4、由已知张量创建不同尺寸的张量

(一般很少用到)

print(t1.new_tensor([1,2,3]))
print(t1.new_zeros(2,3))
print(t1.new_ones(3,3))

结果:

tensor([1, 2, 3])
tensor([[0, 0, 0],
        [0, 0, 0]])
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]])

 

未完待续,将会在后续继续更新

posted @ 2020-07-13 18:28  ASTHNONT  阅读(386)  评论(0编辑  收藏  举报