PyTorch代码学习笔记1

目录

tensor的维度

 random tensors

Zeros and ones 

Creadting a range of tensors and tensors-like

tensor的维度

对于tensor的dimension容易困惑, 对于[2,2] 而言,是一个1-dimension, 但是如果是[[2,2],[3,2]] 来说是2-dimension. 其实感觉可以用我们常用的维度来看,一个平面就是一维, 两个就是2维,可以使用ndim来查看, 如果要看形状的话可以用.shape来看. 

 random tensors

### Random tensors, they are important because the way many neural networks learn is that they stray with tensors full of random numbers and then adjust those random numbers to better represent the data

# Create a random tensor of size (3,4) 
random_tensor=torch.rand(3,4) 
random_tensor

# For a picture, it will be 
random_tensor = torch.rand (size=(3, 224,224))

Zeros and ones 

zeros = torch.zeros (size=(3,4))
zeros

ones= torch.ones(size=(3,4))
ones

Creadting a range of tensors and tensors-like

# Use torch.range() 
torch.arrange(1,10)  #The output will be tensor ([1,2,3,4,5,6,7,8,9,10])
one_to_ten = torch.arrange(start=1, end=11, step=1) #the output is the same

# Crediting tensors like 生成相似形状的tensor,不过都为0 
ten_zeros = torch.zeros_like(input=one_to_ten) 

在使用tensor的时候存在三个主要类型的错误: 1. tensors不是正确的数据类型 2. tensors不是正确的形状(shape) 3. tensor没有使用正确的device

’‘’Tensor Datatypes‘’‘
# Float 32 tensor 有不同类型的数据形式,其中最常用的数据类型是32-bit floating point, 数据的不同类型代表了数据的精度不同, 数据类型是pytorch和深度学习中很重要的一个内容
float_32_tensor = torch.tensor ([3.0, 4.0], dtype=None, device=None, require_grad=False) 
#device可以是CPU,也可以是GPU

#改变数据类型 把32 bit修改为16 bit
float_16_tensor = float_32_tensor.type(torch.float16) 

当出现了这些错误以后,如何使用代码查出问题  1. tensors的数据类型不正确 tensor.dtype  2. Tensors不是正确的形状(shape), tensor.shape 3. tensor没有正确使用正确的device, tensor.device

#create a tensor 
some_tensor = torch.rand (3,4)

# Find out details about some tensor 
print(some_tensor)
print(f"Datatype of tensor: {some_tensor.dtype}")
print(f"Shape of tensor:{some_tensor.size}")
print(f"Device tensor is on: {some_tensor.device}")

Tensor的基本运算: 加, 减, 乘,除, 矩阵点乘(matrix multiplication)

# Create a tensor and add 10 to it 
tensor = torch.tensor ([1,2,3])
tensor+10

# Multiply tensor by 10 
tensor *10

#Substract 10 
tensor - 10

# Try out Pytorch in-bulit function 
torch.mul(tensor,10)

# Element wise multiplication 分别对对应的数进行相乘,得到一个矩阵
print(tensor,"*", tensor)
print(f"Equals:{tensor*tensor}")


#矩阵的相乘,最后得到的数据是根据矩阵乘法得到的结果, matmul的计算比较快,节省时间
torch.matmul(tensor,tensor)

找到tensor的min,max,mean, sum, etc (tensor aggregation)

# find the min 
x= tensor.arrange(0,100,10) 
torch.min(x)

#find the max 
torch.max(x) 

# find the mean,注意在这里的时候因为需要计算平均值,可能需要提前对数据类型进行转化
torch.mean(x) #这个可能会有报错
torch.mean(x.type(torch.float32)), x.type(torch.float).mean()

#find the sum 
torch.sum(x), x.sum()

找到最大和最小值的位置

#首先找到这个最大值的数值
x.argmin()
#然后根据这个数值来定位
x[0] #比如说这个最大值是0,然后找到这个0的位置

猜你喜欢

转载自blog.csdn.net/weixin_44897685/article/details/130734307