1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
""" 训练文件 """
import glob import os
import tensorflow as tf from keras import layers from tensorflow import keras
import numpy as np
print(tf.__version__) gpus = tf.config.list_physical_devices(device_type='GPU') if len(gpus) > 0: tf.config.experimental.set_memory_growth(gpus[0], True)
Image_dir = 'image' img_height = 180 img_width = 180 batch_size = 32 epochs = 15 model_path = "model.h5"
if __name__ == '__main__': train_ds = tf.keras.utils.image_dataset_from_directory( Image_dir + "/train", validation_split=0.2, subset="training", seed=123, image_size=(img_height, img_width), batch_size=batch_size) val_ds = tf.keras.utils.image_dataset_from_directory( Image_dir + "/test", validation_split=0.2, subset="validation", seed=123, image_size=(img_height, img_width), batch_size=batch_size) class_names = train_ds.class_names print(class_names) AUTOTUNE = tf.data.AUTOTUNE train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE) val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
normalization_layer = layers.Rescaling(1. / 255)
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y)) image_batch, labels_batch = next(iter(normalized_ds)) first_image = image_batch[0] print(np.min(first_image), np.max(first_image)) num_classes = len(class_names) data_augmentation = keras.Sequential( [ keras.layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)), keras.layers.RandomRotation(0.1), keras.layers.RandomZoom(0.1), ] ) model = None if os.path.exists(model_path): model = tf.keras.models.load_model(model_path) model.summary() else: model = keras.Sequential([ data_augmentation, keras.layers.Rescaling(1. / 255), keras.layers.Conv2D(16, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(), keras.layers.Conv2D(32, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(), keras.layers.Conv2D(64, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(), keras.layers.Conv2D(128, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(), keras.layers.Dropout(0.2), keras.layers.Flatten(), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(num_classes) ]) try: model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) history = model.fit( train_ds, validation_data=val_ds, epochs=epochs ) except KeyboardInterrupt: pass
print('\n\n\n') test_loss, test_acc = model.evaluate(val_ds, verbose=2) print('\nTest accuracy:', test_acc)
test_loss, test_acc = model.evaluate(train_ds, verbose=2) print('\nTest accuracy:', test_acc)
model.save(model_path)
exit()
|