我正在尝试创建散点图,但是,我得到了不同类别的重复颜色(我有10个类别)。
from sklearn.decomposition import PCA
from sklearn.cluster import MiniBatchKMeans
pca = PCA(n_components=2, random_state=7)
reduced_features = pca.fit_transform(X_idf.toarray())
cls = MiniBatchKMeans(n_clusters=10, random_state=7)
cls.fit(X_idf)
pred = cls.predict(X_idf)
plt.scatter(reduced_features[:,0], reduced_features[:,1], c=pred, )
plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=200,
c='b')
plt.title('K-means data distribution')
我尝试在第一个pl.scatter()调用中添加一些颜色映射(例如:cmap ='bwr'),但这不能解决我的问题。
我的Y数据(c = pred)是从0到10的列表。用于以下绘图的值[... 0 9 5 1 1 1 1 8 1 4 6 4 7 2 0 4 9 9 9 9 4 4 5 5 5 4 4 4 4 3 4 7 1 1 1 1 1 7 4 2 2 2 2 2 4 4 8 8 8 0 8 4 4 4 4 4 4 4 3 3 3 3 4 4 4 4 2 5 4 2 7 .. 。]
这是我当前的情节:
有人知道如何将c参数保留为预测类,但是有不同的颜色可以使我更好地将其可视化吗?
答案 0 :(得分:0)
对于正在寻找具有超过20个选项(也称为“ tab20”)的颜色图的任何人,此方法都可以正常工作:
def generate_colormap(number_of_distinct_colors=100):
number_of_shades = 7
number_of_distinct_colors_with_multiply_of_shades = int(math.ceil(number_of_distinct_colors / number_of_shades) * number_of_shades)
linearly_distributed_nums = np.arange(number_of_distinct_colors_with_multiply_of_shades) / number_of_distinct_colors_with_multiply_of_shades
arr_by_shade_rows = linearly_distributed_nums.reshape(number_of_shades, number_of_distinct_colors_with_multiply_of_shades // number_of_shades)
# Transpose the above matrix (columns become rows) - as a result each row contains saw tooth with values slightly higher than row above
arr_by_shade_columns = arr_by_shade_rows.T
# Keep number of saw teeth for later
number_of_partitions = arr_by_shade_columns.shape[0]
nums_distributed_like_rising_saw = arr_by_shade_columns.reshape(-1)
initial_cm = hsv(nums_distributed_like_rising_saw)
lower_partitions_half = number_of_partitions // 2
upper_partitions_half = number_of_partitions - lower_partitions_half
lower_half = lower_partitions_half * number_of_shades
for i in range(3):
initial_cm[0:lower_half, i] *= np.arange(0.2, 1, 0.8/lower_half)
# Modify second half in such way that colours towards end of partition are less intense and brighter
# Colours closer to the middle are affected less, colours closer to the end are affected more
for i in range(3):
for j in range(upper_partitions_half):
modifier = np.ones(number_of_shades) - initial_cm[lower_half + j * number_of_shades: lower_half + (j + 1) * number_of_shades, i]
modifier = j * modifier / upper_partitions_half
initial_cm[lower_half + j * number_of_shades: lower_half + (j + 1) * number_of_shades, i] += modifier
return ListedColormap(initial_cm)
代码不是我写的,但是我做了一些调整以改进它。抱歉,我找不到原始参考链接。