是否需要在scikitlearn中对输入进行编码,以了解训练数据的编码位置?

2024-06-01 23:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手。 我已经对算法强文本进行了分类数据的训练,在训练过程中,我遇到了一些解决方案的错误。我看到它需要使用LabelEncoder并且我使用了它。解决了问题,完成了算法训练

我想知道为什么它不接受原始数据的字符串(编码前)。 有没有办法给预测算法指定字符串 这是我的密码:


import pandas as pd
import sklearn
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import NearestNeighbors

df=pd.read_csv(r'E:\Study\FYP Data\FYP\datasets\alluni.csv', encoding= 'unicode_escape')
df.head()


Obtained Marks   Intermediate   Bachelor    Institute   %age
0   1001.0  FSc. Pre Medical    DPT          UOS      91.000000
1   1001.0  FSc. Pre Medical    DPT          UOS      91.000000
2   1010.0  FSc. Pre Medical    DPT          UOS      91.818182
3   1000.0  FSc. Pre Medical    DPT          UOS      90.909091
4   1000.0  FSc. Pre Medical    DPT          UOS      90.909091

le = LabelEncoder()
df['Intermediate'] = le.fit_transform(df.Intermediate.values)
df['Intermediate'] = le.fit_transform(df['Intermediate'])

le = LabelEncoder()
df['Institute'] = le.fit_transform(df.Institute.values)
df['Institute'] = le.fit_transform(df['Institute'])
df.head()

Obtained  Marks Intermediate    Bachelor    Institute
0   1001.0          16             DPT        7
1   1001.0          16             DPT        7
2   1010.0          16             DPT        7
3   1000.0          16             DPT        7
4   1000.0          16             DPT        7

df.drop(['%age'],axis=1,inplace=True)
X=df.drop('Bachelor',axis=1)
y=df['Bachelor']
X_train,X_text,y_train,y_test=train_test_split(X,y,test_size=0.2)

model2=DecisionTreeClassifier()
model2.fit(X_train,y_train)

model2.predict([['980','1','UOS']])

当我使用此代码时,它向我显示错误:ValueError: could not convert string to float: 'UOS'。 是否有任何机制将string作为输入


Tags: fromimportledftrainsklearnprefit
1条回答
网友
1楼 · 发布于 2024-06-01 23:14:49

问题是您正在使用LabelEncoder对训练数据进行编码,但在运行model2.predict()时仍在发送原始数据


在运行predict之前,请尝试使用LabelEncoder对数据进行编码

data_encoded = le.transform([['980','1','UOS']])
model2.predict(data_encoded)

相关问题 更多 >