python - Can't save Keras model when using reduce_mean in the model?
问题描述
The Keras code snippet reads:
second_input = inputs_d['second_input']
selected = embedding_layer(second_input)
item_average = tf.reduce_mean(selected, axis=1, keepdims=True)
second_input_encoded = tf.keras.layers.Reshape((3,))(item_average)
If I change second_input as from shape(5,) to shape (1,) and get rid of reduce_mean
the code runs just fine.
The error message reads:
/site-packages/tensorflow/python/util/serialization.py", line 69, in get_json_type raise TypeError('Not JSON Serializable:', obj) TypeError: ('Not JSON Serializable:', b"\n\x04Mean\x12\x04Mean\x1a'embedding_1/embedding_lookup/Identity_2\x1a\x16Mean/reduction_indices*\x07\n\x01T\x12\x020\x01*\n\n\x04Tidx\x12\x020\x03*\x0f\n\tkeep_dims\x12\x02(\x01")
解决方案
您需要使用一个Lambda
层来执行自定义操作:
item_average = tf.keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1, keepdims=True))(selected)
Keras 层的输出是 TF 张量,但增加了一些额外的 Keras 特定属性,这些属性是构建模型所需的。当您直接使用tf.reduce_mean
时,它的输出将是一个没有这些附加属性的张量。但是,当您在Lambda
层内执行相同操作时,将添加这些附加属性,因此一切都会正常工作。
推荐阅读
- excel - 使用查找功能在不同的工作表中查找、复制和粘贴
- php - 这个代码片段的漏洞是什么?
- python-2.7 - 无法通过在 require.txt 文件中添加依赖项来下载 nltk 数据文件夹
- json - 如何使用 NiFi 将未格式化的文本文件转换为 JSON
- javascript - 从配置问题读取的多个 FOR var 循环
- scala - 在scala源文件夹下使用“sbt intellij”时得到GATEWAY_TIMEOUT
- batch-file - rd /s /q 在应该的时候不会默默地表现吗?
- regex - 如何在 perl6 语法中匹配十六进制数组
- angular - 带有 Razor 页面的 ASP .Net Core 与 UI 的 Angular
- javascript - 隐藏列时的 CSS Grid 动态大小