1
我有從doc2vec算法創建的花車矢量,以及他們的標籤。當我用一個簡單的分類器來使用它們時,它可以正常工作並給出預期的準確性。工作代碼如下:Scikit學習管道相同的數據和步驟無法分類
from sklearn.svm import LinearSVC
import pandas as pd
import numpy as np
train_vecs #ndarray (20418,100)
#train_vecs = [[0.3244, 0.3232, -0.5454, 1.4543, ...],...]
y_train #labels
test_vecs #ndarray (6885,100)
y_test #labels
classifier = LinearSVC()
classifier.fit(train_vecs, y_train)
print('Test Accuracy: %.2f'%classifier.score(test_vecs, y_test))
但是現在我想將它移動到一個管道,因爲在未來,我計劃做一個特徵工會各具特色。我所做的是將矢量移動到數據框中,然後使用2個自定義變換器來選擇列,ii)更改數組類型。奇怪的是,完全相同的數據,具有完全相同的形狀,dtype和類型..給出0.0005的準確性。它對我來說根本沒有意義,它應該給出幾乎相等的準確度。在ArrayCaster變壓器之後,輸入的形狀和類型與之前完全相同。整件事情非常令人沮喪。
from sklearn.svm import LinearSVC
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin
# transformer that picks a column from the dataframe
class ItemSelector(BaseEstimator, TransformerMixin):
def __init__(self, column):
self.column = column
def fit(self, X, y=None, **fit_params):
return self
def transform(self, X):
print('item selector type',type(X[self.column]))
print('item selector shape',len(X[self.column]))
print('item selector dtype',X[self.column].dtype)
return (X[self.column])
# transformer that converts the series into an ndarray
class ArrayCaster(BaseEstimator, TransformerMixin):
def fit(self, x, y=None):
return self
def transform(self, data):
print('array caster type',type(np.array(data.tolist())))
print('array caster shape',np.array(data.tolist()).shape)
print('array caster dtype',np.array(data.tolist()).dtype)
return np.array(data.tolist())
train_vecs #ndarray (20418,100)
y_train #labels
test_vecs #ndarray (6885,100)
y_test #labels
train['vecs'] = pd.Series(train_vecs.tolist())
val['vecs'] = pd.Series(test_vecs.tolist())
classifier = Pipeline([
('selector', ItemSelector(column='vecs')),
('array', ArrayCaster()),
('clf',LinearSVC())])
classifier.fit(train, y_train)
print('Test Accuracy: %.2f'%classifier.score(test, y_test))