我想使用KNN算法对文本进行分类。而且我有.csv扩展名的数据。
如果我使用此代码打印,数据将如下所示:
# Preprocessing
X = np.array(dataset.iloc[:, :1])
y = np.array(dataset['Class'])
print("Data variabel X : ", X)
print("Data variabel y : ", y)
输出:
[['pada awalnya aku memandang gadis itu nani namanya']['dua buah melon yang subur segar']]['Pornografi''Non-Pornografi']
我分开参加培训和考试:
# Train Test Split
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)
# loading library
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import LabelEncoder
# Feature Scaling
lb = LabelEncoder()
lb.fit(X_train)
X_train = lb.transform(X_train)
X_test = lb.transform(X_test)
print("X_train : ", X_train)
print("X_test : ", X_test)
# instantiate learning model (k = 3)
knn = KNeighborsClassifier(n_neighbors=3)
# fitting the model
knn.fit([[X_train, y_train]], [y])
# predict the response
pred = knn.predict(X_test)
# evaluate accuracy
print (accuracy_score(y_test, pred))
我收到错误消息:
<ipython-input-223-7d80eb4ea7d1> in <module>()
8
9 X_train = lb.transform(X_train)
---> 10 X_test = lb.transform(X_test)
11
12 print("X_train : ", X_train)
TypeError: '<' not supported between instances of 'int' and 'str'
我的代码有什么问题?
答案 0 :(得分:0)
尝试一下:
lb.transform(X_test.astype(str))
基本上,您需要将数据转换为一种格式。