【问题标题】:TypeError: ('Not JSON Serializable:', <tf.Tensor: shape=(), dtype=float32, numpy=1e-04>)TypeError: ('Not JSON Serializable:', <tf.Tensor: shape=(), dtype=float32, numpy=1e-04>)
【发布时间】:2021-10-17 12:30:14
【问题描述】:

我正在尝试在 keras 的简单 DNN 架构中为来自 mnist 数据集的 10000 张图像实现一个简单的比率度量,但不幸的是,我在尝试保存模型时在第 51 行遇到了这个错误。我看了到处都是,但没有一个答案是有帮助的。这是我的代码

import numpy as np 
import tensorflow as tf 
from tensorflow.keras.layers import Dense
from tensorflow.keras.datasets import mnist 
from tensorflow.keras.metrics import Metric
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical 
from tensorflow.keras.models import Sequential, load_model

(X_train, y_train), (X_test, y_test) = mnist.load_data() 
X_train, X_test = X_train[:10000], X_test[:1000]
y_train, y_test = y_train[:10000], y_test[:1000]
X_train, X_test = X_train.reshape(-1, 28*28) / 255.0, X_test.reshape(-1, 28*28) / 255.0
y_train, y_test = to_categorical(y_train, 10), to_categorical(y_test, 10)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

#Implement a simple ratio metric(y_true over y_pred)
class Ratio(Metric):
    def __init__(self, **kwargs): 
         super().__init__(**kwargs)
         #add_weight() method creates the variables needed to keep track of
         self.mean_ratio = self.add_weight("mean_ratio", initializer="zeros")

    #Updater
    def update_state(self, y_true, y_pred, sample_weight=None):
        y_true = tf.add(y_true, tf.constant(1, dtype=tf.float32))
        y_pred = tf.add(y_pred, tf.constant(1, dtype=tf.float32))
        ratio = tf.divide(y_true, y_pred)
        ratio = tf.reduce_mean(ratio)
        self.mean_ratio.assign(ratio)

    def result(self):
        return self.mean_ratio
    
    #Reset the variables
    def reset_state(self):
        self.mean_ratio.assign(0)

    def get_config(self):
        base_config = super().get_config()
        return {**base_config}

dnn = Sequential()
dnn.add(Dense(128, input_shape=(784, ), activation="relu"))
dnn.add(Dense(64, activation="relu"))
dnn.add(Dense(32, activation="relu"))
dnn.add(Dense(10, activation="softmax"))
dnn.compile(loss="categorical_crossentropy", optimizer=SGD(learning_rate=0.01), metrics=[Ratio()])
dnn.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test, y_test))
dnn.save("custom_component_model.h5") #Error line
dnn = load_model("custom_component_model.h5", custom_objects={"Ratio":Ratio})
dnn.evaluate(X_test, y_test, batch_size=32)

【问题讨论】:

  • 如果我正确阅读了错误信息,您所拥有的只是一个数字。像这样转换成 JSON 应该是微不足道的,但它可能不是一个有用或正确的张量。也许您正在使用的库在极端情况下存在错误,或者他们认为他们不需要支持无用的结构。
  • 我运行了你的代码,它运行完美,我相信这是一个版本问题。我的 TensorFlow 版本 - 2.5.0 。另外,只是说您的ratio 指标高于1,因此其中可能存在错误。我没有检查它的行为,所以它可能是理想的,但仍然只是说。

标签: python numpy tensorflow keras deep-learning


【解决方案1】:

刚刚意识到我有一个名为 eps 的变量,旨在通过一些更改来帮助避免在我之前的代码中进行零除,并发现错误 1e-04 中的给定值与 eps 的值和因为变量保存在 google colab 的缓存中,所以代码遇到了错误。我在另一个笔记本上运行了代码,正如 cmets 中提到的其他人一样,代码工作得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 2021-09-13
    • 2020-11-16
    • 2019-06-15
    • 1970-01-01
    • 2021-09-19
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多