参考视频:莫烦python  https://mofanpy.com/tutorials/machine-learning/torch/torch-numpy/

0.Pytorch 安装

官方网站安装链接:https://pytorch.org/get-started/locally/

选择合适的选项,比如想要有 gpu 加速,就选择对应的 cuda 版本。查看自己的 cuda 版本用 nvcc -V 。

将命令输入到命令行即可完成安装。

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]]