参考视频:莫烦python https://mofanpy.com/tutorials/machine-learning/torch/torch-numpy/
0.Pytorch 安装
1.Numpy 和 Pytorch
# -*- coding: utf-8 -*-
import torch
import numpy as np
np_data = np.arange(6).reshape((2,3)) # numpy数据
torch_data = torch.from_numpy(np_data) # numpy -> torch
torch2array = torch_data.numpy() # torch -> numpy
print(
'\nnumpy',np_data,
'\ntorch',torch_data,
'\ntensor2array',torch2array
)
numpy [[0 1 2]
[3 4 5]]
torch tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
tensor2array [[0 1 2]
[3 4 5]]
# abs 绝对值计算
data = [-1,-2,1,2]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
# http://pytorch.org/docs/torch.html#math-operations
print(
'\n绝对值',
'\nnumpy: ', np.abs(data), # [1 2 1 2]
'\ntorch: ', torch.abs(tensor) # tensor([1., 2., 1., 2.])
)
绝对值
numpy: [1 2 1 2]
torch: tensor([1., 2., 1., 2.])
# 矩阵点乘
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)
print(
'\n矩阵相乘',
'\nnumpy: ', np.matmul(data, data),
'\ntorch: ', torch.mm(tensor, tensor)
)
data = np.array(data)
print(
'\n矩阵相乘',
'\nnumpy: ', data.dot(data),
#'\ntorch: ', tensor.dot(tensor) 错误的方法 只能针对一维度
)
矩阵相乘
numpy: [[ 7 10]
[15 22]]
torch: tensor([[ 7., 10.],
[15., 22.]])
矩阵相乘
numpy: [[ 7 10]
[15 22]]
评论(0)
您还未登录,请登录后发表或查看评论