简体   繁体   中英

How to get precision and recall, for a keras model?

i want to see precision and recall for my model for a binary image classification but i can find how do to that

Here is my code


x = base_model.output

x = tf.keras.layers.GlobalAveragePooling2D()(x)

x = tf.keras.layers.Dense(1024, activation='relu')(x) 
x = tf.keras.layers.Dense(1024, activation='relu')(x)
x = tf.keras.layers.Dense(512, activation='relu')(x)
preds = tf.keras.layers.Dense(2, activation='softmax')(x)

model = tf.keras.Model(inputs = base_model.input, outputs = preds)

for layer in model.layers[:175]:
  layer.trainable = False 

for layer in model.layers[175:]:
  layer.trainable = True  

model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])

history = model.fit_generator(generator=train_generator,
                              epochs=20,
                              steps_per_epoch=step_size_train,
                              validation_data = test_generator,
                              validation_steps=step_size_test)```

If you want precision and recall during train then you can add precision and recall metrics to the metrics list during model compilation as below

model.compile(optimizer='Adam', loss='categorical_crossentropy',
              metrics=['accuracy', 
                       tf.keras.metrics.Precision(),
                       tf.keras.metrics.Recall()])

Example

input = tf.keras.layers.Input(8)
x = tf.keras.layers.Dense(4, activation='relu')(input) 
output = tf.keras.layers.Dense(2, activation='softmax')(x)

model = tf.keras.Model(inputs = input, outputs = output)
model.compile(optimizer='Adam', loss='categorical_crossentropy',
              metrics=['accuracy', 
                       tf.keras.metrics.Precision(),
                       tf.keras.metrics.Recall()])

X = np.random.randn(100,8)
y = np.random.randint(0,2, (100, 2))

model.fit(X, y, epochs=10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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