【问题标题】:float() argument must be a string or a number, not 'csr_matrix'float() 参数必须是字符串或数字,而不是 'csr_matrix'
【发布时间】:2020-10-04 01:23:07
【问题描述】:

我在尝试在 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.

【问题讨论】:

  • 您可以包含您的导入语句吗?

标签: python matplotlib machine-learning data-science k-means


【解决方案1】:

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

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

此挑战使用年龄、性别而不是国籍……但数据分析和方法与您的目标完全一致。

现在,他们正在使用 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()

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2023-02-18
    • 2019-05-22
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多