Spaces:
Sleeping
Sleeping
Commit
·
4b13ee5
1
Parent(s):
497b66f
Create trainning.py
Browse files- trainning.py +107 -0
trainning.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
from sklearn.utils import shuffle
|
| 6 |
+
from huggingface_hub import push_to_hub_keras
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from sklearn.utils.class_weight import compute_class_weight
|
| 9 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 10 |
+
|
| 11 |
+
# Environment variable for Hugging Face token
|
| 12 |
+
sac = os.getenv('accesstoken')
|
| 13 |
+
|
| 14 |
+
class_names = ['buildings', 'forest', 'glacier']
|
| 15 |
+
class_names_label = {class_name: i for i, class_name in enumerate(class_names)}
|
| 16 |
+
IMAGE_SIZE = (150, 150)
|
| 17 |
+
|
| 18 |
+
def load_data():
|
| 19 |
+
DIRECTORY = "imgdataset"
|
| 20 |
+
CATEGORY = ["seg_train", "seg_test"]
|
| 21 |
+
output = []
|
| 22 |
+
for category in CATEGORY:
|
| 23 |
+
path = os.path.join(DIRECTORY, category)
|
| 24 |
+
images = []
|
| 25 |
+
labels = []
|
| 26 |
+
print("Loading {}".format(category))
|
| 27 |
+
for folder in os.listdir(path):
|
| 28 |
+
label = class_names_label[folder]
|
| 29 |
+
for file in os.listdir(os.path.join(path, folder)):
|
| 30 |
+
img_path = os.path.join(os.path.join(path, folder), file)
|
| 31 |
+
image = cv2.imread(img_path)
|
| 32 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 33 |
+
image = cv2.resize(image, IMAGE_SIZE)
|
| 34 |
+
images.append(image)
|
| 35 |
+
labels.append(label)
|
| 36 |
+
images = np.array(images, dtype='float32')
|
| 37 |
+
labels = np.array(labels, dtype='int32')
|
| 38 |
+
output.append((images, labels))
|
| 39 |
+
return output
|
| 40 |
+
|
| 41 |
+
(train_images, train_labels), (test_images, test_labels) = load_data()
|
| 42 |
+
train_images, train_labels = shuffle(train_images, train_labels, random_state=25)
|
| 43 |
+
|
| 44 |
+
# Split the training set into training and validation sets
|
| 45 |
+
train_images, val_images, train_labels, val_labels = train_test_split(
|
| 46 |
+
train_images, train_labels, test_size=0.2, random_state=42
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Data Augmentation
|
| 50 |
+
datagen = ImageDataGenerator(
|
| 51 |
+
rotation_range=20,
|
| 52 |
+
width_shift_range=0.2,
|
| 53 |
+
height_shift_range=0.2,
|
| 54 |
+
shear_range=0.2,
|
| 55 |
+
zoom_range=0.2,
|
| 56 |
+
horizontal_flip=True,
|
| 57 |
+
fill_mode='nearest'
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# Calculate class weights to handle data imbalance
|
| 61 |
+
class_weights = compute_class_weight('balanced', np.unique(train_labels), train_labels)
|
| 62 |
+
|
| 63 |
+
# Model Architecture
|
| 64 |
+
model = tf.keras.models.Sequential([
|
| 65 |
+
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
|
| 66 |
+
tf.keras.layers.MaxPooling2D(2, 2),
|
| 67 |
+
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
|
| 68 |
+
tf.keras.layers.MaxPooling2D(2, 2),
|
| 69 |
+
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
|
| 70 |
+
tf.keras.layers.MaxPooling2D(2, 2),
|
| 71 |
+
tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
|
| 72 |
+
tf.keras.layers.MaxPooling2D(2, 2),
|
| 73 |
+
tf.keras.layers.Flatten(),
|
| 74 |
+
tf.keras.layers.Dense(512, activation='relu'),
|
| 75 |
+
tf.keras.layers.Dense(3, activation='softmax')
|
| 76 |
+
])
|
| 77 |
+
|
| 78 |
+
# Model Compilation
|
| 79 |
+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
| 80 |
+
|
| 81 |
+
# Model Training with Data Augmentation
|
| 82 |
+
batch_size = 32
|
| 83 |
+
epochs = 10
|
| 84 |
+
|
| 85 |
+
history = model.fit(
|
| 86 |
+
datagen.flow(train_images, train_labels, batch_size=batch_size),
|
| 87 |
+
steps_per_epoch=len(train_images) // batch_size,
|
| 88 |
+
epochs=epochs,
|
| 89 |
+
validation_data=(val_images, val_labels),
|
| 90 |
+
class_weight=dict(enumerate(class_weights))
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Model Evaluation
|
| 94 |
+
model.evaluate(test_images, test_labels)
|
| 95 |
+
|
| 96 |
+
# Save the model
|
| 97 |
+
model.save("model_with_augmentation.keras")
|
| 98 |
+
|
| 99 |
+
# Upload the model to your Hugging Face space repository
|
| 100 |
+
push_to_hub_keras(
|
| 101 |
+
model,
|
| 102 |
+
repo_id="okeowo1014/imageaugmentationa",
|
| 103 |
+
commit_message="Model with data augmentation and class weights",
|
| 104 |
+
tags=["image-classifier", "data-augmentation", "class-weights"],
|
| 105 |
+
include_optimizer=True,
|
| 106 |
+
token=sac
|
| 107 |
+
)
|