gpt4 book ai didi

python-3.x - 如何在 Keras 回归模型中包含特征的归一化?

转载 作者:行者123 更新时间:2023-12-04 15:46:47 25 4
gpt4 key购买 nike

我有一个回归任务的数据。
独立特征( X_train )使用标准缩放器进行缩放。
构建了一个 Keras 序列模型,添加了隐藏层。编译模型。
然后用 model.fit(X_train_scaled, y_train ) 拟合模型
然后我将模型保存在 .hdf5 中文件。

现在如何在保存的模型中包含缩放部分,
以便可以将相同的缩放参数应用于看不见的测试数据。

#imported all the libraries for training and evaluating the model
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42)
sc = StandardScaler()
X_train_scaled = sc.fit_transform(X_train)
X_test_scaled= sc.transform (X_test)



def build_model():
model = keras.Sequential([layers.Dense(64, activation=tf.nn.relu,input_shape=[len(train_dataset.keys())]),
layers.Dense(64, activation=tf.nn.relu),
layers.Dense(1)
])

optimizer = tf.keras.optimizers.RMSprop(0.001)

model.compile(loss='mean_squared_error',
optimizer=optimizer,
metrics=['mean_absolute_error', 'mean_squared_error'])
return model
model = build_model()
EPOCHS=1000
history = model.fit(X_train_scaled, y_train, epochs=EPOCHS,
validation_split = 0.2, verbose=0)

loss, mae, mse = model.evaluate(X_test_scaled, y_test, verbose=0)

最佳答案

根据我的理解,标准和有效的方法是使用 Tensorflow Transform。如果我们必须使用 TF Transform,这本质上并不意味着我们应该使用整个 TFX Pipeline。 TF Transform 也可以作为独立使用。

Tensorflow Transform 创建了一个 Beam Transormation Graph,它将这些 Transformations 作为常量注入(inject)到 Tensorflow Graph 中。由于这些转换在图中表示为常量,因此它们在训练和服务中将保持一致。跨培训和服务的一致性的优点是

  • 消除训练服务偏差
  • 无需在服务系统中使用代码,从而改善延迟。

  • 下面提到了 TF 变换的示例代码:

    导入所有依赖项的代码:
    try:
    import tensorflow_transform as tft
    import apache_beam as beam
    except ImportError:
    print('Installing TensorFlow Transform. This will take a minute, ignore the warnings')
    !pip install -q tensorflow_transform
    print('Installing Apache Beam. This will take a minute, ignore the warnings')
    !pip install -q apache_beam
    import tensorflow_transform as tft
    import apache_beam as beam

    import tensorflow as tf
    import tensorflow_transform.beam as tft_beam
    from tensorflow_transform.tf_metadata import dataset_metadata
    from tensorflow_transform.tf_metadata import dataset_schema

    下面提到的是预处理功能,其中我们提到了所有转换:
    def preprocessing_fn(inputs):
    """Preprocess input columns into transformed columns."""
    # Since we are modifying some features and leaving others unchanged, we
    # start by setting `outputs` to a copy of `inputs.
    outputs = inputs.copy()

    # Scale numeric columns to have range [0, 1].
    for key in NUMERIC_FEATURE_KEYS:
    outputs[key] = tft.scale_to_0_1(outputs[key])

    for key in OPTIONAL_NUMERIC_FEATURE_KEYS:
    # This is a SparseTensor because it is optional. Here we fill in a default
    # value when it is missing.
    dense = tf.sparse_to_dense(outputs[key].indices,
    [outputs[key].dense_shape[0], 1],
    outputs[key].values, default_value=0.)
    # Reshaping from a batch of vectors of size 1 to a batch to scalars.
    dense = tf.squeeze(dense, axis=1)
    outputs[key] = tft.scale_to_0_1(dense)

    return outputs

    此外
    tft.scale_to_0_1

    您还可以使用其他 API 进行规范化,例如
    tft.scale_by_min_max, tft.scale_to_z_score

    您可以引用下面提到的链接以获取详细信息和 TF 转换教程。

    https://www.tensorflow.org/tfx/transform/get_started

    https://www.tensorflow.org/tfx/tutorials/transform/census

    关于python-3.x - 如何在 Keras 回归模型中包含特征的归一化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55430596/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com