【发布时间】:2021-12-04 06:20:21
【问题描述】:
我想用 Python 和 Scikit-Learn 库为我的数据集创建聚类模型。数据集包含连续值和分类值。 我已经编码了分类值,但是当我想缩放功能时,我收到了这个错误:
"Cannot center sparse matrices: pass `with_mean=False` "
ValueError: Cannot center sparse matrices: pass `with_mean=False` instead. See docstring for motivation and alternatives.
我在这一行遇到了这个错误:
features = scaler.fit_transform(features)
我做错了什么?
这是我的代码:
features = df[['InvoiceNo', 'StockCode', 'Description', 'Quantity',
'UnitPrice', 'CustomerID', 'Country', 'Total Price']]
columns_for_scaling = ['InvoiceNo', 'StockCode', 'Description', 'Quantity', 'UnitPrice', 'CustomerID', 'Country', 'Total Price']
transformerVectoriser = ColumnTransformer(transformers=[('Encoding Invoice number', OneHotEncoder(handle_unknown = "ignore"), ['InvoiceNo']),
('Encoding StockCode', OneHotEncoder(handle_unknown = "ignore"), ['StockCode']),
('Encoding Description', OneHotEncoder(handle_unknown = "ignore"), ['Description']),
('Encoding Country', OneHotEncoder(handle_unknown = "ignore"), ['Country'])],
remainder='passthrough') # Default is to drop untransformed columns
features = transformerVectoriser.fit_transform(features)
print(features.shape)
scaler = StandardScaler()
features = scaler.fit_transform(features)
sum_of_squared_distances = []
for k in range(1,16):
kmeans = KMeans(n_clusters=k)
kmeans = kmeans.fit(features)
sum_of_squared_distances.append(features.inertia_)
预处理前我的数据形状:(401604, 8)
预处理后我的数据形状:(401604, 29800)
【问题讨论】:
-
错误信息给出了一个简单的解决方案:在缩放器中设置
with_mean=False。
标签: python machine-learning scikit-learn k-means