Numpy np.dot() vs np.multiply() vs *

来源:互联网 发布:淘宝店铺信誉怎么算 编辑:程序博客网 时间:2024/05/29 08:56

先放结论

数据类型 * dot() multiply() array 点乘 矩阵乘(2D),内积(1D, 结果是Scalar标量) 点乘 mat 矩阵乘 矩阵乘 点乘
# -*- coding: utf-8 -*-# Created At 2017-09-11 15:01# Author: LCAR979 <tcoperator@163.com># Version: 1.0# License: GPL 2.0# Description: a numpy demo program shows dot() vs multiply vs *# Python 2.7, NumPy 1.13# What offical doc says:# NumPy v1.13# https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html# numpy.dot(a, b, out=None)# Dot product of two arrays# For 2-D arrays it is equivalent to matrix multiplication,# and for 1-D arrays to inner product of vectors (without complex conjugation).# For N dimensions it is a sum product over the last axis of a# and the second-to-last of b:## dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])import numpy as nparr_2D_a = np.array([[1, 2], [3, 4]])arr_2D_b = np.array([[5, 6], [7, 8]])# 2D casesprint '\n2D cases:\n'print 'arr_2D_a * arr_2D_b = 'print arr_2D_a * arr_2D_bprint 'np.dot(arr_2D_a, arr_2D_b) = 'print np.dot(arr_2D_a, arr_2D_b)print 'np.multiply(arr_2D_a, arr_2D_b) = 'print np.multiply(arr_2D_a, arr_2D_b)mat_2D_a = np.mat([[1, 2], [3, 4]])mat_2D_b = np.mat([[5, 6], [7, 8]])print 'mat_2D_a * mat_2D_b = 'print mat_2D_a * mat_2D_bprint 'np.dot(mat_2D_a, mat_2D_b) = 'print np.dot(mat_2D_a, mat_2D_b)print 'np.multiply(mat_2D_a, mat_2D_b) = 'print np.multiply(mat_2D_a, mat_2D_b)# 1D casesprint '\n1D cases\n'arr_1D_a = np.array([1, 2])arr_1D_b = np.array([5, 6])print 'arr_1D_a * arr_1D_b = 'print arr_1D_a * arr_1D_bprint 'np.dot(arr_1D_a, arr_1D_b) = 'print np.dot(arr_1D_a, arr_1D_b)print 'np.dot(arr_1D_a, arr_1D_b.T) = 'print np.dot(arr_1D_a, arr_1D_b.T)print 'np.multiply(arr_1D_a, arr_1D_b) = 'print np.multiply(arr_1D_a, arr_1D_b)mat_1D_a = np.mat([1, 2])mat_1D_b = np.mat([5, 6])print 'mat_1D_a * mat_1D_b.T = 'print mat_1D_a * mat_1D_b.T# print mat_1D_a * mat_1D_b -> Value Errorprint 'np.dot(mat_1D_a, mat_1D_b.T) = 'print np.dot(mat_1D_a, mat_1D_b.T)# print np.dot(mat_1D_a, mat_1D_b) -> Value Errorprint 'np.multiply(mat_1D_a, mat_1D_b) = 'print np.multiply(mat_1D_a, mat_1D_b)# Conclusion:# * has different meaning :# inner-product for array, matrix-multiplication for matrix# np.dot() for 1D input array, calculate inner product
2D cases:arr_2D_a * arr_2D_b = [[ 5 12] [21 32]]np.dot(arr_2D_a, arr_2D_b) = [[19 22] [43 50]]np.multiply(arr_2D_a, arr_2D_b) = [[ 5 12] [21 32]]mat_2D_a * mat_2D_b = [[19 22] [43 50]]np.dot(mat_2D_a, mat_2D_b) = [[19 22] [43 50]]np.multiply(mat_2D_a, mat_2D_b) = [[ 5 12] [21 32]]1D casesarr_1D_a * arr_1D_b = [ 5 12]np.dot(arr_1D_a, arr_1D_b) = 17np.dot(arr_1D_a, arr_1D_b.T) = 17np.multiply(arr_1D_a, arr_1D_b) = [ 5 12]mat_1D_a * mat_1D_b.T = [[17]]np.dot(mat_1D_a, mat_1D_b.T) = [[17]]np.multiply(mat_1D_a, mat_1D_b) = [[ 5 12]]
数据类型 * dot() multiply() array 点乘 矩阵乘(2D),内积(1D, 结果是Scalar标量) 点乘 mat 矩阵乘 矩阵乘 点乘
原创粉丝点击