[英]calculate euclidean distance for PCA in python
我有3D numpy array
作為PCA
pcar =[[xa ya za]
[xb yb zb]
[xc yc zc]
.
.
[xn yn zn]]
其中每一行都是一個點,我從PCA
上方選擇了任意兩個隨機行作為群集
out_list=pcar[numpy.random.randint(0,pcar.shape[0],2)]
這給出了具有2行的numpy數組。
我必須找到距out_list的每一行與pcar中的每一行(點)的歐幾里得距離,並將該pcar點添加到out_list集群中的最近點。
編輯好,我下載,安裝並自學了numpy。 這是一個numpy版本
舊答案
我知道您想要一個麻木的答案。 我的numpy生銹了,但是由於沒有其他答案,我想在Matlab中給你一個答案。 轉換應該很簡單。 我假設問題是概念,而不是代碼。
請注意,有很多方法可以給這只貓蒙皮,我只是舉一種。
工作脾氣暴躁版本
import numpy as np
pcar = np.random.rand(10,3)
out_list=pcar[np.random.randint(0,pcar.shape[0],2)]
ol_1 = out_list[0,:]
ol_2 = out_list[1,:]
## Get the individual distances
## The trick here is to pre-multiply the 1x3 ol vector with a row of
## ones of size 10x1 to get a 10x3 array with ol replicated, so that it
## can simply be subtracted
d1 = pcar - ones( size(pcar,1))*ol_1
d2 = pcar - ones( size(pcar,1))*ol_2
##% Square them using an element-wise square
d1s = np.square(d1)
d2s = np.square(d2)
##% Sum across the rows, not down columns
d1ss = np.sum(d1s, axis=1)
d2ss = np.sum(d2s, axis=1)
##% Square root using an element-wise square-root
e1 = np.sqrt(d1ss)
e2 = np.sqrt(d2ss)
##% Assign to class one or class two
##% Start by assigning one to everything, then select all those where ol_2
##% is closer and assign them the number 2
assign = ones(size(e1,0));
assign[e2<e1] = 2
##% Separate
pcar1 = pcar[ assign==1, :]
pcar2 = pcar[ assign==2, :]
工作Matlab版本
close all
clear all
% Create 10 records each with 3 attributes
pcar = rand(10, 3)
% Pick two (normally at random of course)
out_list = pcar(1:2, :)
% Hard-coding this separately, though this can be done iteratively
ol_1 = out_list(1,:)
ol_2 = out_list(2,:)
% Get the individual distances
% The trick here is to pre-multiply the 1x3 ol vector with a row of
% ones of size 10x1 to get a 10x3 array with ol replicated, so that it
% can simply be subtracted
d1 = pcar - ones( size(pcar,1), 1)*ol_1
d2 = pcar - ones( size(pcar,1), 1)*ol_2
% Square them using an element-wise square
d1s = d1.^2
d2s = d2.^2
% Sum across the rows, not down columns
d1ss = sum(d1s, 2)
d2ss = sum(d2s, 2)
% Square root using an element-wise square-root
e1 = sqrt(d1ss)
e2 = sqrt(d2ss)
% Assign to class one or class two
% Start by assigning one to everything, then select all those where ol_2
% is closer and assign them the number 2
assign = ones(length(e1),1);
assign(e2<e1)=2
% Separate
pcar1 = pcar( assign==1, :)
pcar2 = pcar( assign==2, :)
% Plot
plot3(pcar1(:,1), pcar1(:,2), pcar1(:,3), 'g+')
hold on
plot3(pcar2(:,1), pcar2(:,2), pcar2(:,3), 'r+')
plot3(ol_1(1), ol_1(2), ol_1(3), 'go')
plot3(ol_2(1), ol_2(2), ol_2(3), 'ro')
Scipy有一個非常快速的實現:
from scipy.spatial.distance import cdist, pdist
cdist像pchar一樣采用兩個向量,並計算每個點之間的距離。 pdist將只給您該矩陣的上三角。
由於它們是在后台用C或Fortran實現的,因此它們的性能很高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.