对于 NumPy 数组,* 运算符执行逐元素乘法:
result[0, 0] = b[0, 0] * b[0, 0]
在你的情况下,你很可能有dtype=np.uint8,这样你就会遇到整数溢出,例如:
result[0, 0] = b[0, 0] * b[0, 0] = 234 * 234 = 54576
由于np.uint8 被限制在[0, ..., 255] 的值范围内,您需要获取54576 % 256 = 228,即您的result[0, 0]。
因此,如果您确实希望在不发生整数溢出的情况下进行逐元素乘法,例如,将b 转换为np.int。
或者,如果您真的想要进行实数矩阵乘法,也可以将b 转换为np.int,但也要使用正确的@ 运算符。
以下是不同用例的一些代码:
import numpy as np
b = np.array([[234, 229], [129, 11]], np.uint8)
print('Matrix b:\n', b, '\n')
# Matrix b:
# [[234 229]
# [129 11]]
print('Element-wise multiplication b * b (np.uint8):\n',
b * b, '\n')
# Element-wise multiplication b * b (np.uint8):
# [[228 217]
# [ 1 121]]
print('Element-wise multiplication b * b (np.int):\n',
np.int_(b) * np.int_(b), '\n')
# Element-wise multiplication b * b (np.int):
# [[54756 52441]
# [16641 121]]
print('Element-wise multiplication b * b (np.int) % 256:\n',
(np.int_(b) * np.int_(b)) % 256, '\n')
# Element-wise multiplication b * b (np.int) % 256:
# [[228 217]
# [ 1 121]]
print('Actual matrix multiplication b @ b (np.int):\n',
(np.int_(b) @ np.int_(b)), '\n')
# Actual matrix multiplication b @ b (np.int):
# [[84297 56105]
# [31605 29662]]
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.9.1
PyCharm: 2021.1.1
NumPy: 1.20.2
----------------------------------------