【问题标题】:How to average a layer's output in tensorflow?如何在张量流中平均一层的输出?
【发布时间】:2022-06-20 16:09:45
【问题描述】:

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

我还需要提一下,“隐藏层”是所有 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() 似乎不适合这种情况,我该如何实现想要的功能?

【问题讨论】:

    标签: python tensorflow machine-learning keras


    【解决方案1】:

    您可以使用 tf.reduce_mean 如下。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多