Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在Keras回归模型中包含特征的标准化?_Python 3.x_Keras_Pipeline_Keras Layer_Tensorflow Serving - Fatal编程技术网

Python 3.x 如何在Keras回归模型中包含特征的标准化?

Python 3.x 如何在Keras回归模型中包含特征的标准化?,python-3.x,keras,pipeline,keras-layer,tensorflow-serving,Python 3.x,Keras,Pipeline,Keras Layer,Tensorflow Serving,我有一个回归任务的数据。 独立特征(X_train)用标准缩放器缩放。 构建了添加隐藏层的Keras序列模型。编辑模型。 然后用模型拟合模型。拟合(X\U序列缩放,y\U序列) 然后我将模型保存在.hdf5文件中 现在,如何在保存的模型中包含缩放部分, 因此,相同的缩放参数可以应用于看不见的测试数据 #imported all the libraries for training and evaluating the model X_train, X_test, y_train, y_test

我有一个回归任务的数据。 独立特征(
X_train
)用标准缩放器缩放。 构建了添加隐藏层的Keras序列模型。编辑模型。 然后用
模型拟合模型。拟合(X\U序列缩放,y\U序列)
然后我将模型保存在
.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变换。本质上,这并不意味着如果我们必须使用TF转换,就应该使用整个TFX管道。TF转换也可以作为独立的转换使用

Tensorflow变换创建梁变换图,该图将这些变换作为常数注入Tensorflow图中。由于这些转换在图中表示为常量,因此它们在培训和服务中是一致的。培训和服务的一致性优势如下:

  • 消除训练服务倾斜
  • 消除了在服务系统中使用代码的需要,从而提高了延迟
  • 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转换教程,请参阅下面提到的链接

    可能存在的副本