如何解决除“ {”之后没有执行Python尝试?
我被卡在问题下方显示的python代码上。
此代码是受监督的神经网络项目的一部分。
遇到未知标签时,encoder.inverse_transform(x)
会产生ValueError。
我期望的是:代码为每个x返回一个结果,当x不在encoder.classes_
中时,该x的结果将为'Onbekend'
。
它的作用是:当Output包含一个未知标签时,无论x的数量如何,代码都会导致一个“ Onbekend”。 似乎并没有为输出中的每个x执行try函数。
有人知道我在这里想念什么吗?
import pandas as pd
from sklearn import model_selection
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
import bisect
# Dataframe creation
data = {'Text': ['Koffie','Auto onderdelen','Brandstof','Zeilen','Studie','Cadeau','Telefoon'],'Labels': ['Leven','Auto','Leven','Telefonie']}
trainDF = pd.DataFrame(data=data,dtype = str)
#split the dataset into training and validation datasets
train_x,valid_x,train_y,valid_y =
model_selection.train_test_split(trainDF['Text'],trainDF['Labels'])
# label encode the target variable
encoder = LabelEncoder()
train_y = encoder.fit_transform(train_y)
valid_y = encoder.fit_transform(valid_y)
# Create a count vectorizer object
count_vect = CountVectorizer(analyzer = 'word',token_pattern='\w{1,}')
count_vect.fit(trainDF['Text'])
# Transform the training and validation data using count vectorizer object
xtrain_count = count_vect.transform(train_x)
xvalid_count = count_vect.transform(valid_x)
classifier = LogisticRegression()
classifier.fit(xtrain_count,train_y)
# Modelling
xinput_count = count_vect.transform(trainDF['Text'])
Output = classifier.predict(xinput_count)
for x in Output:
b = b + 1
try:
R = encoder.inverse_transform(Output)
except ValueError:
R = 'Onbekend'
encoder_classes = encoder.classes_.tolist()
bisect.insort_left(encoder_classes,'Onbekend')
encoder.classes_ = encoder_classes
print(R)
解决方法
代码应为:
for x in Output:
try:
x = encoder.inverse_transform(x)
except ValueError:
x = 'Onbekend'
print(x)
由于print(x)
未嵌套在for循环中,因此它将返回x的最后一个值,而不是完整的数组。
令人误解的部分是,R = encoder.inverse_transform(Output)
使用完整的Output数组,print(R)
将返回完整的数组,因为Output
仅包含已知标签,使其看起来像代码正确。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。