float()参数必须是字符串或数字,而不是“csr\u矩阵”

2024-04-18 17:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在matplotlib上绘制集群时遇到了这个问题

# Training the K-Means model on the dataset
kmeans = KMeans(n_clusters = 4, init = 'k-means++', random_state = 42)

y_kmeans = kmeans.fit_predict(X)


#X.shape is (767135, 37)   (It has undergone One Hot Encoding)

# Visualising the clusters
plt.scatter(X[y_kmeans == 0, 0], X[y_kmeans == 0, 1], s = 50, c = 'red',alpha = 0.3,  label = 'Cluster 1')
plt.scatter(X[y_kmeans == 1, 0], X[y_kmeans == 1, 1], s = 50, c = 'blue',alpha = 0.3, label = 'Cluster 2')
plt.scatter(X[y_kmeans == 2, 0], X[y_kmeans == 2, 1], s = 50, c = 'green',alpha = 0.3, label = 'Cluster 3')
plt.scatter(X[y_kmeans == 3, 0], X[y_kmeans == 3, 1], s = 50, c = 'cyan',alpha = 0.3, label = 'Cluster 4')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 300, c = 'yellow', label = 'Centroids')
plt.title('Clusters of customers')
plt.xlabel('Nationality')
plt.ylabel('Total Spending')
plt.legend()
plt.show()

运行代码时,我遇到以下错误:

TypeError: float() argument must be a string or a number, not 'csr_matrix'

ValueError: setting an array element with a sequence.

Tags: thealphamatplotlibtraining绘制集群pltlabel
1条回答
网友
1楼 · 发布于 2024-04-18 17:18:18

这篇关于KD Nuggets的文章将向您展示如何做到这一点,因为它是一个非常相似的数据集。它甚至还向您展示了如何进行三维可视化

https://www.kdnuggets.com/2019/11/customer-segmentation-using-k-means-clustering.html

这个挑战使用年龄、性别而不是国籍。。。但是数据分析和方法与你的目标是一致的

enter image description hereenter image description hereenter image description here

现在,他们正在使用3d绘图,但我认为这仍然适用,并将修复矩阵问题。尝试使用以下参数类型而不是矩阵调用散点图:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(df.Age[df.label == 0], df["Annual Income (k$)"][df.label == 0], df["Spending Score (1-100)"][df.label == 0], c='blue', s=60)
ax.scatter(df.Age[df.label == 1], df["Annual Income (k$)"][df.label == 1], df["Spending Score (1-100)"][df.label == 1], c='red', s=60)
ax.scatter(df.Age[df.label == 2], df["Annual Income (k$)"][df.label == 2], df["Spending Score (1-100)"][df.label == 2], c='green', s=60)
ax.scatter(df.Age[df.label == 3], df["Annual Income (k$)"][df.label == 3], df["Spending Score (1-100)"][df.label == 3], c='orange', s=60)
ax.scatter(df.Age[df.label == 4], df["Annual Income (k$)"][df.label == 4], df["Spending Score (1-100)"][df.label == 4], c='purple', s=60)
ax.view_init(30, 185)
plt.xlabel("Age")
plt.ylabel("Annual Income (k$)")
ax.set_zlabel('Spending Score (1-100)')
plt.show()

相关问题 更多 >