python-3.x - 二维数据的 numpy 条件函数
问题描述
我有一个由特征 (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 (最近一次调用最后一次) 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 结果 = 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 # 使用旧迭代器,因为 np.nditer 不处理大小为 0 的数组 188 # 一致 -- > 189 b = np.broadcast(*args[:32]) 190 # 不幸的是,它不能直接处理 32 个或更多参数 191 for pos in range(32, len(args), 31):
ValueError:形状不匹配:无法将对象广播到单个形状
建议?
谢谢!
解决方案
以下是更清洁的方式(但与您的方式非常相似)。这是一个简单的例子:
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
函数完成任务的方法,我猜你这样做的方式是最好的方式,基于这个答案。
干杯。
推荐阅读
- google-chrome - TypeError:无法读取未定义的属性“同步”。我该如何解决这个问题?
- python - Django 编辑表单安全方式
- bash - 将txt转换为分栏文件
- reactjs - 类型“{}”不可分配给类型“ComponentProps”
- wordpress - 在 WordPress 中的特定帖子标题上添加当前时间
- html - 我如何正确对齐图像?
- laravel - laravel-5.7:SQLSTATE[HY000]:一般错误:1364 字段 'category_id' 没有默认值
- android - 通过 Glide 从 URL 加载图像的问题(“无法找到模型的任何 ModelLoaders”)
- php - CakePHP 2.0 可包含返回意外结果
- node.js - 如何标记 HTML 以在 Mongoose 中保存嵌套对象?