我对Tensorflow完全陌生,我正在尝试组建一支军队,这是我的第一个CNN。
我最及时的问题是我如何才能获得此预测结果的准确性;我正在使用此功能:
cnn.predict (x)
我一直在研究,但未能获得结果,您能指导我吗?
为了更好的参考,这是我的代码:
我的课程“分类”的代码是:
img_path = './images/acta37.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = cnn.predict_proba(x)
result = features[0]
respuesta = np.argmax(result)
print(respuesta, result)
resultado [0.9960091 0.00399088]
用于创建模型的代码如下:
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import os
from tensorflow.python.keras import backend as K
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
K.clear_session()
data_entrenamiento = './data/train'
data_validacion = './data/validation'
epocas=20
longitud, altura = 224, 224
batch_size = 32
pasos = 10
validation_steps = 3
filtrosConv1 = 32
filtrosConv2 = 64
tamano_filtro1 = (3, 3)
tamano_filtro2 = (2, 2)
tamano_pool = (2, 2)
clases = 2
lr = 0.0004
IMG_SIZE = 224
IMG_SHAPE = (longitud, altura, 3)
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy')>0.959):
print("¡Alcanzó una precisión del 99% y canceló el entrenamiento!")
self.model.stop_training = True
def modelo():
vgg = tf.keras.applications.VGG16()
vgg.summary()
cnn=Sequential()
for capa in vgg.layers:
cnn.add(capa)
cnn.pop()
for layer in cnn.layers:
layer.trainable=False
cnn.add(Dense(2,activation='softmax'))
cnn.summary()
return cnn
def modelo():
vgg=tf.keras.applications.VGG16()
cnn=Sequential()
for capa in vgg.layers:
cnn.add(capa)
cnn.pop()
for layer in cnn.layers:
layer.trainable=False
cnn.add(Dense(2,activation='softmax'))
cnn.summary()
return cnn
entrenamiento_datagen = ImageDataGenerator(
rescale=1. / 255)
#shear_range=0.2,
#zoom_range=0.2,
#horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1. / 255)
entrenamiento_generador = entrenamiento_datagen.flow_from_directory(
data_entrenamiento,
target_size=(altura, longitud),
batch_size=batch_size,
class_mode='categorical')
validacion_generador = test_datagen.flow_from_directory(
data_validacion,
target_size=(altura, longitud),
batch_size=batch_size,
class_mode='categorical')
cnn=modelo()
cnn.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
callbacks = myCallback()
history = cnn.fit_generator(
entrenamiento_generador,
steps_per_epoch=pasos,
epochs=epocas,
validation_data=validacion_generador,
validation_steps=validation_steps,
callbacks=[callbacks])
print('classes model: ', entrenamiento_generador.class_indices)
target_dir = './modelo/'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
cnn.save('./modelo/model.h5')
cnn.save_weights('./modelo/model_weights.h5')
我先感谢您对模型的构建提出任何建议,如果我可以以某种方式进行改进或修改,目的是对文档进行分类,到目前为止,使用这种配置,我可以获得满意的结果。