<p>我以前没有使用过Theano,但是这里有一个基于纯Numpy函数的解决方案(也许您可以将它转换为等效的Theano函数)。请注意,我在下面的表达式中使用了automatic<em>broadcasting</em>,因此如果Theano不支持它,您可能需要显式重写它):</p>
<pre class="lang-py prettyprint-override"><code># X is an m-by-n matrix (rows are examples, columns are dimensions)
# D is an m-by-m symmetric matrix of pairwise Euclidean distances
a = np.sum(X**2, axis=1)
D = np.sqrt((a + a[np.newaxis].T) - 2*np.dot(X, X.T))
</code></pre>
<p>它基于这样一个事实:<code>||u-v||^2 = ||u||^2 + ||v||^2 - 2*u.v</code>。(我用MATLAB在我的<a href="https://stackoverflow.com/a/4171845/97160">previous</a><a href="https://stackoverflow.com/a/7774323/97160">answers</a>中展示了这一点)</p>
<p>以下是与Scipy现有函数的比较:</p>
^{pr2}$
<p>差异应该可以忽略不计,接近机器epsilon(<code>np.spacing(1)</code>):</p>
<pre><code>>>> np.linalg.norm(D1-D2)
8.5368137554718277e-16
</code></pre>
<p>高温</p>
<hr/>
<h2>编辑:</h2>
<p>下面是另一个单循环实现:</p>
<pre class="lang-py prettyprint-override"><code>def my_pdist_compact(X):
D = np.empty(shape=[0,0], dtype=X.dtype)
for i in range(X.shape[0]-1):
D = np.append(D, np.sqrt(np.sum((X[i,] - X[i+1:,])**2, axis=1)))
return D
</code></pre>
<p>相当于MATLAB代码:</p>
<pre class="lang-matlab prettyprint-override"><code>function D = my_pdist_compact(X)
n = size(X,1);
D = cell(n-1,1);
for i=1:n-1
D{i} = sqrt(sum(bsxfun(@minus, X(i,:), X(i+1:end,:)).^2, 2));
end
D = vertcat(D{:});
end
</code></pre>
<p>这将返回紧凑形式的成对距离(对称矩阵的上三角部分)。这与<code>pdist</code>的输出相同。使用<code>squareform</code>将其转换为完整矩阵。在</p>
<pre class="lang-py prettyprint-override"><code>>>> d1 = my_pdist_compact(X)
>>> d2 = pdist(X) # from scipy.spatial.distance
>>> (d1 == d2).all()
True
</code></pre>
<p>我将把它留给您看看是否可以使用ano编写等价的<a href="http://deeplearning.net/software/theano/tutorial/loop.html" rel="nofollow noreferrer">loop</a>(参见<a href="http://deeplearning.net/software/theano/library/scan.html" rel="nofollow noreferrer">^{<cd5>}</a>)!在</p>