我有一個奇怪的錯誤,我似乎無法除錯
#import all the necessary libraries and be specific so as to avoid wasting time importing everything
import sys
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.applications import VGG16
from tensorflow.keras import optimizers
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import sklearn.metrics as metrics
from sklearn.metrics import confusion_matrix
import seaborn as sns
model_type = 'vgg16'
# Loading the VGG Model
vgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(200,200,3))
vgg_model.trainable = False
model = tf.keras.Sequential([vgg_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(512, activation= "relu"),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(16, activation="softmax")
])
datagen = ImageDataGenerator(featurewise_center=True)
#retrieve the trian data using imagedatagen
train = datagen.flow_from_directory('/content/16_flowers/Train/',
class_mode='categorical', color_mode= 'rgb',batch_size=64, target_size=(200, 200))
test = datagen.flow_from_directory('/content/16_flowers/Test/',
class_mode='categorical', color_mode= 'rgb',batch_size=10, target_size=(200, 200))
base_learning_rate = 0.00005
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),loss = tf.keras.metrics.categorical_crossentropy,metrics=['accuracy'])
history = model.fit(train,epochs = 100 , validation_data = test)
#summarise_diagnostics(history)
model.save("vgg16CNN.model")
_, acc = model.evaluate(test, steps=len(test), verbose=0)
print('> %.3f' % (acc * 100.0))
plot_cm(model)
我的資料集是一個包含 16 朵花的資料集,訓練資料是每類 70 張影像,我的驗證/測驗資料是每類 10 張影像。當我運行代碼時,我得到大約 99% 的訓練準確度和 76% 的驗證準確度,0.07 的訓練損失和 0.7 的驗證損失。
但是當我使用生成的模型并使用它對測驗資料集進行預測,然后將其預測與真實類別進行比較時,我的準確率約為 6.25%,誰能告訴我為什么會這樣?
以下是我進行預測并重新運行這些預測的準確性的代碼
datagen = ImageDataGenerator(featurewise_center=True)
test = datagen.flow_from_directory('/content/16_flowers/Test/',
class_mode='categorical', color_mode= 'rgb',batch_size=10, target_size=(200, 200))
predictions = model.predict(test)
predicted_classes = np.argmax(predictions, axis=1)
true_classes = test.classes
count = 0
for i in range(len(predicted_classes)):
print(true_classes[i],predicted_classes[i])
if true_classes[i] == predicted_classes[i]:
count =1
print(count/160*100)
uj5u.com熱心網友回復:
對于 flow_from_directory 中的測驗,設定 shuffle=False 以保留相對于檔案的預測順序。然后使用
classes=list(train_gen.class_indices.keys())
count=0
predictions = model.predict(test)
for i,p in enumerate(predictions):
index=np.argmax(p)
predicted_class=classes[index]
true_index=test.labels[i]
true_class= classes[true_index]
print('True class is ', true_class, . ' Predicted class is ', predicted class)
if index == true_index:
count =1
accuracy = count * 100/len(predictions)
print('Accuracy om Test set is ', accuracy)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/375442.html
下一篇:tf.concat不同長度的張量
