1. torch简单创建
shape = ( 2 , 3 , )
rand_tensor = torch. rand( shape)
ones_tensor = torch. ones( shape)
zeros_tensor = torch. zeros( shape)
print ( f"Random Tensor: \n {rand_tensor} \n" )
print ( f"Ones Tensor: \n {ones_tensor} \n" )
print ( f"Zeros Tensor: \n {zeros_tensor}" )
2. torch和numpy转换
import torch
import numpy as np
data = [ [ 1 , 2 ] , [ 3 , 4 ] ]
x_data = torch. tensor( data)
np_array = np. array( data)
x_np = torch. from_numpy( np_array)
x_np. numpy( )
3. 创建相似维度Tensor
x_ones = torch. ones_like( x_data)
print ( f"Ones Tensor: \n {x_ones} \n" )
x_rand = torch. rand_like( x_data, dtype= torch. float )
print ( f"Random Tensor: \n {x_rand} \n" )
4. Tensor的基本属性
tensor = torch. rand( 3 , 4 )
print ( f"Shape of tensor: {tensor.shape}" )
print ( f"Datatype of tensor: {tensor.dtype}" )
print ( f"Device tensor is stored on: {tensor.device}" )
5. 查看GPU可获取
if torch. cuda. is_available( ) :
tensor = tensor. to( 'cuda' )
6. 张量拼接
tensor = torch. ones( 4 , 4 )
t1 = torch. cat( [ tensor, tensor, tensor] , dim= 1 )
print ( t1)
7. 张量乘积(对应位置相乘:mul 和 *)
print ( f"tensor.mul(tensor): \n {tensor.mul(tensor)} \n" )
print ( f"tensor * tensor: \n {tensor * tensor}" )
8. 张量矩阵乘法(matmul 和 @)
print ( f"tensor.matmul(tensor.T): \n {tensor.matmul(tensor.T)} \n" )
print ( f"tensor @ tensor.T: \n {tensor @ tensor.T}" )