0
点赞
收藏
分享

微信扫一扫

PyTorch入门使用

1. 张量 Tensor

2. PyTorch 中张量的创建

import torch

a = torch.tensor([[1, -1], [2, 3]])
print(a, type(a))

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]]) <class 'torch.Tensor'>
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, type(a))

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32) <class 'torch.Tensor'>
# 创建3x4的空张量,用无用数据填充
torch.empty(3, 4)
# 创建3x4的全是1的张量
torch.ones([3, 4])
# 创建3x4的全是0的张量
torch.zeros([3, 4])
# 创建3x4的全是随机数的张量,随机区间[0, 1)
torch.rand([3, 4])
# 创建3x4的随机整数张量,随机区间[low, high)
torch.randint(low=0, high=10, size=[3, 4])
# 创建3x4的随机数张量,随机值得分布均值为0,方差为1
torch.randn([3, 4])

3. PyTorch 中的常用方法

import torch
import numpy as np

a = torch.tensor(np.arange(1))
print(a)
print(a.item())

# 输出结果
tensor([0], dtype=torch.int32)
0
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.numpy())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
[[ 1 -1]
 [ 2  3]]
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.size())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
torch.Size([2, 2])
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
b = a.view((1, 4))
print(b)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
tensor([[ 1, -1,  2,  3]], dtype=torch.int32)
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a)
print(a.dim())
print(a.max())
print(a.t())

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32)
2
tensor(3, dtype=torch.int32)
tensor([[ 1,  2],
        [-1,  3]], dtype=torch.int32)
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a[1, 0])
a[1, 0] = 100
print(a)

# 输出结果
tensor(2, dtype=torch.int32)
tensor([[  1,  -1],
        [100,   3]], dtype=torch.int32)

4. Tensor 的数据类型

关于数据类型的常用方法:

import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]))
print(a, a.dtype)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32) torch.int32
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.float32)
print(a, a.dtype)

# 输出结果
tensor([[ 1., -1.],
        [ 2.,  3.]]) torch.float32
import torch
import numpy as np

a = torch.tensor(np.array([[1, -1], [2, 3]]), dtype=torch.int32)
print(a, a.dtype)
a = a.type(torch.float)
print(a, a.dtype)

# 输出结果
tensor([[ 1, -1],
        [ 2,  3]], dtype=torch.int32) torch.int32
tensor([[ 1., -1.],
        [ 2.,  3.]]) torch.float32

 

举报

相关推荐

0 条评论