简体   繁体   English

我如何在 python 中进行点生产?

[英]how can i do dot production in python?

Write the function dot_product(M, N), that takes as parameters two matrices M and N, and returns a new matrix containing dot product of these matrices.编写函数 dot_product(M, N),它将两个矩阵 M 和 N 作为参数,并返回一个包含这些矩阵点积的新矩阵。

I understand the logic but not sure how to do the multiply each rows and columns this is what i have so far我理解逻辑,但不知道如何将每一行和每一列相乘,这是我目前所拥有的

def dot_product(M, N):

    """ takes as parameters two matrices M and N, and returns a new matrix
        containing dot product of these matrices
    """

    assert( len(M[0]) == len(N)), " innter length differnet " 

    new_matrix = zeros(len(M[0]) , len(N))

    transP = transpose(N)

    storing_values = []

    for r in range(len(M)):

        for c in range(len(M[0])):

            storing_values += M[r][c] * transP[r][c]

I'm using helper function transpose to rotate the matrix N so when i iterate I'm looking at same columns and rows for both matrices.我正在使用辅助函数转置来旋转矩阵 N,因此当我迭代时,我正在查看两个矩阵的相同列和行。

output should look like this : [[26.00, 4.00] [62.00, 13.00]]输出应如下所示:[[26.00, 4.00] [62.00, 13.00]]

Using the numpy in-built dot product function looks easy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html使用 numpy 内置点积函数看起来很容易: https : //docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html

Should be something to the effect of:应该是这样的:

import numpy as np

def dot_product(M, N):
    return np.dot(np.asarray(M), np.asarray(N))

In general, a lot of functionality in python has already been implemented in packages like numpy, I try not to reinvent the wheel.一般来说,python 中的很多功能已经在像 numpy 这样的包中实现了,我尽量不重新发明轮子。 Not sure if this is acceptable in your case as this seems to be a homework problem, but this is the easiest way to get the dot product of two matrices.不确定这在您的情况下是否可以接受,因为这似乎是一个家庭作业问题,但这是获得两个矩阵点积的最简单方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM