【问题标题】:Keras Normalization for a 2d input array二维输入数组的 Keras 标准化
【发布时间】:2021-05-01 17:05:52
【问题描述】:

我是机器学习的新手,并试图将其应用于我的问题。 我有一个包含 44000 行特征的训练数据集,形状为 6、25。我想构建一个顺序模型。我想知道是否有一种方法可以使用这些功能而不将其展平。目前,我将特征展平为一维数组并进行规范化以进行训练(参见下面的代码)。我找不到标准化二维特征的方法。

dataset2d = dataset2d.reshape(dataset2d.shape[0],
                              dataset2d.shape[1]*dataset2d.shape[2])
normalizer = preprocessing.Normalization()
normalizer.adapt(dataset2d)
print(normalizer.mean.numpy())

x_train, x_test, y_train, y_test = train_test_split(dataset2d, flux_val,
                                                    test_size=0.2)

# %% DNN regression multiple parameter
def build_and_compile_model(norm):
    inputs = Input(shape=(x_test.shape[1],))
    x = norm(inputs)
    x = layers.Dense(128, activation="selu")(x)
    x = layers.Dense(64, activation="relu")(x)
    x = layers.Dense(32, activation="relu")(x)
    x = layers.Dense(1, activation="linear")(x)
    model = Model(inputs, x)
    model.compile(loss='mean_squared_error',
                  optimizer=keras.optimizers.Adam(learning_rate=1e-3))
    return model


dnn_model = build_and_compile_model(normalizer)
dnn_model.summary()
# interrupt training when model is no longer imporving
path_checkpoint = "model_checkpoint.h5"
modelckpt_callback = keras.callbacks.ModelCheckpoint(monitor="val_loss",
                                                     filepath=path_checkpoint,
                                                     verbose=1,
                                                     save_weights_only=True,
                                                     save_best_only=True)
es_callback = keras.callbacks.EarlyStopping(monitor="val_loss",
                                            min_delta=0, patience=10)
history = dnn_model.fit(x_train, y_train, validation_split=0.2,
                        epochs=120, callbacks=[es_callback, modelckpt_callback])

我还尝试将我的模型输入层修改为以下内容,这样我就不需要重塑我的输入了

inputs = Input(shape=(x_test.shape[-1], x_test.shape[-2], ))

并将归一化修改为以下

normalizer = preprocessing.Normalization(axis=1)
normalizer.adapt(dataset2d)
print(normalizer.mean.numpy())

但这似乎没有帮助。归一化适应长度为 6 的一维数组,而我希望它适应形状为 25、6 的二维数组。

抱歉,问题太长了。非常感谢您的帮助。

【问题讨论】:

    标签: python tensorflow machine-learning keras normalization


    【解决方案1】:

    我不确定我是否理解您的问题。归一化层可以采用 N-D 张量并产生相同形状的输出,例如:

    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras import layers
    import numpy as np
    
    t = tf.constant(np.arange(2*3*4).reshape(2,3,4) , dtype=tf.float32)
    
    tf.print("\n",t)
    
    normalizer_layer = tf.keras.layers.LayerNormalization(axis=1)
    
    output = normalizer_layer(t)
    
    tf.print("\n",output)
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 1970-01-01
      • 2019-04-05
      • 2021-05-03
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多