Untitled

mail@pastecode.io avatar
unknown
python
a month ago
3.0 kB
26
Indexable
Never
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense, AvgPool2D
import matplotlib.pyplot as plt
from tensorflow.keras.optimizers import Adam
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator

from tensorflow.keras.applications.resnet import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
 
def load_train(path):
    datagen = ImageDataGenerator(validation_split=0.25, rescale=1./255, horizontal_flip = True)
    train_datagen_flow = datagen.flow_from_directory(
        path,
        target_size=(150, 150),
        batch_size=16,
        class_mode='sparse',
        subset='training',
        seed=12345)
    return train_datagen_flow
 
def create_model(input_shape):


    optimizer = Adam(learning_rate = 0.0001)
    backbone = ResNet50(input_shape=(150, 150, 3),
#                     weights='imagenet', 
                    weights='/datasets/keras_models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',
                    include_top=False)

#     # замораживаем ResNet50 без верхушки
#     backbone.trainable = False
    
    model = Sequential()
    model.add(backbone)
    model.add(GlobalAveragePooling2D())
    model.add(Dense(12, activation='softmax')) 
    model.compile(loss='sparse_categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
    
    return model
#     В этом варианте качество 0,9978


#     optimizer = Adam(learning_rate=0.0001)
    
#     # Добавляем сверточный слой перед ResNet50
#     model = Sequential()
#     model.add(Conv2D(64, (3, 3), input_shape=input_shape, activation='relu'))
#     model.add(MaxPooling2D(pool_size=(2, 2)))

#     # Добавляем ResNet50
#     backbone = ResNet50(input_shape=(150, 150, 3),
#                         weights='/datasets/keras_models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5',
#                         include_top=False)
#     model.add(backbone)
    
#     # Продолжаем с вашим текущим кодом
#     model.add(GlobalAveragePooling2D())
#     model.add(Dense(12, activation='softmax')) 
#     model.compile(loss='sparse_categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
    
#     return model сервер не стал выполнять этот вариант
 
def train_model(model, train_data, test_data, batch_size=None, epochs=5,
                steps_per_epoch=None, validation_steps=None):
 
    model.fit(train_data,
              validation_data=test_data,
              batch_size=batch_size, epochs=epochs,
              steps_per_epoch=steps_per_epoch,
              validation_steps=validation_steps,
              verbose=2, shuffle=True)
    
    return model
Leave a Comment