scikit-learn 1.2.0 中有很多变化,它支持所有变压器的 pandas 输出,但如何在自定义变压器中使用它?
在[1]中:这是我的自定义变压器,它是一个标准缩放器:
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class StandardScalerCustom(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
self.mean = np.mean(X, axis=0)
self.std = np.std(X, axis=0)
return self
def transform(self, X):
return (X - self.mean) / self.std
Run Code Online (Sandbox Code Playgroud)
在[2]中:创建了特定的scale管道
scale_pipe = make_pipeline(StandardScalerCustom())
Run Code Online (Sandbox Code Playgroud)
在[3]中:添加到一个完整的管道中,它可能与缩放器、输入器、编码器等混合。
full_pipeline = ColumnTransformer([
("imputer", impute_pipe, ['column_1'])
("scaler", scale_pipe, ['column_2'])
])
# From documentation
full_pipeline.set_output(transform="pandas")
Run Code Online (Sandbox Code Playgroud)
得到这个错误:
ValueError:无法配置 StandardScalerCustom() 的输出,因为set_output不可用。
有一个解决方案,它可以是:
set_config(transform_output="pandas")
但根据具体情况,如何在 StandardScalerCustom() 类中创建一个可以修复上述错误的函数?
我的文字如图所示:
list1 = ["My name is xyz", "My name is pqr", "I work in abc"]
Run Code Online (Sandbox Code Playgroud)
以上将是使用 kmeans 聚类文本的训练集。
list2 = ["My name is xyz", "I work in abc"]
Run Code Online (Sandbox Code Playgroud)
以上是我的测试集。
我构建了一个矢量化器和模型,如下所示:
vectorizer = TfidfVectorizer(min_df = 0, max_df=0.5, stop_words = "english", charset_error = "ignore", ngram_range = (1,3))
vectorized = vectorizer.fit_transform(list1)
km=KMeans(n_clusters=2, init='k-means++', n_init=10, max_iter=1000, tol=0.0001, precompute_distances=True, verbose=0, random_state=None, copy_x=True, n_jobs=1)
km.fit(vectorized)
Run Code Online (Sandbox Code Playgroud)
如果我尝试预测“list2”测试集的集群:
km.predict(list2)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ValueError: Incorrect number of features. Got 2 features, expected 5
Run Code Online (Sandbox Code Playgroud)
有人告诉我用它Pipeline来解决这个问题。所以我写了下面的代码:
pipe = Pipeline([('vect', vectorizer), ('vectorized', …Run Code Online (Sandbox Code Playgroud) python machine-learning k-means scikit-learn scikit-learn-pipeline