这是我的代码:
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import KFold
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import datasets
import numpy as np
newsgroups = datasets.fetch_20newsgroups(
subset='all',
categories=['alt.atheism', 'sci.space']
)
X = newsgroups.data
y = newsgroups.target
TD_IF = TfidfVectorizer()
y_scaled = TD_IF.fit_transform(newsgroups, y)
grid = {'C': np.power(10.0, np.arange(-5, 6))}
cv = KFold(y_scaled.size, n_folds=5, shuffle=True, random_state=241)
clf = SVC(kernel='linear', random_state=241)
gs = GridSearchCV(estimator=clf, param_grid=grid, scoring='accuracy', cv=cv)
gs.fit(X, y_scaled)
我收到错误,我不明白为什么。回溯:
Traceback(最近一次调用最后一次): File
"C:/User/Roman/PycharmProjects/week_3/assignment_2.py",第23行,in
gs.fit(X,y_scaled)#待办事项:选中此行File"C:\User\Roman\AppData\Roaming\Python\Python35\site-包\sklear\grid_search.py",
line 804,in fit
返回self_fit(X,y,ParameterGrid(self.param_grid))File"C:\User\Roman\AppData\Roaming\Python\Python35\site-包\sklear\grid_search.py",
line 525,in_fit
X,y=indexable(X,y)File"C:\User\Roman\AppData\Roaming\Python\Python35\site-包\sklear\utils\validation.py",
line 201,in indexable
check_consistent_length(*结果)File"C:\User\Roman\站点包\sklear\utils\validation.py",
第176行,check_consistent_length
"%s"%str(唯一项))
ValueError:发现样本数不一致的数组:[6 1786]
有人能解释为什么会出现这个错误吗?
我认为您对这里的X
和y
有点困惑。您想将您的X
转换为tf-idf向量并使用它对y
进行训练。见下文
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import KFold
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import datasets
import numpy as np
newsgroups = datasets.fetch_20newsgroups(
subset='all',
categories=['alt.atheism', 'sci.space']
)
X = newsgroups.data
y = newsgroups.target
TD_IF = TfidfVectorizer()
X_scaled = TD_IF.fit_transform(X, y)
grid = {'C': np.power(10.0, np.arange(-1, 1))}
cv = KFold(y_scaled.size, n_folds=5, shuffle=True, random_state=241)
clf = SVC(kernel='linear', random_state=241)
gs = GridSearchCV(estimator=clf, param_grid=grid, scoring='accuracy', cv=cv)
gs.fit(X_scaled, y)