Python Tensorflow使用fit_generator

时间:2019-12-25 07:35:19

标签: python tensorflow

使用fit_generator时,我发现历史记录返回的结果中没有验证集的结果。

valid_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
valid_generator = valid_datagen.flow_from_directory(directory=valid_dir,
                                                target_size=(height, width),
                                                batch_size=batch_size,
                                                shuffle=False,
                                                class_mode="categorical")
model.compile(loss="categorical_crossentropy",
          optimizer="adam", metrics=[tf.keras.metrics.Recall(name="recall")])
history = model.fit_generator(train_generator,
                          steps_per_epoch=train_num,
                          epochs=10,
                          validation_data=valid_generator,
                          validation_steps=valid_num,
                          verbose=1)
'this is result {'loss': [1.1909259875399814], 'recall': [0.42346254]}'

我想知道如何解决?

1 个答案:

答案 0 :(得分:0)

我在您的代码中看不到任何问题。这里使用<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script> <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons'> <link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" /> <div id="app"> <v-app id="inspire"> <v-container> <v-layout row> <v-flex xs6> <v-card> <v-card-text> <v-layout row justify-space-between v-for="option in pricing" :key="option.value" class="my-3"> <span :class="option.class">{{option.text}}</span> <component v-for="(el, i) in selected" :key="i" :is="el.value"></component> <span>{{option.value}}</span> </v-layout> <v-layout row justify-center> <v-flex xs11> <v-btn block> Request </v-btn> </v-flex> </v-layout> </v-card-text> </v-card> <v-flex v-for="el in elements" :key="el.value"> <v-checkbox :value="el" v-model="selected" :label="el.title"> </v-checkbox> </v-flex> </v-flex> </v-layout> </v-container> </v-app> </div>执行了数据论证,您可以看到训练集和验证集的准确性和损失。

fit_generator

输出:

import os, shutil
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dropout, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.losses import binary_crossentropy
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np

from google.colab import drive
drive.mount('/content/drive')

train_dir  = '/content/drive/My Drive/Dogs_Vs_Cats/train'
val_dir = '/content/drive/My Drive/Dogs_Vs_Cats/test'

Max_Pool_Size = (2,2)

model = Sequential([
    Conv2D(input_shape = (150, 150, 3), filters = 32, kernel_size = (3,3), activation = 'relu', 
           padding = 'valid', data_format = 'channels_last'),
    MaxPooling2D(pool_size = Max_Pool_Size),
    Conv2D(filters = 64, kernel_size = (3,3), activation = 'relu', padding = 'valid'),
    MaxPooling2D(pool_size = Max_Pool_Size),
    Conv2D(filters = 128, kernel_size = (3,3), activation = 'relu', padding = 'valid'),
    MaxPooling2D(pool_size = Max_Pool_Size),
    Conv2D(filters = 128, kernel_size = (3,3), activation = 'relu', padding = 'valid'),
    MaxPooling2D(pool_size = Max_Pool_Size),
    Flatten(),
    Dense(units = 512, activation = 'relu'),
    Dense(units = 1, activation = 'sigmoid')
])

model.summary()

model.compile(optimizer = RMSprop(learning_rate = 0.001), loss = 'binary_crossentropy', metrics = [tf.keras.metrics.Recall(name="recall")])

Train_Gen = ImageDataGenerator(1./255)
Val_Gen = ImageDataGenerator(1./255)

Train_Generator = Train_Gen.flow_from_directory(train_dir, target_size = (150,150), batch_size = 20,
                                               class_mode = 'binary')

Val_Generator = Val_Gen.flow_from_directory(val_dir, target_size = (150, 150), class_mode = 'binary',
                                           batch_size = 128)

batch_size = 20
target_size = (150,150)
No_Of_Training_Images = Train_Generator.classes.shape[0]
No_Of_Val_Images = Val_Generator.classes.shape[0]
steps_per_epoch = No_Of_Training_Images/batch_size
validation_steps = No_Of_Val_Images/batch_size

history = model.fit(x = Train_Generator, shuffle=True, epochs = 5, 
          steps_per_epoch = steps_per_epoch,
          validation_data = Val_Generator,
          validation_steps = validation_steps)