簡體   English   中英

目標變量的字符串和數字的混合

[英]Mixture of strings and numerics for a target variable

我正在測試下面的代碼,但在最后一行出現錯誤。

dataset = df[['Rate', 'Weights', 'Change', 'Price', 'CategoryOne']].copy() # 
dataset.shape


X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values


from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)



from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)

X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)


#Import knearest neighbors Classifier model
from sklearn.neighbors import KNeighborsClassifier

#Create KNN Classifier
knn = KNeighborsClassifier(n_neighbors=5)

#Train the model using the training sets
knn.fit(X_train, y_train)

#Predict the response for test dataset
y_pred = knn.predict(X_test)


#Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics
# Model Accuracy, how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))



#Import knearest neighbors Classifier model
from sklearn.neighbors import KNeighborsClassifier

#Create KNN Classifier
knn = KNeighborsClassifier(n_neighbors=7)

#Train the model using the training sets
knn.fit(X_train, y_train)

在最后一行,當我嘗試擬合 X_train 和 y_train 時,出現此錯誤:

TypeError: '<' not supported between instances of 'int' and 'str'

CategoryOne 字段中的數據如下所示: '2a', '1', '2a' 這可能是問題嗎? 我知道目標變量不必是數字。 我只想看看自變量和因變量(CategoryOne)之間的關系。

這是堆棧跟蹤:

Traceback (most recent call last):

  File "<ipython-input-108-36266936f0ca>", line 29, in <module>
    knn.fit(X_train, y_train)

  File "C:\Users\rs\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\neighbors\base.py", line 906, in fit
    check_classification_targets(y)

  File "C:\Users\rs\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\multiclass.py", line 166, in check_classification_targets
    y_type = type_of_target(y)

  File "C:\Users\rs\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\multiclass.py", line 287, in type_of_target
    if (len(np.unique(y)) > 2) or (y.ndim >= 2 and len(y[0]) > 1):

  File "C:\Users\rs\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\arraysetops.py", line 264, in unique
    ret = _unique1d(ar, return_index, return_inverse, return_counts)

  File "C:\Users\rs\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\lib\arraysetops.py", line 312, in _unique1d
    ar.sort()

TypeError: '<' not supported between instances of 'int' and 'str'

您可以嘗試將CategoryOne列作為字符串數據顯式附加,方法是修改dataset的構造,如下所示:

dataset = df[['Rate', 'Weights', 'Change', 'Price', 'CategoryOne']].copy()
dataset['CategoryOne'] = dataset['CategoryOne'].map(lambda x : str(x))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM