实现dotProduct的最pythonic方法是什么?

时间:2019-05-28 07:46:20

标签: python loops numpy

我正在尝试使用numpy数组在Python中实现点积。到目前为止,我正在使用的代码有效:

x = np.random.rand(5,5)
w = np.random.rand(5,1)
dot_product = np.zeros((5,1), dtype = np.dtype('O'))

for j in range(len(dot_product[:,0])):
     for i in range(len(dot_product[0,:])):
         sumt = 0
         for column in range(len(x[0,:])):
             temp_x = x[j,column]
             temp_plain = w[column,i]
             sumt += temp_x * temp_plain
         dot_product[j,i] = sumt

但是,我想知道是否还有更Python化的方式来做到这一点。

当然,我知道numpy.dot的存在,它将计算点积,但是我想自己实现,这是因为我正在处理加密数据,所以不能使用公共乘法和加法。

这个问题的目的是要知道如何优化代码,而不是使用现有功能。

2 个答案:

答案 0 :(得分:1)

baseURL: "${properties.myappendpoint @ context='uri'}"

输出:

def dot_prod(x,w):
   if not ( x.shape[1]==w.shape[0]):
       raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')

   dot_product = np.zeros((x.shape[0], w.shape[1]), dtype=np.dtype('O'))
   for i1,a in enumerate(x):
      for i2,y in enumerate(w.T):
         dot_product[i1,i2]= np.sum(a*y)
   return dot_product

答案 1 :(得分:0)

使用嵌套列表组合。

>x = np.random.rand(5,3)
>w = np.random.rand(3,2)
>dot_prod(x,w)
array([[1.0216453677132162, 1.0520242959212602],
       [0.7139675035454871, 0.7616075739263084],
       [0.9126062852861008, 0.9864445729083398],
       [0.42673040494581216, 0.4203998986679549],
       [0.9638211885773351, 1.0142282080627387]], dtype=object)

>x.dot(w)
array([[1.02164537, 1.0520243 ],
       [0.7139675 , 0.76160757],
       [0.91260629, 0.98644457],
       [0.4267304 , 0.4203999 ],
       [0.96382119, 1.01422821]])


>x = np.random.rand(5,3)
>w = np.random.rand(2,2)
>dot_prod(x,w)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/alperen/Projects/tmp.py", line 8, in dot_prod
    raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')
Exception: The number of columns of the first matrix  does not match the number of rows of the second matrix