python-3.x - 二维数据的 numpy 条件函数

标签 python-3.x numpy k-means

我有一个由特征 (X) 和标签 (y) 组成的合成数据集,用于使用 Python 3.8、sklearn 0.22.2 和 numpy 1.19 进行 KMeans 聚类。

X.shape, y.shape
# ((100, 2), (100,))

kmeans = KMeans(n_clusters = 3, init = 'random', n_init = 10, max_iter = 300)

# Train model on scaled features-
kmeans.fit(X)

在“X”上训练 KMeans 后,我想用使用 KMeans 获得的聚类中心(离散)替换“X”的唯一(连续)值。

for i in range(3):
    print("cluster number {0} has center = {1}".format(i + 1, kmeans.cluster_centers_[i, :]))
'''
cluster number 1 has center = [-0.7869159   1.14173859]
cluster number 2 has center = [ 1.28010442 -1.04663318]
cluster number 3 has center = [-0.54654735  0.0054752 ]
'''


set(kmeans.labels_)
# {0, 1, 2}

我这样做的一种方法是:

X[np.where(clustered_labels == 0)] = val[0,:]
X[np.where(clustered_labels == 1)] = val[1,:]
X[np.where(clustered_labels == 2)] = val[2,:]

我可以使用 np.select() 来做到这一点吗?

cond = [clustered_labels == i for i in range(3)]
val = kmeans.cluster_centers_[:,:]

但是在执行代码时:

np.select(cond, val)  

             

我收到以下错误:

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in ----> 1 np.select(cond, val)

<array_function internals> in select(*args, **kwargs)

~/.local/lib/python3.8/site-packages/numpy/lib/function_base.py in select(condlist, choicelist, default) 693 result_shape = condlist[0].shape 694 else: --> 695 result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape 696 697 result = np.full(result_shape, choicelist[-1], dtype)

<array_function internals> in broadcast_arrays(*args, **kwargs)

~/.local/lib/python3.8/site-packages/numpy/lib/stride_tricks.py in broadcast_arrays(subok, *args) 256 args = [np.array(_m, copy=False, subok=subok) for _m in args] 257 --> 258 shape = _broadcast_shape(*args) 259 260 if all(array.shape == shape for array in args):

~/.local/lib/python3.8/site-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args) 187 # use the old-iterator because np.nditer does not handle size 0 arrays 188 # consistently --> 189 b = np.broadcast(*args[:32]) 190 # unfortunately, it cannot handle 32 or more arguments directly 191 for pos in range(32, len(args), 31):

ValueError: shape mismatch: objects cannot be broadcast to a single shape

建议?

谢谢!

最佳答案

更干净的方法(但与您的方法非常相似)如下。这是一个简单的例子:

from sklearn.cluster import KMeans
import numpy as np

x1 = np.random.normal(0, 2, 100)
y1 = np.random.normal(0, 1, 100)
label1 = np.ones(100)
d1 = np.column_stack([x1, y1, label1])

x2 = np.random.normal(3, 1, 100)
y2 = np.random.normal(1, 2, 100)
label2 = np.ones(100) * 2
d2 = np.column_stack([x2, y2, label2])

x3 = np.random.normal(-3, 0.5, 100)
y3 = np.random.normal(0.5, 0.25, 100)
label3 = np.ones(100) * 3
d3 = np.column_stack([x3, y3, label3])

D = np.row_stack([d1, d2, d3])
np.random.shuffle(D)
X = D[:, :2]
y = D[:, 2]

print(f'X.shape = {X.shape}, y.shape = {y.shape}')
# X.shape = (300, 2), y.shape = (300,)

kmeans = KMeans(n_clusters = 3, init = 'random', n_init = 10, max_iter = 300)

# Train model on scaled features-
kmeans.fit(X)

preds = kmeans.predict(X)
X[preds==0] = kmeans.cluster_centers_[0]
X[preds==1] = kmeans.cluster_centers_[1]
X[preds==2] = kmeans.cluster_centers_[2]

完成该任务的另一种方法是使用 np.put 方法而不是如下所示的赋值:

np.put(X, preds==0, kmeans.cluster_centers_[0])
np.put(X, preds==1, kmeans.cluster_centers_[1])
np.put(X, preds==2, kmeans.cluster_centers_[2])

坦率地说,我没有看到通过 np.select 函数来完成任务的方法,我猜你的做法是最好的方法,基于 this answer

干杯。

关于python-3.x - 二维数据的 numpy 条件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63041722/

相关文章:

python - Seaborn 中的自定义调色板

python - 四舍五入到最接近的百位时,如何包含 0

python - 2D 可变迭代器/生成器

c++ - OpenCV 聚类函数 cv KMeans2() - 数组中的聚类中心类型是什么?

python - 如何使用原始数据中的id导出k-means算法的输出(簇标签)

python-3.x - Jupyter Notebook 无法在 Windows 10 中使用 python 3.8 启动

python - 可疑行为 - 在 Python 3.4.1 中 str 不可调用返回 "".join(list(map(str,reversed(result))))

python - 如何屏蔽张量中每一行的特定切片

python - pylab 导入状态?

python - 绘制一维数据的 KMeans 聚类和分类