keras TypeError:“历史记录”对象不可调用

2nc8po8w  于 2023-01-30  发布在  其他
关注(0)|答案(2)|浏览(147)

我正在尝试实现saliency_map。我使用的是DenseNet121,并且我适合model。cose代码片段:

for train_index, val_index in skf.split(X_train, y_train):
    X_train_fold, X_val_fold = X_train[train_index], X_train[val_index]
    y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]
    i = i+1;
    print("Fold:",i)
    DenseNet121 = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[ es_callback])

saliency_map的代码片段:

# Function to generate saliency maps
def generate_saliency_map(model, X, y):
    # Convert numpy arrays to TensorFlow tensors
    X = tf.convert_to_tensor(X)
    y = tf.convert_to_tensor(y)
    X = tf.expand_dims(X, axis=0)
    with tf.GradientTape() as tape:
        tape.watch(X)
        output_tensor = model(X)
        output_class = tf.math.argmax(output_tensor, axis=-1)
        one_hot = tf.one_hot(output_class, depth=4)
        loss = tf.reduce_sum(output_tensor * one_hot, axis=-1)
    grads = tape.gradient(loss, X)
    saliency_map = tf.reduce_max(tf.abs(grads), axis=-1)
    return saliency_map
# Generate saliency maps for a few test images
for i in range(5):
    # print(X_test[i].shape)
    saliency_map = generate_saliency_map(DenseNet121, X_test[i], y_test[i])
    plt.imshow(saliency_map, cmap='gray')
    plt.show()

错误:TypeError: 'History' object is not callable
我附上一张图片,以便更好地理解错误。

ma8fv8wu

ma8fv8wu1#

这一行将用History对象覆盖以前的Keras模型。

DenseNet121 = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[ es_callback])

如果你想存储训练的历史记录,你可以声明一个新变量

history = model.fit(datagen.flow(X_train_fold, y_train_fold, batch_size=32), epochs=10, verbose=1,validation_data=(X_val_fold,y_val_fold) ,callbacks=[es_callback])
pdtvr36n

pdtvr36n2#

你需要使用model作为参数,而不是generate_saliency_map中的DenseNet121,因为DenseNet121保存的是历史对象而不是模型。

# Generate saliency maps for a few test images
for i in range(5):
    # print(X_test[i].shape)
    saliency_map = generate_saliency_map(model, X_test[i], y_test[i])
    plt.imshow(saliency_map, cmap='gray')
    plt.show()

相关问题