title: Pytorch学习笔记-numpy和torch的数据格式
numpy和torch的数据格式学习笔记
"""
对比学习numpy与tensor数据格式
"""
import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data) # numpy转torch
tensor2array = torch_data.numpy() # torch数据格式转numpy
print(
'\nnumpy array:', np_data, # [[0 1 2], [3 4 5]]
'\ntorch tensor:', torch_data, # 0 1 2 \n 3 4 5 [torch.LongTensor of size 2x3]
'\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
)
# ------------------------torch运算-------------------------#
'''
官网API:https://pytorch.org/docs/stable/torch.html
'''
# abs 绝对值计算
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
print(
'\nabs',
'\nnumpy: ', np.abs(data), # [1 2 1 2]
'\ntorch: ', torch.abs(tensor) # [1 2 1 2]
)
# sin 三角函数 sin
print(
'\nsin',
'\nnumpy: ', np.sin(data), # [-0.84147098 -0.90929743 0.84147098 0.90929743]
'\ntorch: ', torch.sin(tensor) # [-0.8415 -0.9093 0.8415 0.9093]
# numpy数据最长小数点后9位,tensor最长小数点后4位
)
# mean 均值
print(
'\nmean',
'\nnumpy: ', np.mean(data), # 0.0
'\ntorch: ', torch.mean(tensor) # 0.0
)
# --------------矩阵运算------------------#
# matrix multiplication 矩阵点乘
data = [[1, 2], [3, 4]]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
# correct method
print(
'\nmatrix multiplication (matmul)',
'\nnumpy: ', np.matmul(data, data), # numpy计算矩阵方法 [[7, 10], [15, 22]]
'\ntorch: ', torch.mm(tensor, tensor) # torch计算矩阵方法 [[7., 10.], [15., 22.]]
)
# !!!! 下面是错误的方法 !!!!
data = np.array(data) # array格式
print(
'\nmatrix multiplication (dot)',
'\nnumpy: ', data.dot(data), # [[7, 10], [15, 22]] 在numpy 中可行
# '\ntorch: ', tensor.dot(tensor) # torch 会转换成 [1,2,3,4].dot([1,2,3,4) = 30.0,这句有问题
)
a = np.arange(3 * 4 * 5 * 6).reshape((3, 4, 5, 6))
b = np.arange(3 * 4 * 5 * 6)[::-1].reshape((5, 4, 6, 3))
# 2D以上,np.dot(a, b)相当于sum(a * b)
print("result = {}".format(np.dot(a, b)[2, 3, 2, 1, 2, 2]))
print(f"result2 = {sum(a[2, 3, 2, :] * b[1, 2, :, 2])}")