python - 实现 dotProduct 的最 Pythonic 方式是什么?
问题描述
我正在尝试使用 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
但是,我想知道是否有更 Pythonic 的方式来做到这一点。
当然,我知道 的存在numpy.dot
,它会计算点积,但我想自己实现它,这是因为我正在处理加密数据,所以我不能使用常见的乘法和加法。
该问题的目标是了解如何优化代码,而不是使用现有功能。
解决方案
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
输出:
>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
推荐阅读
- php - 不同页面的WordPress自定义类
- json - 如果 json 数据为空或 json 链接已失效,是否可以显示 Flutter 应用程序
- javascript - 单元测试检查 React 组件的顺序
- javascript - 如何从一个页面保存多个画布
- wordpress - Woocommerce 产品图片链接到外部会员链接
- java - 如果 TextView 显示特定文本,则将可见性设置为 GONE
- css - 如何在一行中居中 3 列?
- dojo - Dojo gridx 偶尔会以错误的顺序显示行
- html - 具有类内部标题的 div 将包含三个 div 元素
- r - 如何根据以下格式制作索引和拆分列