pytorch实用快速入门(一)

没有系统的学习梳理过pytorch的基本使用方法,之前都是用到哪儿学到哪儿,最近几天准备梳理一下pytorch的简单使用方法

主要参考莫烦python 的pytorch系列学习整理下来方便日后查看

pytorch的tensor与numpy的ndarrray进行转换

# -*- coding:utf-8 -*-

import torch
import numpy as np

np_data = np.arange(6)
#print(np_data) [0 1 2 3 4 5] 
np_data = np_data.reshape(2,3)
#print(np_data) [[0 1 2][3 4 5]] #建立ndarray数组

torch_data = torch.from_numpy(np_data)
#print(torch_data) tensor([[0, 1, 2],[3, 4, 5]]) #将numpy数组转换为tensor

tensor2array = torch_data.numpy()
#print(tensor2array) [[0 1 2][3 4 5]]
#print(tensor2array.dtype) int64 #将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]]
# )

data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 32-bit floating point
#print(tensor) 

# abs
print(
    "\n abs",
    "\n numpy:",np.abs(data),
    "\n tensor:", torch.abs(tensor),
)

# sin
print(
    '\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
)


# matrix multiplication
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  # 32-bit floating point
# print(tensor.type())

tensor2 = tensor.double()
#print(tensor2,tensor2.type()) tensor([[1., 2.], [3., 4.]], dtype=torch.float64) torch.DoubleTensor


# correct method
print(
    '\nmatrix multiplication (matmul)',
    '\nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
    '\ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
)


# incorrect method
data = np.array(data)
print(
    '\nmatrix multiplication (dot)',
    '\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]]
    '\ntorch: ', tensor.dot(tensor)     # this will convert tensor to [1,2,3,4], you'll get 30.0
)

相关的源码主要还是采用莫烦python的源码,并添加自己的一些理解,随后整理完成,自己的代码也会放置在自己github主页上

    原文作者:小哲lxz
    原文地址: https://zhuanlan.zhihu.com/p/64465070
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞