CoolFace
Apppublic

okeowo1014/intelimageclassifier

sourceHugging Facemitupdated 3y agoView on Hugging Face
0likes
trainer.py101 linesDownload Raw Back to root
1from huggingface_hub import push_to_hub_keras2import numpy as np3import pandas as pd4import os5from sklearn.metrics import classification_report6import seaborn as sn7from sklearn.utils import shuffle8import matplotlib.pyplot as plt9import cv210import tensorflow as tf11from tqdm import tqdm12 13sac = os.getenv('accesstoken')14sn.set(font_scale=1.4)15 16class_names = ['buildings', 'forest', 'glacier', 'mountain', 'sea', 'street']17class_names_label = {class_name: i for i, class_name in enumerate(class_names)}18nb_classes = len(class_names)19print(class_names_label)20IMAGE_SIZE = (150, 150)21 22 23def load_data():24    DIRECTORY = "imgdataset"25    CATEGORY = ["seg_train", "seg_test"]26    output = []27    for category in CATEGORY:28        path = os.path.join(DIRECTORY, category)29        images = []30        labels = []31        print("Loading {}".format(category))32        for folder in os.listdir(path):33            label = class_names_label[folder]34            # Iterate through each image in our folder35            for file in os.listdir(os.path.join(path, folder)):36                # Get the path name of the image37                img_path = os.path.join(os.path.join(path, folder), file)38                # Open and resize the ing39                image = cv2.imread(img_path)40                image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)41                image = cv2.resize(image, IMAGE_SIZE)42                # Append the image and its corresponding Label to the output43                images.append(image)44                labels.append(label)45        # Convert both the images and labels to a numpy array46        images = np.array(images, dtype='float32')47        labels = np.array(labels, dtype='int32')48        output.append((images, labels))49    return output50 51 52(train_images, train_labels), (test_images, test_labels) = load_data()53train_images, train_labels = shuffle(train_images, train_labels, random_state=25)54print("Train: ", train_images.shape, train_labels.shape)55print("Test: ", test_images.shape, test_labels.shape)56#57# model = tf.keras.models.Sequential([58#     tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),59#     tf.keras.layers.MaxPooling2D(2, 2),60#     tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),61#     tf.keras.layers.MaxPooling2D(2, 2),62#     tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),63#     tf.keras.layers.MaxPooling2D(2, 2),64#     tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),65#     tf.keras.layers.MaxPooling2D(2, 2),66#     tf.keras.layers.Flatten(),67#     tf.keras.layers.Dense(512, activation='relu'),68#     tf.keras.layers.Dense(6, activation='softmax')69# ])70model = tf.keras.Sequential([71    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),72    tf.keras.layers.MaxPooling2D(2, 2),73    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),74    tf.keras.layers.MaxPooling2D(2, 2),75    tf.keras.layers.Flatten(),76    tf.keras.layers.Dense(128, activation=tf.nn.relu),77    tf.keras.layers.Dense(6, activation=tf.nn.softmax)78])79 80model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])81model.fit(train_images, train_labels, epochs=6, validation_split=0.2)82 83# Evaluate the model84model.evaluate(test_images, test_labels)85 86# save the model87model.save("model.keras")88# from transformers import push_to_hub_keras89 90# Save the model91# model.save("model.keras")92 93# Upload the model to your Hugging Face space repository94push_to_hub_keras(95    model,96    repo_id="okeowo1014/imgclassifiertraining",97    commit_message="Optional commit message",98    tags=["image-classifier", "some_other_tag"],99    include_optimizer=True, token=sac100)101