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 )

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

  • 相关阅读:
    一个主板上连接两个都有引导的盘
    pytorch查看模型weight与grad
    linux终端窗口字体缩放快捷键
    vim选中多行缩进(python多行缩进)与删除多行前面的空格
    python import 包的路径以及相对路径加载的问题
    pycharm中添加PATH变量
    Atom选中多行操作
    php扩展 swoole的安装与使用
    12121212
    linux系统下清理所有Redis缓存
  • 原文地址:https://www.cnblogs.com/dhName/p/11742856.html
Copyright © 2011-2022 走看看