python - 如何在 tensorflow 中平均一层的输出?

标签 python tensorflow machine-learning keras

这是我尝试用 tensorflow 实现的一个玩具模型。输入是一组 (10) 实数对。我想要近似的底层函数是 formula 。实现的模型应如下所示:

model architecture

我还需要提及的是,“隐藏层”对于所有 X_i 来说都是同一层(相同的参数)。

到目前为止我实现了什么:

import tensorflow as tf
import numpy as np

def tf_model():
    # Define the inputs
    inputs = tf.keras.Input(shape=[10, 2])

    # Define common hidden layer
    hidden_layer = tf.keras.layers.Dense(64, activation="relu")(inputs)

    # Propagate and average
    outputs = tf.keras.layers.Dense(1, activation="sigmoid")(hidden_layer)
    outputs = tf.keras.layers.Average()(outputs)

    return tf.keras.Model(inputs=inputs, outputs=output)

X = np.random.rand(1000,10,2) * 100
y = 1 / (1 + X[...,0]**2 + X[...,1]**4)
y = np.average(y, axis=1)

model = tf_model()
model.fit(X, y)

运行这个我得到什么:

Traceback (most recent call last):
File "model_test.py", line 21, in <module>
    model = tf_model()
File "model_test.py", line 13, in tf_model
    outputs = tf.keras.layers.Average()(outputs)
File "/home/redbull/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "/home/redbull/.local/lib/python3.8/site-packages/keras/layers/merge.py", line 88, in build
    raise ValueError(
ValueError: A merge layer should be called on a list of inputs. Received: input_shape=(None, 10, 1) (not a list of shapes)

我认为问题在于 tf.keras.layers.Average() 仅适用于输入列表,但不适用于 tf 层/张量。

由于tf.keras.layers.Average()似乎不适合这种情况,我该如何实现想要的功能?

最佳答案

您可以使用tf.reduce_mean,如下所示。

outputs = tf.reduce_mean(outputs, axis=1)

关于python - 如何在 tensorflow 中平均一层的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71364558/

相关文章:

Python,如何在文本消息的同一行打印当前日期时间?

python - 为什么我需要在Keras中编译和拟合预训练模型?

python - 从 Pandas DataFrame 计算 IDF

machine-learning - OpenCL Theano - 如何强制禁用 CUDA?

python - ValueError : Input 0 is incompatible with layer simple_rnn_1: expected ndim=3, 在 Keras 中发现 ndim=2

python - 根据 pandas 数据框中的特定列以及其他列在单独的列中按计数和总和进行分组

python - 我们如何从Python中的glyph id获取unicode?

python - 输出出现两次 - 更新发布此问题前 30 分钟提出的问题

python - 神经网络在数字序列中寻找模式

python - 如何在 Tensorflow 中绘制张量并将其保存为图像