zoukankan      html  css  js  c++  java
  • torch or numpy

    黄色:重点

    粉色:不懂

    1. Torch 自称为神经网络界的 Numpy, 因为他能将 torch 产生的 tensor 放在 GPU 中加速运算 (前提是你有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算. 
      import torch
      import numpy as np
      
      np_data = np.arange(6).reshape((2, 3))
      torch_data = torch.from_numpy(np_data)
      tensor2array = torch_data.numpy()
      print(
          '
      numpy array:', np_data,          # [[0 1 2], [3 4 5]]
          '
      torch tensor:', torch_data,      #  0  1  2 
       3  4  5    [torch.LongTensor of size 2x3]
          '
      tensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
      )

      Torch 中的数学运算

      其实 torch 中 tensor 的运算和 numpy array 的如出一辙, 我们就以对比的形式来看. 如果想了解 torch 中其它更多有用的运算符, API就是你要去的地方.

      # abs 绝对值计算
      data = [-1, -2, 1, 2]
      tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
      print(
          '
      abs',
          '
      numpy: ', np.abs(data),          # [1 2 1 2]
          '
      torch: ', torch.abs(tensor)      # [1 2 1 2]
      )
      
      # sin   三角函数 sin
      print(
          '
      sin',
          '
      numpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
          '
      torch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
      )
      
      # mean  均值
      print(
          '
      mean',
          '
      numpy: ', np.mean(data),         # 0.0
          '
      torch: ', torch.mean(tensor)     # 0.0
      )

      除了简单的计算, 矩阵运算才是神经网络中最重要的部分. 所以我们展示下矩阵的乘法. 注意一下包含了一个 numpy 中可行, 但是 torch 中不可行的方式.

      # matrix multiplication 矩阵点乘
      data = [[1,2], [3,4]]
      tensor = torch.FloatTensor(data)  # 转换成32位浮点 tensor
      # correct method
      print(
          '
      matrix multiplication (matmul)',
          '
      numpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
          '
      torch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
      )
      
      # !!!!  下面是错误的方法 !!!!
      data = np.array(data)
      print(
          '
      matrix multiplication (dot)',
          '
      numpy: ', data.dot(data),        # [[7, 10], [15, 22]] 在numpy 中可行
          '
      torch: ', tensor.dot(tensor)     # torch 会转换成 [1,2,3,4].dot([1,2,3,4) = 30.0
      )
  • 相关阅读:
    绘画字符串
    方法名,类名与字符串之间的转换
    重写视图的点击区域
    ios7新特性
    常用的sq语句
    基于xmpp的ios聊天客户端(一)
    iOS真机测试,为Provisioning添加设备
    【IOS 开发】Object-C 运算符
    【Android 应用开发】 自定义组件 宽高适配方法, 手势监听器操作组件, 回调接口维护策略, 绘制方法分析 -- 基于 WheelView 组件分析自定义组件
    博客技术资料整理
  • 原文地址:https://www.cnblogs.com/CATHY-MU/p/7800771.html
Copyright © 2011-2022 走看看