ValueError:未知标签类型:一起使用聚类+分类模型时为'连续'

问题描述 投票:0回答:1

我创建了一个聚类模型,以使用Scikit-Learn的KMeans算法根据年收入和支出得分来尝试寻找不同的客户群。使用它为每个客户返回的集群值,我尝试使用来自sklearn.svm的支持向量分类创建分类模型。但是,当我尝试将新模型拟合到数据集时,出现错误消息:

File "/Users/user/Documents/Machine Learning A-Z Template Folder/Part 4 - Clustering/Section 24 - K-Means Clustering/cluster_and_prediction.py", line 28, in <module>
    classifier.fit(x_train, y_train)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/sklearn/svm/_base.py", line 149, in fit
    y = self._validate_targets(y)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/sklearn/svm/_base.py", line 525, in _validate_targets
    check_classification_targets(y)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/sklearn/utils/multiclass.py", line 169, in check_classification_targets
    raise ValueError("Unknown label type: %r" % y_type)
ValueError: Unknown label type: 'continuous'

我的代码如下

import pandas as pd 
import numpy as np 

# Using relevant columns from dataset
dataset = pd.read_csv('Mall_Customers.csv')
x = dataset.iloc[:, 3:5].values

# Creating model with ideal amount of clusters
kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10, random_state=0)
kmeans.fit(x)

predictions = kmeans.predict(x)

# Creating numpy array for feature scaling
predictions = np.array(predictions, dtype=int)
predictions = predictions[:, None]

from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
sc_y = StandardScaler()
x = sc_x.fit_transform(x)
predictions = sc_y.fit_transform(predictions)

# Splitting dataset into training and test sets
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, predictions, test_size=.25)

# Creating Support Vector Classification model
from sklearn.svm import SVC
classifier = SVC(kernel='rbf')
classifier.fit(x_train, y_train)

Elbow Model Used for Clustering

Clustering Visualization

.zip file with the dataset(the dataset is called 'Mall_Customers.csv'

我该如何解决?

python machine-learning scikit-learn svm k-means
1个回答
0
投票

由于您要解决5类分类问题,因此您应该not使用缩放器作为标签;这会将它们转换为分类模型中输入的连续变量,因此会产生错误。

此外,与该问题无关,但正确的方法是仅使您的缩放器适合您的训练数据,然后使用该适合的缩放器来转换您的测试数据。

所以,这是必要的更改(在完成设置predictions变量后:

# initial (unscaled) x used here:
x_train, x_test, y_train, y_test = train_test_split(x, predictions, test_size=.25)
sc = StandardScaler()
x_train_scaled = sc.fit_transform(x_train)
x_test_scaled = sc.transform(x_test)

classifier = SVC(kernel='rbf')
classifier.fit(x_train_scaled, y_train) # no scaling for predictions or y_train
© www.soinside.com 2019 - 2024. All rights reserved.