将(500x5000)和(5000x1)矩阵相加,如何得到(500x5000)矩阵?

2024-04-27 04:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在iPython笔记本上学习教程。我的目的是计算(X^2-X\u列)^2,将结果存储在dists中。下面的代码似乎可以工作。我不明白它是怎么工作的。你知道吗

为什么(2*inner\u prod+train\u sum)加上不同大小的矩阵会得到一个500x5000的矩阵?你知道吗

在计算距离时如何处理矩阵?你知道吗

    test_sum = np.sum(np.square(X), axis=1) # summed each example #(500x1)
    train_sum = np.sum(np.square(self.X_train), axis=1) # summed each example #(5000x1)
    inner_prod = np.dot(X, self.X_train.T) #matrix multiplication for 2-D arrays (500x3072)*(3072x5000)=(500x5000)
    print inner_prod.shape
    print X.shape
    print self.X_train.T.shape
    print test_sum.shape
    print test_sum.size
    print train_sum.shape
    print train_sum.size
    print test_sum.reshape(-1,1).shape
    # how... does reshaping work???
    print (2*inner_prod+train_sum).shape
    dists = np.sqrt(np.reshape(test_sum,(-1,1)) - 2 * inner_prod + train_sum) # (500x1) - 2*(500x5000) + (5000x1) = (500x5000)
    print dists.shape

打印报表提供以下内容:

(500L, 5000L)
(500L, 3072L)
(3072L, 5000L)
(500L,)
500
(5000L,)
5000
(500L, 1L)
(500L, 5000L)
(500L, 5000L)

Tags: testselfnptrain矩阵prodinnereach
1条回答
网友
1楼 · 发布于 2024-04-27 04:26:05
print train_sum.shape           # (5000,)
print train_sum.size
print test_sum.reshape(-1,1).shape    # (5000,1)
# how... does reshaping work???
print (2*inner_prod+train_sum).shape

test_sum.reshape(-1,1)以新数组的形式返回新的形状(但共享数据)。它不会重塑test_sum本身。你知道吗

因此,广播的作用是:

(500,5000) + (5000,) => (500,5000)+(1,5000)=>(500,5000)

如果它做了整形,你就会出错。你知道吗

(500,5000) + (5000,1) => error

In [68]: np.ones((500,5000))+np.zeros((5000,1))
ValueError: operands could not be broadcast together with shapes (500,5000) (5000,1) 

实际上只有一种方法可以将(5005000)数组和(5000,)数组相加,这就是没有(有效)重塑的情况下得到的结果。你知道吗

train_sum.shape = (-1,1)起作用,但不像reshape那样经常使用。坚持重塑,但要正确使用。你知道吗

相关问题 更多 >