[英]Data pre-processing steps with different features
我想在分類器中包含多個功能,以更好地提高 model 性能。 我有一個類似於這個的數據集
文本 | is_it_capital? | is_it_upper? | 包含數? | Label |
---|---|---|---|---|
文本示例 | 0 | 0 | 0 | 0 |
另一個文本示例 | 1 | 1 | 0 | 1 |
發生了什么事?我們 5 點再說吧 | 1 | 0 | 1 | 1 |
我正在對文本(BoW、TF-IDF、...)應用不同的預處理算法。 通過選擇X= df['Text']
並應用預處理算法,在我的分類器中僅使用 Text 列是“容易的”。 但是,我現在還想包括is_it_capital?
和其他變量(標簽除外)作為特征,因為我發現它們可能對我的分類器有用。 我嘗試的是以下內容:
X=df[['Text','is_it_capital?', 'is_it_upper?', 'contains_num?']]
y=df['Label']
from sklearn.base import TransformerMixin
class DenseTransformer(TransformerMixin):
def fit(self, X, y=None, **fit_params):
return self
def transform(self, X, y=None, **fit_params):
return X.todense()
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
('vectorizer', CountVectorizer()),
('to_dense', DenseTransformer()),
])
transformer = ColumnTransformer([('text', pipeline, 'Text')], remainder='passthrough')
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=40)
X_train = transformer.fit_transform(X_train)
X_test = transformer.transform(X_test)
df_train = pd.concat([X_train, y_train], axis=1)
df_test = pd.concat([X_test, y_test], axis=1)
#Logistic regression
logR_pipeline = Pipeline([
('LogRCV',countV),
('LogR_clf',LogisticRegression())
])
logR_pipeline.fit(df_train['Text'], df_train['Label'])
predicted_LogR = logR_pipeline.predict(df_test['Text'])
np.mean(predicted_LogR == df_test['Label'])
但是我得到了錯誤:
TypeError: 無法連接類型為'<class'scipy.sparse.csr.csr_matrix'>'的object; 只有 Series 和 DataFrame 對象有效
有沒有人處理過類似的問題? 我該如何解決? 我的目標是在我的分類器中包含所有功能。
更新:
我也試過這個:
from sklearn.base import BaseEstimator,TransformerMixin
class custom_count_v(BaseEstimator,TransformerMixin):
def __init__(self,tfidf):
self.tfidf = tfidf
def fit(self, X, y=None):
joined_X = X.apply(lambda x: ' '.join(x), axis=1)
self.tfidf.fit(joined_X)
return self
def transform(self, X):
joined_X = X.apply(lambda x: ' '.join(x), axis=1)
return self.tfidf.transform(joined_X)
count_v = CountVectorizer()
clmn = ColumnTransformer([("count", custom_count_v(count_v), ['Text'])],remainder="passthrough")
clmn.fit_transform(df)
它不會返回任何錯誤,但不清楚我是否正確包含所有功能,以及是否需要在訓練/測試拆分之前或之后進行。如果您能在申請之前向我展示這將非常有幫助分類器:
#Logistic regression
logR_pipeline = Pipeline([
('LogRCV',....),
('LogR_clf',LogisticRegression())
])
logR_pipeline.fit(....)
predicted_LogR = logR_pipeline.predict(...)
np.mean(predicted_LogR == ...)
應該是 dataframe 或列而不是點(我猜這取決於轉換和連接),以便更好地執行我所做的步驟和錯誤。
您的錯誤似乎試圖連接 arrays 和系列。
我對pipeline和columntransformer不熟悉,所以我可能會弄錯; 似乎它沒有從 CountVectorizer 中捕獲特征名稱,因此沒有標記的 dataframe 沒有任何好處:也許您可以堅持使用 numpy ZA3CBC3F9D0CE2F2C1554E1B671 如果我弄錯了,無論如何從 np.array 跳轉到 dataframe 應該很容易......
所以,你可以這樣做:
df_train = np.append(
X_train, #this is an array
np.array(y_train).reshape(len(y_train),1), #convert the Serie to numpy array of correct shape
axis=1)
print(df_train)
[[1 0 1 0 0 1 0 1 0 1 1 0 1]
[0 1 0 1 1 0 1 0 1 1 0 1 1]]
希望這會有所幫助(盡管正如我所說,我不熟悉這些 sklearn 庫......)
編輯
更完整的東西,沒有那些管道(我不確定是否需要); 由於輸入數據集,它在我的計算機上失敗了,但是您的完整數據集可能會更成功。
df = pd.DataFrame(
[["an example of text", 0, 0, 0, 0],
["ANOTHER example of text", 1, 1, 0, 1],
["What's happening?Let's talk at 5", 1, 0, 1, 1]
],
columns=["Text", "is_it_capital?", "is_it_upper?", "contains_num?", "Label"]
)
X=df[['Text','is_it_capital?', 'is_it_upper?', 'contains_num?']]
y=df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=40)
cv = CountVectorizer()
X_train = (
pd.DataFrame(
cv.fit_transform(X_train['Text']).toarray(),
columns=cv.get_feature_names(),
index=X_train.index
) #This way you keep the labels/indexes in a dataframe format
.join(X_train.drop('Text', axis=1)) #add your previous 'get_dummies' columns
)
X_test = (
pd.DataFrame(
cv.transform(X_test['Text']).toarray(),
columns=cv.get_feature_names(),
index=X_test.index
)
.join(X_test.drop('Text', axis=1))
)
#Then compute your regression directly :
lr = LogisticRegression()
lr = lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.