PYTORCH 系列教程(一)
Author:muzi
将numpy数组转换为张量,或者张量转换为数组
(convert numpy to tensor or vise versa 反之亦然)code
import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3))
print np_data
torch_data = torch.from_numpy(np_data)
print torch_data
tensor2array = torch_data.numpy()
print tensor2array
结果:[[0 1 2]
[3 4 5]]0 1 2
3 4 5
[torch.LongTensor of size 2x3][[0 1 2]
[3 4 5]]元素取绝对值
code
data = [-1, -2, 1, 2]
print data
tensor = torch.FloatTensor(data)
print tensor
print np.abs(data)
print torch.abs(tensor)
结果:[-1, -2, 1, 2]
-1
-2
1
2
[torch.FloatTensor of size 4][1 2 1 2]
1
2
1
2
[torch.FloatTensor of size 4]元素取sin值
code
print np.sin(data)
print torch.sin(tensor)
结果:[-0.84147098 -0.90929743 0.84147098 0.90929743]
-0.8415
-0.9093
0.8415
0.9093
[torch.FloatTensor of size 4]张量元素取sigmoid值
code
print tensor.sigmoid()
结果0.2689
0.1192
0.7311
0.8808
[torch.FloatTensor of size 4]张量元素取指数值
code
print tensor.exp()
结果:0.3679
0.1353
2.7183
7.3891
[torch.FloatTensor of size 4]元素取平均值
code
print np.mean(data)
print torch.mean(tensor)
结果:0.0
0.0
7.列表,张量的矩阵运算data = [[1,2], [3,4]]
print data
print type(data)
tensor = torch.FloatTensor(data)
print np.matmul(data,data)
print type(np.matmul(data,data))
print torch.mm(tensor,tensor)
结果:[[1, 2], [3, 4]]
数据类型是list,可以通过matmul计算list的矩阵运算。
[[ 7 10]
[15 22]]
7 10
15 22
[torch.FloatTensor of size 2x2]数组的矩阵乘法操作;张量的內积运算
code
data = np.array(data)
print data
print type(data) #数据类型是数组,可以通过dot操作计算矩阵运算
print data.dot(data)
tensor = torch.FloatTensor(data)
print tensor
#print tensor.dot(tensor) #不正确的操作,因为维度不匹配
data1 = [1,2,3,4]
print type(data1)
print type(data1)
tensor = torch.FloatTensor(data1)
print tensor
print tensor.dot(tensor) #正确的操作 进行內积运算
结果:[[1 2]
[3 4]]
[[ 7 10]
[15 22]]1 2
3 4
[torch.FloatTensor of size 2x2][1, 2, 3, 4]
1
2
3
4
[torch.FloatTensor of size 4]30.0
张量对应元素相乘
data =[[1,2],[3,4]]
print data
print type(data)
data = np.array(data)
print data # 数据类型:列表与数组区别
print type(data)
tensor = torch.FloatTensor(data)
print tensor.mm(tensor)
print tensor*tensor # 张量元素的对应乘积
data1 = np.arange(1,5)
data2 = np.array([1,2,3,4]) # 两种方式 产生(n,)的数组
print data1
print data2
print type(data1)
print data1.shape
tensor_1D = torch.FloatTensor(data1)
tensor_1D_ = torch.from_numpy(data2) #两种方式 将(n,)的数组转换为 1-D张量
print tensor_1D
print tensor_1D.dot(tensor_1D) # 1-D张量类型数据的內积:对应元素相乘求和
结果:[[1, 2], [3, 4]]
[[1 2]
[3 4]]
#列表与数组的区别 7 10
15 22
[torch.FloatTensor of size 2x2] #张量矩阵乘法
1 4
9 16
[torch.FloatTensor of size 2x2] #张量对应元素相乘
[1 2 3 4]
[1 2 3 4]
<type 'numpy.ndarray'>
(4,)
1
2
3
4
[torch.FloatTensor of size 4]
<class 'torch.FloatTensor'>
30.0
Reference :
莫烦:pytorch教程