#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.mobilenet import MobileNet, preprocess_input
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
get_ipython().run_line_magic('matplotlib', 'inline')
# In[3]:
IMG_WIDTH, IMG_HEIGHT = 224, 224
VALIDATION_DATA_DIR = 'data/val/'
VALIDATION_BATCH_SIZE = 64
validation_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
validation_generator = validation_datagen.flow_from_directory(
VALIDATION_DATA_DIR,
target_size=(IMG_WIDTH, IMG_HEIGHT),
batch_size=VALIDATION_BATCH_SIZE,
shuffle=False,
class_mode='categorical')
# In[4]:
from tensorflow.keras.models import load_model
from tensorflow.keras.utils import CustomObjectScope
from tensorflow.keras.initializers import glorot_uniform
with CustomObjectScope(
{'GlorotUniform': glorot_uniform()}):
model = load_model('data/model.h5')
# In[5]:
# Let's view the names of the files.
filenames = validation_generator.filenames
print(len(filenames))
print(filenames[:10])
# In[6]:
ground_truth = validation_generator.classes
print(ground_truth[:10])
print(len(ground_truth))
# In[7]:
label_to_index = validation_generator.class_indices
print(label_to_index)
# In[8]:
index_to_label = dict((v, k) for k, v in label_to_index.items())
print(index_to_label)
# In[9]:
predictions = model.predict_generator(validation_generator,
steps=None)
print(predictions[:10])
# In[10]:
prediction_index = []
for prediction in predictions:
prediction_index.append(np.argmax(prediction))
def accuracy(predictions, ground_truth):
total = 0
for i, j in zip(predictions, ground_truth):
if i == j:
total += 1
return total * 1.0 / len(predictions)
print(accuracy(prediction_index, ground_truth))
# In[11]:
prediction_table = {}
for index, val in enumerate(predictions):
index_of_highest_probability = np.argmax(val)
value_of_highest_probability = val[index_of_highest_probability]
prediction_table[index] = [
value_of_highest_probability, index_of_highest_probability,
ground_truth[index]
]
assert len(predictions) == len(ground_truth) == len(prediction_table)
# In[12]:
def get_images_with_sorted_probabilities(prediction_table,
get_highest
[视觉工程]如何可视化分析二分类模型效果
最新推荐文章于 2024-05-15 09:58:03 发布