数据处理 numpy和pytorch tensor 转换 1234567891011 import torchimport numpy as npnp_data = np.arange(6).reshape((2, 3))torch_data = torch.from_numpy(np_data)tensor2array = torch_data.numpy()print( 'nnumpy array:', np_data, 'ntorch tensor:', torch_data, # 0 1 2 n 3 4 5 [torch.LongTensor of size 2x3] 'ntensor to array:', tensor2array, ) 数学计算 12345678910111213141516171819202122 # abs 绝对值计算data = [-1, -2, 1, 2]tensor = torch.FloatTensor(data) # 转换成32位浮点 tensorprint( 'nabs', 'nnumpy: ', np.abs(data), # [1 2 1 2] 'ntorch: ', torch.abs(tensor) # [1 2 1 2])# sin 三角函数 sinprint( '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])# mean 均值print( 'nmean', 'nnumpy: ', np.mean(data), # 0.0 'ntorch: ', torch.mean(tensor) # 0.0) 矩阵计算 1234567891011121314151617181920 # matrix multiplication 矩阵点乘data = [[1,2], [3,4]]tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor# correct methodprint( 'nmatrix multiplication (matmul)', 'nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]] 'ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]])# !!!! 下面是错误的方法 !!!!data = np.array(data)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)# tensor.dot()在(>= 0.3.0)版本之后只能支持一维数组的内积tensor.dot(tensor) # torch 会转换成 [1,2,3,4].dot([1,2,3,4]) = 30.0 并且 tensor 只能是一维数组tensor 赞微海报分享
近期评论