1. torch类型numpy的互相转换
import numpy as np
import tensorflow as tf
import torch
np_data = np.arange(6).reshape((2, 3)) #(2,3)
torch_data = torch.from_numpy(np_data) #转换成tensor
tensor2array = torch_data.numpy() #tensor—>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]]
)
2.sin,mean,abs等函数的语法,torch和numpy保持了一致性
data=[-1,-2,1,2]
tensor=torch.FloatTensor(data)#把data变成张量
print(
"\nabs",
"\nnumpy:",np.abs(data),
"\ntorch:",torch.abs(tensor)
)
#sin
print('\nsin',
'\nnumpy: ',np.sin(data),
"\ntorch:",torch.sin(tensor))
#mean
print("\nmena",
"\nnumpy:",np.mean(data),
"\ntorch:",torch.mean(tensor))
3.矩阵相乘
data=[[1,2],[3,4]]
tensor=torch.FloatTensor(data)
print('\nmatrix multiplication (matmul)',
'\nnumpy: ',np.matmul(data,data),
"\ntorch:",tensor@tensor, #这个方法莫烦在视频中没有说道
"\ntorch:", torch.mm(tensor,tensor))
在此注意一点,视频中未提到tensor@tensor,但是确实存在(如有错误,欢迎指出)
4.不一致的点
data=[[1,2],[3,4]]
data=np.array(data)
tensor=torch.FloatTensor(data)
print(
'\nmatrix multiplication (dot)',
'\nnumpy: ',data.dot(data),
"\ntorch:",tensor.dot(tensor))
这里报错,因为tensor只能针对一维的数组
————————————————————————————————————————————————
我是一名机器学习的初学者,是万千小白中努力学习的一员(刚涉机器学习的坑,如有错误,希望指出,共同进步)