PyTorch基础

1 PyTorch中的张量概念与定义

2020-04-14  本文已影响0人  熊出没之熊二快跑

1 什么是张量

张量是一个多维数组,他是标量、向量、矩阵的高维拓展


标量、向量、矩阵和张量

2 Tensor与Variable

2.1Variable

Variable
Variabletorch.autograd中的数据类型,主要用于封装Tensor,进行自动求导

2.2 Tensor

Tensor
PyTorch0.4.0版本开始,Variable并入Tensor,总共8个参数,上面四个与数据有关,下面四个与梯度有关

3 张量的三种创建方法

3.1 直接创建

输入:

import torch
import numpy as np
Flag = False
# ===================== example 1 =============================
# 通过torch.tensor创建张量
Flag = True
if Flag:
    arr = np.ones((3, 3))
    print("ndarray的数据类型:", arr.dtype)

    # t = torch.tensor(arr)
    t = torch.tensor(arr, device='cuda')
    print(t)

输出:

ndarray的数据类型: float64
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], device='cuda:0', dtype=torch.float64)

Process finished with exit code 0

输入:

# ===================== example 2 =============================
# 通过torch.from_numpy创建张量
Flag = True
if Flag:
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    t = torch.from_numpy(arr)
    print("NDarray:", arr)
    print("Tensor:", t)
    print("\n")

    print("修改arr中的数据:")
    arr[0, 0] = 888
    print("NDarray:", arr)
    print("Tensor:", t)
    print("\n")

    print("修改tensor中的数据:")
    t[0, 1] = 999
    print("NDarray:", arr)
    print("Tensor:", t)
    print("\n")

输出:

NDarray: [[1 2 3]
 [4 5 6]]
Tensor: tensor([[1, 2, 3],
        [4, 5, 6]], dtype=torch.int32)


修改arr中的数据:
NDarray: [[888   2   3]
 [  4   5   6]]
Tensor: tensor([[888,   2,   3],
        [  4,   5,   6]], dtype=torch.int32)


修改tensor中的数据:
NDarray: [[888 999   3]
 [  4   5   6]]
Tensor: tensor([[888, 999,   3],
        [  4,   5,   6]], dtype=torch.int32)

3.2 依据数值创建张量

输入:

# ===================== example 3 =============================
# 通过torch.zeros创建张量
# Flag = True
if Flag:
    out_t = torch.tensor([1])
    t = torch.zeros((3, 3), out=out_t)  # 将生成的张量赋给out

    print(t, "\n", out_t)
    print(id(t), id(out_t), id(t)==id(out_t))

输出:

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2585763895552 2585763895552 True
# ===================== example 4 =============================
# 通过torch.full创建张量
Flag = True
if Flag:
    t = torch.full((3, 3), 10)
    print(t)

输出:

tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]) 
 tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
2585763895552 2585763895552 True
tensor([[10., 10., 10.],
        [10., 10., 10.],
        [10., 10., 10.]])

3.3 根据概率分布创建张量

上一篇下一篇

猜你喜欢

热点阅读