# 矩阵乘法
import numpy as np
# x,y是向量
def naive_vector_dot(x, y):
sum = 0
for i in range(x.shape[0]):
sum += x[i] * y[i]
return sum
# a,b是矩阵
def vector_dot(a, b):
z = np.zeros((a.shape[0], b.shape[1]))
for i in range(a.shape[0]):
for j in range(b.shape[1]):
z[i, j] = naive_vector_dot(a[i, :], b[:, j])
return z
#a : <class 'numpy.ndarray'>
a = np.arange(1, 5).reshape(2, 2)
b = np.arange(6, 10).reshape(2, 2)
c = np.dot(a, b)
c_ = vector_dot(a, b)
print(c)
print(c_)
print(c == c_)
python矩阵乘法
最新推荐文章于 2024-10-10 19:43:55 发布
该博客展示了如何使用Python的NumPy库进行矩阵乘法。通过定义`naive_vector_dot`函数计算两个向量的点积,然后利用这个函数在`vector_dot`中实现两个矩阵的乘法。博客通过实例展示了如何应用这些函数,并验证了自定义函数与NumPy内置的`dot`函数结果的一致性。
1873

被折叠的 条评论
为什么被折叠?



