pytorch学习笔记(1)-从创建Tensor开始

文章目录

      • 创建Tensor
        • 1.基本创建
        • 2.创建特殊值
        • 3.创建随机值和特定序列Tensor
        • 4.Numpy转Tensor
        • 5.Tensor转Numpy

创建Tensor


pytorch学习的最基础的学习就从创建张量开始。

1.基本创建

import torch
#根据值创建
a = torch.Tensor([[1, 2],[3, 4]])
print(a)

#根据形状创建,随机初始
b = torch.Tensor(2, 2)
print(b)

d = torch.tensor(((1, 2), (3, 4)))
print(d.type())
print(d.type_as(a))

tensor([[1., 2.],
[3., 4.]])
torch.FloatTensor
tensor([[1., 2.],
[3., 4.]])
torch.LongTensor
tensor([[1., 2.],
[3., 4.]])

2.创建特殊值

#创建空Tensor
d = torch.empty(2,3)
print(d.type())
print(d.type_as(a))

#创建0值Tensor
d = torch.zeros(2,3)
print(d.type())
print(d.type_as(a))

#同形状的0值Tensor
d = torch.zeros_like(d)
print(d.type())
print(d.type_as(a))

#对角线为1
d = torch.eye(2, 2)
print(d.type())
print(d.type_as(a))

#全1
d = torch.ones(2, 2)
print(d.type())
print(d.type_as(a))

d = torch.ones_like(d)
print(d.type())
print(d.type_as(a))

torch.FloatTensor
tensor([[0., 0., 0.],
[0., 0., 0.]])

torch.FloatTensor
tensor([[0., 0., 0.],
[0., 0., 0.]])

torch.FloatTensor
tensor([[0., 0., 0.],
[0., 0., 0.]])

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

torch.FloatTensor
tensor([[1., 1.],
[1., 1.]])

torch.FloatTensor
tensor([[1., 1.],
[1., 1.]])

3.创建随机值和特定序列Tensor

#0-1随机值
d = torch.rand(2, 3)
print(d.type())
print(d.type_as(a))

d = torch.arange(2, 10, 2)
print(d.type())
print(d.type_as(a))

d = torch.linspace(10, 2, 3)
print(d.type())
print(d.type_as(a))

dd = torch.normal(mean=0, std=1, size=(2, 3), out=b)
print(b)
print(dd)

d = torch.normal(mean=torch.rand(5), std=torch.rand(5))
print(d.type())
print(d.type_as(a))


d = torch.Tensor(2, 2).uniform_(-1, 1)
print(d.type())
print(d.type_as(a))


d = torch.randperm(10)
print(d.type())
print(d.type_as(a))

torch.FloatTensor
tensor([[0.6432, 0.4434, 0.3289],
[0.6581, 0.7615, 0.6703]])

torch.LongTensor
tensor([2., 4., 6., 8.])

torch.FloatTensor
tensor([10., 6., 2.])

tensor([[-0.4051, -0.5710, -1.3798],
[ 0.3047, -0.3695, -0.2271]])

tensor([[-0.4051, -0.5710, -1.3798],
[ 0.3047, -0.3695, -0.2271]])

torch.FloatTensor
tensor([0.4624, 1.2237, 1.1937, 1.3881, 0.5219])

torch.FloatTensor
tensor([[ 0.9237, 0.2990],
[-0.5562, -0.2350]])

torch.LongTensor
tensor([2., 7., 4., 3., 5., 6., 9., 1., 0., 8.])

4.Numpy转Tensor

a = torch.ones(5)
b = a.numpy()    
a.add_(1)
print(a)
print(b)

tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]

5.Tensor转Numpy

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1,out = a)
print(a)
print(b)

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

你可能感兴趣的:(深度学习框架,numpy,python,人工智能,深度学习)