[Pytorch]何为tensor(一)

学习内容:

列表、numpy数组、tensor的特性

图像张量的shape

创建tensor的方法

tensor的四大操作


一、列表、numpy数组、tensor的特性

代码如下:

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"))

输出如下:

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

进程已结束,退出代码0

二、图像张量的shape

B:BATCH SIZE批数量
C:COLOR CHANNEL颜色通道
H:HEIGHT高度
W:WIDTH宽度

三、创建tensor的方法

四、tensor的四大操作

1.Reshaping operations

2.Element-wise operations

猜你喜欢

转载自blog.csdn.net/weixin_66896881/article/details/128583365