我正在研究一个多标签分类问题
import pandas as pd
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
tdf = pd.read_csv("data.csv", index_col="DocID",error_bad_lines=False)[:8]
print tdf
给我
DocID Content Tags
1 some text here... [70]
2 some text here... [59]
3 some text here... [183]
4 some text here... [173]
5 some text here... [71]
6 some text here... [98]
7 some text here... [211]
8 some text here... [188]
然后我根据需要识别和转换列
X=tdf["Content"]
y=tdf["Tags"]
t=TfidfVectorizer()
print t.fit_transform(X).toarray()
print MultiLabelBinarizer().fit_transform(y)
给我
[[ 0. 0.01058315 0. ..., 0.00529157 0. 0. ]
[ 0. 0.00947091 0. ..., 0.00473545 0. 0. ]
[ 0.01190602 0.00950931 0. ..., 0.00475465 0. 0. ]
...,
[ 0. 0.01314373 0. ..., 0.00657187 0. 0. ]
[ 0. 0.01200425 0.37574455 ..., 0.00600212 0.01502978 0. ]
[ 0. 0.02206688 0. ..., 0.01103344 0. 0. ]]
[[1 0 0 0 0 1 0 0 1 1]
[0 0 0 0 1 0 0 1 1 1]
[0 1 0 1 0 0 1 0 1 1]
[0 1 0 1 0 1 0 0 1 1]
[0 1 0 0 0 1 0 0 1 1]
[0 0 0 0 0 0 1 1 1 1]
[0 1 1 0 0 0 0 0 1 1]
[0 1 0 0 0 0 1 0 1 1]]
看看我的数据,这里的 y不应该只有 8 列吗?为什么有 10 列?
然后我拆分、变换、拟合并得分
Xtrain, Xvalidate, ytrain, yvalidate = train_test_split(X, y, test_size=.5)
Xtrain=t.fit_transform(Xtrain).toarray()
Xvalidate=t.fit_transform(Xvalidate).toarray()
ytrain=MultiLabelBinarizer().fit_transform(ytrain)
yvalidate=MultiLabelBinarizer().fit_transform(yvalidate)
clf = OneVsRestClassifier(LogisticRegression(penalty='l2', C=0.01)).fit(Xtrain, ytrain)
print "One vs rest accuracy: %.3f" % clf.score(Xvalidate,yvalidate)
但我得到了错误
print "One vs rest accuracy: %.3f" % clf.score(Xvalidate,yvalidate)
File "X:\Anaconda2\lib\site-packages\sklearn\base.py", line 310, in score
return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
File "X:\Anaconda2\lib\site-packages\sklearn\multiclass.py", line 325, in predict
indices.extend(np.where(_predict_binary(e, X) > thresh)[0])
File "X:\Anaconda2\lib\site-packages\sklearn\multiclass.py", line 83, in _predict_binary
score = np.ravel(estimator.decision_function(X))
File "X:\Anaconda2\lib\site-packages\sklearn\linear_model\base.py", line 249, in decision_function
% (X.shape[1], n_features))
ValueError: X has 1546 features per sample; expecting 1354
这个错误是什么意思?可能是数据吗?我已经使用具有相似(相同列格式和数据格式)数据的完全相同的算法,并且没有问题。另外,为什么 fit 函数有效?
我在这里做错了什么?
编辑
所以在我的标签列中,数据被读取为字符串。因此 y 中有两个额外的列。我试过了
X=tdf["Content"]
y=tdf["Tags"]
y = [map(int, list(_y.replace(',','').replace('[','').replace(']',''))) for _y in y]
以适应多个值,但我仍然是同样的错误。至少我得到了正确的 y 列数。