使用Scikit-learn LabelEncoder遇报错:'LabelEncoder'无classes_属性
Hey there, let's break down why you're hitting this AttributeError and fix it step by step.
核心原因
The classes_ attribute of LabelEncoder doesn't exist out of the box—it only gets created after you call the fit() method on your label data. Right now, you've just initialized the encoder with encoder = LabelEncoder() but never used it to process any labels, so the attribute hasn't been generated yet. That's exactly why Python is throwing that error.
具体修复步骤
先拟合你的标签数据
Before you try to accessencoder.classes_, you need to feed your label data into the encoder usingfit(). For example, if your labels are stored in a variable likey_train, run this first:encoder.fit(y_train) # Replace y_train with your actual label data调整代码顺序&避免命名冲突
You've named one of your functionsclasses_()—while this isn't a bug, it's easy to confuse with the encoder'sclasses_attribute. Renaming it to something likeget_classes()will make your code clearer. Also, make sure thefit()call happens before you define or call these helper functions.修正Dense层的参数顺序
Your last line of code has a syntax issue with theDenselayer. The correct order for parameters (especially in Keras) should have the number of units first, followed by input dimensions (if needed), then activation. Your current code has293floating in the middle, which will cause another error.
修改后的完整代码示例
from sklearn.preprocessing import LabelEncoder from keras.layers import TimeDistributed, Dense # 示例标签数据(替换成你自己的真实标签) y = ["class_a", "class_b", "class_a", "class_c"] # 初始化并拟合编码器——这一步是关键! encoder = LabelEncoder() encoder.fit(y) def get_classes(): # Return the classes which are classified by this model return encoder.classes_ def num_of_classes(): """ Return the number of output classes """ return len(get_classes()) # 修正后的TimeDistributed + Dense层 X = TimeDistributed(Dense(units=num_of_classes(), input_dim=293, activation="softmax"))
额外提醒
If your label data is loaded or processed later in your code, make sure you call encoder.fit() before you invoke num_of_classes() or get_classes(). If you're working within a class structure, consider putting the fit() call inside your class's __init__ method to ensure the encoder is ready when you need it.
内容的提问来源于stack exchange,提问作者IS92

