我的数据对象是一个实例:
class data_instance:
def __init__(self, data, tlabel):
self.data = data # 1xd numpy array
self.true_label = tlabel # integer {1,-1}
到目前为止,在代码中,我有一个名为 data_history 的列表充满 data_istance和一组 centers (形状为 (k,d) 的 numpy 数组)。
对于给定的数据实例 new_data , 我想要:
1/获取离
new_data最近的中心来自centers(按欧几里得距离)让它被称为Nearest_center.2/遍历
data_history和:- 2.1/选择最近中心为
Nearest_center的元素(1/的结果)进入名为neighbors的列表. - 2.2/获取
neighbors中对象的标签.
- 2.1/选择最近中心为
下面是我的代码,它可以工作,但速度很慢,我正在寻找更高效的代码。
我的代码
对于 1/
def getNearestCenter(data,centers):
if centers.shape != (1,2):
dist_ = np.sqrt(np.sum(np.power(data-centers,2),axis=1)) # This compute distance between data and all centers
center = centers[np.argmin(dist_)] # this return center which have the minimum distance from data
else:
center=centers[0]
return center
For 2/(优化)
def getLabel(dataPoint, C, history):
labels = []
cluster = getNearestCenter(dataPoint.data,C)
for x in history:
if np.all(getNearestCenter(x.data,C) == cluster):
labels.append(x.true_label)
return labels
请您参考如下方法:
您应该使用 scipy.spatial 中优化的 cdist,这比用 numpy 计算它更有效,
from scipy.spatial.distance import cdist
dist = cdist(data, C, metric='euclidean')
dist_idx = np.argmin(dist, axis=1)
一个更优雅的解决方案是使用 scipy.spatial.cKDTree(正如@Saullo Castro 在评论中指出的那样),这对于大型数据集来说可能更快,
from scipy.spatial import cKDTree
tr = cKDTree(C)
dist, dist_idx = tr.query(data, k=1)
