python - 如何使用 sklearn 管道缩放 Keras 自动编码器模型的目标值?

标签 python tensorflow machine-learning keras scikit-learn

我正在使用 sklearn 管道来构建 Keras 自动编码器模型并使用 gridsearch 来查找最佳超参数。如果我使用多层感知器模型进行分类,这很好用;但是,在自动编码器中,我需要输出值与输入相同。换句话说,我使用的是 StandardScalar管道中的实例以缩放输入值,因此这引出了我的问题:我如何制作 StandardScalar管道内的实例同时处理输入数据和目标数据,以便它们最终相同?
我提供了一个代码片段作为示例。

from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV, KFold
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop, Adam
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor

X, y = make_classification (n_features = 50, n_redundant = 0, random_state = 0,
                            scale = 100, n_clusters_per_class = 1)

# Define wrapper
def create_model (learn_rate = 0.01, input_shape, metrics = ['mse']):
  model = Sequential ()
  model.add (Dense (units = 64, activation = 'relu',
                   input_shape = (input_shape, )))
  model.add (Dense (32, activation = 'relu'))
  model.add (Dense (8,  activation = 'relu'))
  model.add (Dense (32, activation = 'relu'))
  model.add (Dense (input_shape, activation = None))
  model.compile (loss = 'mean_squared_error',
                 optimizer = Adam (lr = learn_rate),
                 metrics = metrics)
  return model

# Create scaler
my_scaler = StandardScaler ()
steps = list ()
steps.append (('scaler', my_scaler))
standard_scaler_transformer = Pipeline (steps)

# Create classifier
clf = KerasRegressor (build_fn = create_model, verbose = 2)

# Assemble pipeline
# How to scale input and output??
clf = Pipeline (steps = [('scaler', my_scaler),
                         ('classifier', clf)],
                verbose = True)

# Run grid search
param_grid = {'classifier__input_shape' : [X.shape [1]],
              'classifier__batch_size' : [50],
              'classifier__learn_rate' : [0.001],
              'classifier__epochs' : [5, 10]}
cv = KFold (n_splits = 5, shuffle = False)
grid = GridSearchCV (estimator = clf, param_grid = param_grid,
                     scoring = 'neg_mean_squared_error', verbose = 1, cv = cv)
grid_result = grid.fit (X, X)

print ('Best: %f using %s' % (grid_result.best_score_, grid_result.best_params_))

最佳答案

您可以使用 TransformedTargetRegressor 通过提供函数(即使用 y 参数)或转换器(即 func 参数)对目标值(即 transformer )应用任意变换。
在这种情况下(即拟合自动编码器模型),因为您想应用相同的 StandardScalar目标值上的实例,您可以使用 transformer争论。它可以通过以下方式之一完成:

  • 您可以将其用作管道步骤之一,包装回归量:
    scaler = StandardScaler()
    regressor = KerasRegressor(...)
    
    pipe = Pipeline(steps=[
        ('scaler', scaler),
        ('ttregressor', TransformedTargetRegressor(regressor, transformer=scaler))
    ])
    
    # Use `__regressor` to access the regressor hyperparameters
    param_grid = {'ttregressor__regressor__hyperparam_name' : ...}
    
    gridcv = GridSearchCV(estimator=pipe, param_grid=param_grid, ...)
    gridcv.fit(X, X)
    
  • 或者,您可以将它包裹在 GridSearchCV 周围。像这样:
     ttgridcv = TransformedTargetRegressor(GridSearchCV(...), transformer=scalar)
     ttgridcv.fit(X, X)
    
     # Use `regressor_` attribute to access the fitted regressor (i.e. `GridSearchCV` instance) 
     print(ttgridcv.regressor_.best_score_, ttgridcv.regressor_.best_params_))
    
  • 关于python - 如何使用 sklearn 管道缩放 Keras 自动编码器模型的目标值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63094847/

    相关文章:

    python - Pandas :TypeError: float() argument must be a string or a number, 不是 'pandas._libs.interval.Interval'

    python - 如何使用 Python 获取默认网关 IP?

    python - "Failed to locate libpython within timeout period."尝试使用 pyflame 分析不在容器中的 .py 文件时

    python - web3.py中sendTransaction和sendRawTransaction的区别

    python - 我的 python 游戏代码无法运行

    python - 循环 model.fit 时无法重置模型

    amazon-web-services - AWS g4dn.4xlarge 实例中的驱动程序空间不足

    python - 使用 Keras,如何输入 X_train 图像(超过一千张图像)?

    python - 如何判断哪个 Keras 模型更好?

    python - 具有一个(或多个)参数的 Python 多输出回归或分类器