[Pytorch] What is tensor (1)

Learning Content:

Features of lists, numpy arrays, and tensors

The shape of the image tensor

The method of creating tensor

The four major operations of tensor


1. Features of lists, numpy arrays, and tensor

code show as below:

import torch
import numpy as np

# print(torch.__version__)
# print(torch.cuda.is_available())
# print(torch.version.cuda)

# 创建一个列表
dd=[
    [1,2,3],
    [4,5,6],
    [7,8,9]
    ]
# 输出列表:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(str(dd)+"\n")
# 输出类型:列表"<class 'list'>"
# !!!列表没有shape属性

print(str(type(dd))+"\n")
# 转为numpy的n维数组
npdd=np.array(dd)
# 输出numpy的n维数组:
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]]
print(str(npdd)+"\n")
# 输出类型:numpy的n维数组"<class 'numpy.ndarray'>"
print(str(type(npdd))+"\n")
# 输出shape:(3, 3)
print(str(npdd.shape)+"\n")

# 转为张量(cuda)
t=torch.tensor(dd).cuda()
# 输出张量:
# tensor([[1, 2, 3],
#         [4, 5, 6],
#         [7, 8, 9]], device='cuda:0')
print(str(t)+"\n")
# 输出类型:# <class 'torch.Tensor'>
print(str(type(t))+"\n")
# 输出shape:torch.Size([3, 3])
print(str(t.shape)+"\n")

# reshape张量
r=t.reshape(1,9)
# 输出新张量:tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9]], device='cuda:0')
print(str(r)+"\n")
# 输出shape:torch.Size([1, 9])
print(str(r.shape)+"\n")

# 输出数据类型
print(str(t.dtype)+"\n")
# 输出设备
print(str(t.device)+"\n")
#输出布局
print(str(t.layout)+"\n")

# 创建device
device=torch.device("cuda:0")
# 输出device
print((str(device)+"\n"))

The output is as follows:

D:\pytorch\pytorchbasis\venv\Scripts\python.exe D:\pytorch\pytorchbasis\tensorIntroduction.py

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

<class 'list'>

[[1 2 3]

[4 5 6]

[7 8 9]]

<class 'numpy.ndarray'>

(3, 3)

tensor([[1, 2, 3],

[4, 5, 6],

[7, 8, 9]], device='cuda:0')

<class 'torch.Tensor'>

torch.Size([3, 3])

tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9]], device='cuda:0')

torch.Size([1, 9])

torch.int64

cuda:0

torch.strided

cuda:0

Process ended with exit code 0

2. The shape of the image tensor

B: BATCH SIZE batch quantity
C: COLOR CHANNEL color channel
H: HEIGHT height
W: WIDTH width

3. The method of creating tensor

Fourth, the four major operations of tensor

1.Reshaping operations

2.Element-wise operations

Guess you like

Origin blog.csdn.net/weixin_66896881/article/details/128583365
Recommended