我有以下代码来帮助理解问题
hypotesisResult = (hypotesis(dataset, theta_init))print(dataset.T.shape)print(hypotesisResult.shape)print(y.shape)print((hypotesisResult - y).shape)print(np.subtract(hypotesisResult, y).shape)
这段代码的输出如下:
(7, 1329)
(1329, 1)
(1329,1)
(1329, 1329)
(1329, 1329)
我的问题是,如果我有一个大小为(1329, 1)的矩阵”hypotesisResult”,当我从中减去大小为(1329,1)的”y”时,为什么结果是一个(1329, 1329)的矩阵?我做错了什么?我想要一个新的(1329, 1)的矩阵,就像标量减法一样
回答:
我不相信你显示的形状。最好重新运行这个脚本,同时检查dtype。
这是我期望的行为,涉及到(n,1)和(n,)或(1,n)数组:
In [605]: x=np.ones((4,1),int); y=np.ones((4,),int)In [606]: x,yOut[606]: (array([[1], [1], [1], [1]]), array([1, 1, 1, 1]))In [607]: x-yOut[607]: array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])In [608]: x-y[None,:]Out[608]: array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])In [609]: x-y[:,None]Out[609]: array([[0], [0], [0], [0]])In [610]: x.T-yOut[610]: array([[0, 0, 0, 0]])
两个基本的广播规则是:
-
如果需要,添加前导大小为1的维度以匹配维度数
-
调整大小为1的维度以匹配其他数组