繁体   English   中英

如何在 Keras 回归模型中包含特征的归一化?

[英]How to include normalization of features in Keras regression model?

我有一个回归任务的数据。 独立特征( 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 作为常量注入到 Tensorflow Graph 中。 由于这些转换在图中表示为常量,因此它们在训练和服务中将保持一致。 跨培训和服务的一致性的优点是

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

下面提到了 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM