简体   繁体   English

确定 Keras model 的输入形状

[英]Determine the input shape of a Keras model

I have a question about the feature_columns and the input_shape argument in tf.keras.layers.InputLayer and in Tensorflow.我对tf.keras.layers.InputLayer和 Tensorflow 中的feature_columnsinput_shape参数有疑问。

I'm following an example which has the following code to create the feature columns:我正在关注一个示例,该示例具有以下代码来创建功能列:

feature_columns = []
latitude = tf.feature_column.numeric_column("latitude")
feature_columns.append(latitude)
longitude = tf.feature_column.numeric_column("longitude")
feature_columns.append(longitude)
fp_feature_layer = layers.DenseFeatures(feature_columns)

And below is the code to build the model:下面是构建 model 的代码:

def build_model(my_learning_rate, feature_layer)
    model = tf.keras.models.Sequential()
    model.add(feature_layer)
    model.add(tf.keras.layers.Dense(units=1, input_shape=(1,)))
    model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=my_learning_rate),
            loss="mean_squared_error",
            metrics=[tf.keras.metrics.RootMeanSquaredError()])

When calling the build_model function, I will pass in a learning rate and the feature layer, which will be the fp_feature_layer .在调用build_model function 时,我将传入学习率和特征层,即fp_feature_layer My question is that since the feature_columns has two features in it, which is latitude and longitude, shouldn't the input_shape be (2,) instead of (1,) .我的问题是,由于feature_columns中有两个特征,即纬度和经度,所以input_shape不应该是(2,)而不是(1,) Or, more generally, since the code is already specifying the feature_layer , do we still specify the input_shape in model.add(tf.keras.layers.Dense() ? Shouldn't the input_shape be determined by the feature_layer ? Is it how it works? Since the output is only one value for each example, units=1 makes sense to me. But I'm having a hard time understanding the input_shape . Thanks in advance!或者更笼统地说,既然代码已经指定了feature_layer ,那我们还要在model.add(tf.keras.layers.Dense()中指定input_shape吗? input_shape不应该由feature_layer来决定吗?是这样吗?有效吗?由于 output 对于每个示例只有一个值,因此units=1对我来说很有意义。但我很难理解input_shape 。提前致谢!

Yes, your understanding of feature layer will know the input shape, we don't need to specify the input shape again in the first hidden layer is correct.是的,你对feature layer will know the input shape, we don't need to specify the input shape again in the first hidden layer是正确的。

So, the code can be modified from所以,代码可以从

model.add(tf.keras.layers.Dense(units=1, input_shape=(1,)))

to

model.add(tf.keras.layers.Dense(units=1))

Please refer this Comprehensive Tensorflow Tutorial to understand how to use Feature Columns and Feature Layer in Keras Sequential Model .请参阅此综合 Tensorflow 教程以了解如何在Keras Sequential Model中使用Feature ColumnsFeature Layer

Hope this helps.希望这可以帮助。 Happy Learning!快乐学习!

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

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