zoukankan      html  css  js  c++  java
  • pytorch之 compare with numpy

     1 import torch
     2 import numpy as np
     3 
     4 # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations
     5 
     6 # convert numpy to tensor or vise versa
     7 np_data = np.arange(6).reshape((2, 3))
     8 torch_data = torch.from_numpy(np_data)
     9 tensor2array = torch_data.numpy()
    10 print(
    11     '
    numpy array:', np_data,          # [[0 1 2], [3 4 5]]
    12     '
    torch tensor:', torch_data,      #  0  1  2 
     3  4  5    [torch.LongTensor of size 2x3]
    13     '
    tensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
    14 )
    15 
    16 
    17 # abs
    18 data = [-1, -2, 1, 2]
    19 tensor = torch.FloatTensor(data)  # 32-bit floating point
    20 print(
    21     '
    abs',
    22     '
    numpy: ', np.abs(data),          # [1 2 1 2]
    23     '
    torch: ', torch.abs(tensor)      # [1 2 1 2]
    24 )
    25 
    26 # sin
    27 print(
    28     '
    sin',
    29     '
    numpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
    30     '
    torch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
    31 )
    32 
    33 # mean
    34 print(
    35     '
    mean',
    36     '
    numpy: ', np.mean(data),         # 0.0
    37     '
    torch: ', torch.mean(tensor)     # 0.0
    38 )
    39 
    40 # matrix multiplication
    41 data = [[1,2], [3,4]]
    42 tensor = torch.FloatTensor(data)  # 32-bit floating point
    43 # correct method
    44 print(
    45     '
    matrix multiplication (matmul)',
    46     '
    numpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
    47     '
    torch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
    48 )
    49 # incorrect method
    50 data = np.array(data)
    51 print(
    52     '
    matrix multiplication (dot)',
    53     '
    numpy: ', data.dot(data),        # [[7, 10], [15, 22]]
    54     '
    torch: ', tensor.dot(tensor)     # this will convert tensor to [1,2,3,4], you'll get 30.0
    55 )

     仅为自己练习,没有其他用途

  • 相关阅读:
    2017.10.25总结与回顾
    2017.10.24总结与回顾
    CSS盒子模型
    2017.10.23学习知识总结回顾及编写新网页
    JAVA与mysql之间的编码问题
    想写好代码,送你三个神器
    Vue+highligh.js实现语法高亮(转)
    Vue.JS实现复制到粘帖板功能
    npm install、npm install --save与npm install --save-dev区别(转)
    ES7与ES8新特性
  • 原文地址:https://www.cnblogs.com/dhName/p/11742856.html
Copyright © 2011-2022 走看看