zoukankan      html  css  js  c++  java
  • Python中的几种矩阵乘法(转)

    一.  np.dot()

    1.同线性代数中矩阵乘法的定义。np.dot(A, B)表示:

    • 对二维矩阵,计算真正意义上的矩阵乘积。
    • 对于一维矩阵,计算两者的内积。

    2.代码

     【code】

    import numpy as np
    
    # 2-D array: 2 x 3
    two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
    # 2-D array: 3 x 2
    two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])
    
    two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
    print('two_multi_res: %s' %(two_multi_res))
    
    # 1-D array
    one_dim_vec_one = np.array([1, 2, 3])
    one_dim_vec_two = np.array([4, 5, 6])
    one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
    print('one_result_res: %s' %(one_result_res))

     【result】

    two_multi_res: [[22 28]
                    [49 64]]
    one_result_res: 32

    二. np.multiply()或 *

    1.在Python中,实现对应元素相乘(element-wise product),有2种方式,

    • 一个是np.multiply()
    • 另外一个是 *

    2.代码

    【code】

    import numpy as np
    
    # 2-D array: 2 x 3
    two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
    another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])
    
    # 对应元素相乘 element-wise product
    element_wise = two_dim_matrix_one * another_two_dim_matrix_one
    print('element wise product: %s' %(element_wise))
    
    # 对应元素相乘 element-wise product
    element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
    print('element wise product: %s' % (element_wise_2))

     【result】

    element wise product: [[ 7 16 27]
                           [16 35  6]]
    element wise product: [[ 7 16 27]
                           [16 35  6]]

    --------------------------------------

    参考链接:

    1. http://blog.csdn.net/u012609509/article/details/70230204
  • 相关阅读:
    动态图片 Movie android-gif-drawable GifView
    X5SDK 腾讯浏览器内核
    AS 自动生成选择器 SelectorChapek
    Genymotion 模拟器 VirtualBox
    360加固保 安全防护 多渠道打包
    Thread 如何安全结束一个线程 MD
    面试题 HashMap 数据结构 实现原理
    nGrinder3.4 性能测试框架安装
    java内存泄漏的定位与分析
    JVM总结-内存监视手段及各区域内存溢出解决
  • 原文地址:https://www.cnblogs.com/hezhiyao/p/8177832.html
Copyright © 2011-2022 走看看