sem是什么?,南阳网站seo公司,wordpress 写文章 插件,佛山市制作网站点赞收藏关注#xff01; 如需转载请注明出处#xff01; 张量与数组和矩阵非常相似。 在PyTorch中#xff0c;使用张量来编码模型的输入和输出#xff0c;以及模型的参数。 张量可以在GPU或其他硬件加速器上运行。 张量和NumPy数组通常可以共享相同的底层内存#xff0c… 点赞收藏关注 如需转载请注明出处 张量与数组和矩阵非常相似。 在PyTorch中使用张量来编码模型的输入和输出以及模型的参数。 张量可以在GPU或其他硬件加速器上运行。 张量和NumPy数组通常可以共享相同的底层内存从而消除了复制数据的需要。 对自动微分进行了优化。 一 Tensor构建
张量可以直接从数据中创建。数据类型是自动推断的
import torch
import numpy as np
data [[1, 2],[3, 4]]
x_data torch.tensor(data)张量可以从NumPy数组中创建
np_array np.array(data)
x_np torch.from_numpy(np_array)从另一个tensor创建
#新张量保留参数张量的属性(形状数据类型)
x_ones torch.ones_like(x_data) # 保留x_data的属性
print(fOnes Tensor: \n {x_ones} \n)
x_rand torch.rand_like(x_data, dtypetorch.float) # 重写x_data的数据类型
print(fRandom Tensor: \n {x_rand} \n)随机量或者常量初始化
shape (2,3,)#决定了输出张量的维数
rand_tensor torch.rand(shape)
ones_tensor torch.ones(shape)
zeros_tensor torch.zeros(shape)
print(fRandom Tensor: \n {rand_tensor} \n)
print(fOnes Tensor: \n {ones_tensor} \n)
print(fZeros Tensor: \n {zeros_tensor})二Tensor常用操作
张量属性描述它们的形状、数据类型和存储它们的设备 tensor torch.rand(3,4)
print(fShape of tensor: {tensor.shape})
print(fDatatype of tensor: {tensor.dtype})
print(fDevice tensor is stored on: {tensor.device})将Tensor转到GPU上
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor tensor.to(cuda)
Tensor索引
tensor torch.ones(4, 4)
print(First row: ,tensor[0])
print(First column: , tensor[:, 0])
print(Last column:, tensor[..., -1])
tensor[:,1] 0
print(tensor)Tensor连接concatenate
t1 torch.cat([tensor, tensor], dim1)
print(t1)
Tensor与NumPy相互转换
t torch.ones(5)
print(ft: {t})
n t.numpy()
print(fn: {n})
tt torch.from_numpy(n)
print(ft:{tt})数学运算
#计算两个张量之间的矩阵乘法。Y1 y2 y3的值是一样的
y1 tensor tensor.T
y2 tensor.matmul(tensor.T)
y3 torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, outy3)
print(fy1: {y1})
print(fy2: {y2})
print(fy3: {y3})#它计算元素的乘积。z1 z2 z3的值是一样的
z1 tensor * tensor
z2 tensor.mul(tensor)
z3 torch.rand_like(tensor)
torch.mul(tensor, tensor, outz3)
print(fz1: {z1})
print(fz2: {z2})
print(fz3: {z3})如有帮助点赞收藏关注