我正在尝试使用GridSearchCV和Pipeline构建一个多输出模型.管道给我带来麻烦,因为标准分类器示例没有包装分类器的OneVsRestClassifier().我正在使用scikit-learn 0.18和python 3.5
## Pipeline: Train and Predict
## SGD: support vector machine (SVM) with gradient descent
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDClassifier
clf = Pipeline([
('vect', CountVectorizer(ngram_range=(1,3), max_df=0.50 ) ),
('tfidf', TfidfTransformer() ),
('clf', SGDClassifier(loss='modified_huber', penalty='elasticnet',
alpha=1e-4, n_iter=5, random_state=42,
shuffle=True, n_jobs=-1) ),
])
ovr_clf = OneVsRestClassifier(clf )
from sklearn.model_selection import GridSearchCV
parameters = {'vect__ngram_range': [(1,1), (1,3)],
'tfidf__norm': ('l1', 'l2', None),
'estimator__loss': ('modified_huber', 'hinge',),
}
gs_clf = GridSearchCV(estimator=pipeline, param_grid=parameters,
scoring='f1_weighted', n_jobs=-1, verbose=1)
gs_clf = …Run Code Online (Sandbox Code Playgroud) 我使用XGBBoost训练多标签分类模型,并希望在另一个系统中编写此模型.
是否可以在XGB Booster中将我的XGBClassifier模型的文本输出视为dump_model.
编辑:我发现model._Booster.dump_model(outputfile)返回一个转储文件,如下所示.但是,没有任何内容可以指定类.在我的模型中,有10个类,但是在dumpfile中只有一个助推器.所以,我不确定它是所有类的模型还是只是其中之一.
booster[0]:
0:[101<0.142245024] yes=1,no=2,missing=1
1:[107<0.102833837] yes=3,no=4,missing=3
3:[101<0.039123565] yes=7,no=8,missing=7
7:leaf=-0.0142603116
8:leaf=0.023763923
4:[101<0.0646461397] yes=9,no=10,missing=9
9:leaf=-0.0345750563
10:leaf=-0.0135767004
2:[107<0.238691002] yes=5,no=6,missing=5
5:[103<0.0775454491] yes=11,no=12,missing=11
11:leaf=0.188941464
12:leaf=0.0651629418
6:[101<0.999929309] yes=13,no=14,missing=13
13:leaf=0.00403384864
14:leaf=0.236842111
booster[1]:
0:[102<0.014829753] yes=1,no=2,missing=1
1:[102<0.00999682024] yes=3,no=4,missing=3
3:[107<0.0966737345] yes=7,no=8,missing=7
7:leaf=-0.0387153365
8:leaf=-0.0486520194
4:[107<0.0922582299] yes=9,no=10,missing=9
9:leaf=0.0301927216
10:leaf=-0.0284226239
2:[102<0.199759275] yes=5,no=6,missing=5
5:[107<0.12201979] yes=11,no=12,missing=11
11:leaf=0.093562685
12:leaf=0.0127987256
6:[107<0.298737913] yes=13,no=14,missing=13
13:leaf=0.227570012
14:leaf=0.113037519
Run Code Online (Sandbox Code Playgroud) 我正在训练一个多标签分类模型来检测衣服的属性。我在 Keras 中使用迁移学习,重新训练 vgg-19 模型的最后几层。
属性总数为 1000,其中约 99% 为 0。准确率、准确率、召回率等指标都失败了,因为该模型可以预测全为零并且仍然获得非常高的分数。二元交叉熵、汉明损失等在损失函数的情况下不起作用。
我正在使用深度时尚数据集。
那么,我可以使用哪些指标和损失函数来正确衡量我的模型?
python machine-learning multilabel-classification keras vgg-net
我正在做多标签分类,我尝试为每个文档预测正确的标签,这是我的代码:
mlb = MultiLabelBinarizer()
X = dataframe['body'].values
y = mlb.fit_transform(dataframe['tag'].values)
classifier = Pipeline([
('vectorizer', CountVectorizer(lowercase=True,
stop_words='english',
max_df = 0.8,
min_df = 10)),
('tfidf', TfidfTransformer()),
('clf', OneVsRestClassifier(LinearSVC()))])
predicted = cross_val_predict(classifier, X, y)
Run Code Online (Sandbox Code Playgroud)
运行我的代码时,我收到多个警告:
UserWarning: Label not :NUMBER: is present in all training examples.
Run Code Online (Sandbox Code Playgroud)
当我打印出预测标签和真实标签时,cca一半的所有文件都有标签为空的预测.
为什么会发生这种情况,是否与在训练运行时打印出的警告有关?我怎样才能避免那些空洞的预测呢?
LinearSVC().
我试过了RandomForestClassifier(),它也给出了空洞的预测.奇怪的是,当我cross_val_predict(classifier, X, y, method='predict_proba')用于预测每个标签的概率而不是二元决策0/1时,每个预测集总是至少有一个标签,给定文档的概率> 0.所以我不知道为什么这个标签没有选择二元决策?或者是以不同于概率的方式评估二元决策?
EDIT02: 我找到了一个老职位,其中OP处理类似的问题.这是同样的情况吗?
python classification scikit-learn text-classification multilabel-classification
无法使用class_weight来解决我的多标签问题.也就是说,每个标签都是0或1,但每个输入样本有许多标签.
代码(用于MWE目的的随机数据):
import tensorflow as tf
from keras.models import Sequential, Model
from keras.layers import Input, Concatenate, LSTM, Dense
from keras import optimizers
from keras.utils import to_categorical
from keras import backend as K
import numpy as np
# from http://www.deepideas.net/unbalanced-classes-machine-learning/
def sensitivity(y_true, y_pred):
true_positives = tf.reduce_sum(tf.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = tf.reduce_sum(tf.round(K.clip(y_true, 0, 1)))
return true_positives / (possible_positives + K.epsilon())
# from http://www.deepideas.net/unbalanced-classes-machine-learning/
def specificity(y_true, y_pred):
true_negatives = tf.reduce_sum(K.round(K.clip((1-y_true) * (1-y_pred), 0, 1)))
possible_negatives = tf.reduce_sum(K.round(K.clip(1-y_true, 0, 1)))
return true_negatives …Run Code Online (Sandbox Code Playgroud) classification machine-learning multilabel-classification keras tensorflow
我一直坚持使用多标签分类(我必须说我对神经网络很新).首先,我将解释我正在努力训练的网络.我在网络中有1000个类,它们有多标签输出.对于每个训练示例,正输出的数量相同(即10),但是它们可以分配给1000个类中的任何一个.所以10个类有输出1而其余990有输出0.对于多标签分类,我使用'二进制交叉熵'作为成本函数,'sigmoid'作为激活函数.当我尝试0.5的这个规则作为1或0的截止时.所有这些都是0.我明白这是一个类不平衡问题.从这个链接,我理解,我可能不得不创建额外的输出标签.遗憾的是,我还没有弄清楚如何将其纳入keras中的简单神经网络.
nclasses = 1000
# if we wanted to maximize an imbalance problem!
#class_weight = {k: len(Y_train)/(nclasses*(Y_train==k).sum()) for k in range(nclasses)}
#print(class_weight)
# building neural network model
inp = Input(shape=[X_train.shape[1]])
x = Dense(5000, activation='relu')(inp)
x = Dense(4000, activation='relu')(x)
x = Dense(3000, activation='relu')(x)
x = Dense(2000, activation='relu')(x)
x = Dense(nclasses, activation='sigmoid')(x)
model = Model(inputs=[inp], outputs=[x])
print(model.summary())
adam=keras.optimizers.adam(lr=0.00001)
model.compile('adam', 'binary_crossentropy')
history = model.fit(
X_train, Y_train, batch_size=32, epochs=50,verbose=0,shuffle=False)
plt.plot(history.history['loss'])
#plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
model.save('model2.h5')
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我处理这里的代码,如果你能为这个问题提出一个好的"准确度"指标,我也非常感谢你们. …
我是机器学习的新手。
我正在尝试进行多标签文本分类。我有这些文档的原始标签以及分类结果(使用 mlknn 分类器)表示为一种热编码(19000 文档 x 200 标签)。现在我正在尝试使用 f1_score micro 和 macro 来评估分类,但是我收到了这个错误(在第 3 行)ValueError: Classification metrics can't handle a mix of multiclass-multioutput and multilabel-indicator targets,我不知道如何解决它。这是我的代码:
1. y_true = np.loadtxt("target_matrix.txt")
2. y_pred = np.loadtxt("classification_results.txt")
3. print (f1_score(y_true, y_pred, average='macro'))
4. print (f1_score(y_true, y_pred, average='micro'))
Run Code Online (Sandbox Code Playgroud)
我还尝试使用cross_val_score分类来立即进行评估,但遇到了另一个错误(来自cross_val_score行):
File "_csparsetools.pyx", line 20, in scipy.sparse._csparsetools.lil_get1
File "_csparsetools.pyx", line 48, in scipy.sparse._csparsetools.lil_get1
IndexError: column index (11) out of bounds
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
X = np.loadtxt("docvecs.txt", delimiter=",")
y = np.loadtxt("target_matrix.txt", dtype='int')
cv_scores …Run Code Online (Sandbox Code Playgroud) 我正在尝试构建一个多标签分类器来预测某些输入数据的概率为0或1.我使用的是神经网络和Tensorflow + Keras(后来可能是CNN).
问题如下:数据严重偏差.还有很多负面的例子,而不是积极的,可能是90:10.因此,我的神经网络几乎总是输出非常低的概率作为正例.使用二进制数,它在大多数情况下会预测为0.
几乎所有类别的性能都> 95%,但这是因为它几乎总是预测为零......因此假阴性的数量非常高.
一些建议如何解决这个问题?
以下是我到目前为止所考虑的想法:
使用定制的损失函数惩罚假阴性(我的第一次尝试失败).类似于类中加权积极的例子而不是消极的例子.这类似于类权重,但在类中.你会如何在Keras实现这一点?
通过克隆它们然后过度拟合神经网络来过采样正例,以便平衡正面和负面的例子.
提前致谢!
python neural-network multilabel-classification keras tensorflow
我正在尝试使用270标签解决一个多标签问题,并且我已将目标标签转换为一种热编码形式。我正在使用BCEWithLogitsLoss(). 由于训练数据不平衡,我正在使用pos_weight参数,但我有点困惑。
pos_weight(张量,可选)——正例的权重。必须是长度等于类数的向量。
我是否需要将每个标签的正值的总数作为张量给出,或者它们的权重意味着其他东西?
我正在寻找可以帮助我绘制混淆矩阵的人。我在大学的学期论文中需要这个。但是我在编程方面的经验很少。
在图片中,您可以看到分类报告以及 myy_test和X_testmy 案例的结构dtree_predictions。
如果有人可以帮助我,我会很高兴,因为我尝试了很多事情,但我只是没有得到解决方案,只有错误消息。
X_train, X_test, y_train, y_test = train_test_split(X, Y_profile, test_size = 0.3, random_state = 30)
dtree_model = DecisionTreeClassifier().fit(X_train,y_train)
dtree_predictions = dtree_model.predict(X_test)
print(metrics.classification_report(dtree_predictions, y_test))
precision recall f1-score support
0 1.00 1.00 1.00 222
1 1.00 1.00 1.00 211
2 1.00 1.00 1.00 229
3 0.96 0.97 0.96 348
4 0.89 0.85 0.87 93
5 0.86 0.86 0.86 105
6 0.94 0.93 0.94 116
7 1.00 1.00 1.00 364
8 0.99 0.97 0.98 …Run Code Online (Sandbox Code Playgroud) python decision-tree confusion-matrix scikit-learn multilabel-classification