On the main function, the whole can run
Main function part of the code
# Separate data sets Training and validation And the class name # initialization mobilenetv2 Model def get_MOBILENT_model(IMG_SHAPE=(224, 224, 3), class_num=245): # There is no need for normalization in the process of fine-tuning base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') # load mobilenetv2 Model base_model.trainable = False # Freeze the network parameters extracted from the backbone model = tf.keras.models.Sequential([ tf.keras.layers.experimental.preprocessing.Rescaling(1. / 127.5, offset=-1, input_shape=IMG_SHAPE), # normalization , Process the pixel value as -1 To 1 Between base_model, tf.keras.layers.GlobalAveragePooling2D(), # Global average pooling tf.keras.layers.Dense(class_num, activation='softmax'), # Set the last full connection layer , Used for classification ]) model.summary() # Output model information # model training model.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy']) # For compiling models , The optimizer for the specified model is adam Optimizer , The loss function of the model is the cross entropy loss function return model # Back to the model def train_test_split(date_dir,height_size,width_size, batch_size): train_ds = tf.keras.preprocessing.image_dataset_from_directory( # File directory date_dir, # The tag will be encoded as a classification vector label_mode='categorical', # Division ratio validation_split=0.2, # Division ratio # Training set subset="training", seed=123, image_size=(height_size, width_size), # Batch size batch_size=batch_size) val_ds = tf.keras.preprocessing.image_dataset_from_directory( date_dir, label_mode='categorical', # Division ratio validation_split=0.2, # Verification set subset="validation", seed=123, image_size=(height_size, width_size), # Batch size batch_size=batch_size) class_names = train_ds.class_names # Get the class name of the dataset return train_ds, val_ds, class_names # Return to the training set 、 Validation set and class name def test(Date_dir,H5_name): train_ds, val_ds, class_names = train_test_split(Date_dir, 224, 224, 4) model = tf.keras.models.load_model(H5_name) model.summary() # loss, accuracy = model.evaluate(val_ds) # print('test accuracy :', accuracy) pre=model.predict(val_ds) print(len(pre[0]))
But you can't test a single picture
img_path=r"D:\python Rubbish\rubbish data\images\img_4.jpg"model = load_model("D:\python Rubbish\mobilent.h5")model.summary()img=image.load_img(img_path,target_size=(224,224))img_tensor = image.img_to_array(img)img_tensor/=127.5print(' The size of the image is :',img_tensor.shape)# The previous model set the offset img_tensor=img_tensor-1print(img_tensor)img_tensor=np.expand_dims(img_tensor,axis=0)prediction=model.predict(img_tensor)print(prediction)