- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个二维点数据集,我想使用 K 均值技术对其进行分类。
数据:
import numpy as np
x1 = np.array([3,1,1,2,1,6,6,6,5,6,7,8,9,8,9,9,8])
x2 = np.array([5,4,5,6,5,8,6,7,6,7,1,2,1,2,3,2,3])
X = np.array(list(zip(x1,x2))).reshape(len(x1), 2)
我想对从 1 到 9 的簇数量进行迭代,以测试散点图上的最终分布。所以我计算了数据集的质心。
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
max_k = 10
K = range(1,max_k)
centroid = [sum(X)/len(X) for k in K]
sst = sum(np.min(cdist(X, centroid, "euclidean"), axis = 1))
然后使用 cm.Spectral
为每次迭代创建一个包含一种 rgb
颜色的调色板。
color_palette = [plt.cm.Spectral(float(k)/max_k) for k in K]
并在迭代 k
的循环中使用它:
from sklearn.cluster import KMeans
import pandas as pd
ssw = []
for k in K:
kmeanModel = KMeans(n_clusters=k).fit(X)
centers = pd.DataFrame(kmeanModel.cluster_centers_)
labels = kmeanModel.labels_
ssw_k = sum(np.min(cdist(X, kmeanModel.cluster_centers_), axis = 1))
ssw.append(ssw_k)
label_color = [color_palette[i] for i in labels]
plt.plot()
plt.xlim([0,10])
plt.ylim([0,10])
plt.title("Clustering for k = %s"%str(k))
plt.scatter(x1,x2, c=label_color)
plt.scatter(centers[0], centers[1], c=color_palette, marker = "x")
plt.show()
我正在我的 Python 3.7.3 版本中复制这段代码,并且从这段代码的源代码中我知道它在旧版本中运行良好。当 matplotlib.pyplot.cm
中的函数 Spectral
以小写形式编写时 (spectral
)。
结果是下一个。
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
4237 valid_shape = False
-> 4238 raise ValueError
4239 except ValueError:
ValueError:
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-26-2f513f9c616c> in <module>
24 plt.title("Clustering for k = %s"%str(k))
25 plt.scatter(x1,x2, c=label_color)
---> 26 plt.scatter(centers[0], centers[1], c=[i for i in color_palette], marker = "x")
27 plt.show()
~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, data, **kwargs)
2860 vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
2861 verts=verts, edgecolors=edgecolors, **({"data": data} if data
-> 2862 is not None else {}), **kwargs)
2863 sci(__ret)
2864 return __ret
~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
4243 "acceptable for use with 'x' with size {xs}, "
4244 "'y' with size {ys}."
-> 4245 .format(nc=n_elem, xs=x.size, ys=y.size)
4246 )
4247 # Both the mapping *and* the RGBA conversion failed: pretty
ValueError: 'c' argument has 9 elements, which is not acceptable for use with 'x' with size 1, 'y' with size 1.
我希望每个组的中心颜色与组本身一样。
提前致谢。
最佳答案
尝试通过与 x 和 y 值的长度相对应的索引来使用相应大小的调色板,如下所示。
P.S:您的代码在 matplotlib 2.2.2
中运行良好
for i, k in enumerate(K):
# rest of your code
plt.scatter(centers[0], centers[1], c=color_palette[0:i+1], marker = "x")
print (centers[0].values)
plt.show()
关于python - 如何在循环中使用使用 pyplot.Spectral 创建的调色板来绘制散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56936255/
我尝试从网站 https://plot.ly/scikit-learn/plot-kmeans-silhouette-analysis/ 运行代码.当我运行时发现 matplotlib 模块已经没有光
关于 http://en.cppreference.com/w/cpp/numeric/random : The Mersenne twister is slower and has greater
我有一个二维点数据集,我想使用 K 均值技术对其进行分类。 数据: import numpy as np x1 = np.array([3,1,1,2,1,6,6,6,5,6,7,8,9,8,9,9,
我正在尝试列出我的 .hdr 文件中存在的所有波段。我有超过 100 个波段,这是一个高光谱数据。 img = envi.open('Dun_Hyperion_Atm_Corr.hdr','Dun_H
我正在尝试打开一个 envi .img 文件,但有一个同名的 .hdr 文件。在 .img 文件中有两个图像,我可以使用以下代码读取它们。 from spectral import * img = o
让我们从一个简单的时间序列输入开始,并尝试构建一个自动编码器,该自动编码器简单地进行傅立叶变换,然后在 keras 中对我们的数据进行反变换。 如果我们尝试这样做: inputs = Input(sh
新的 Scipy v0.11 提供了一个用于光谱分析的包。不幸的是,文档很少,而且没有很多可用的示例。 作为一个小例子,我正在尝试发现正弦波的周期。不幸的是,它预测的周期为 1 而不是预期的 2pi。
我指的是以下帖子:Using scipy.signal.spectral.lombscargle for period discovery 我意识到在某些情况下给出的答案是正确的。 sin(x) 的频
我正在使用 scikit learn 的“谱聚类”功能。我能够对 8100 x 8100 矩阵执行聚类,但此函数会对 10000 x 10000 矩阵抛出错误。 有人用过这个函数来处理大矩阵吗? 编辑
我一直在使用 pylab 的代码,它运行良好: import pylab as pl colors = pl.cm.Spectral(np.linspace(0, 1, 10)) 但是,我想摆脱 py
我正在尝试查找在不均匀时间测量的信号的功率谱密度。数据看起来像这样: 0 1.55 755 1.58 2412256 2.42 2413137 0.32 2497761 1.19 ... 其中第一列是
我有两个长度相等的时间序列(地震道的不同分量),我计算了它们的单独频谱图 PxV 和 PxH,它们对应于地震信号的垂直和水平分量。然后,我提取了每个频谱图的数据数组(对应于时间 - 频率空间中的点的幅
我将我的 MacBook 更新为 Mavericks,重新安装了 Macports 和我常用的所有 Python 2.7 模块。在运行 Python 时,我收到以下消息: 导入 mlab 时: 来自
我是一名优秀的程序员,十分优秀!