Upload Dog_Training.py
Browse files- Dog_Training.py +61 -0
Dog_Training.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
from sklearn.preprocessing import LabelEncoder
|
5 |
+
from keras.models import Sequential
|
6 |
+
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
|
7 |
+
import pickle
|
8 |
+
|
9 |
+
|
10 |
+
def load_images_from_folder(folder, img_size=(128, 128)):
|
11 |
+
images = []
|
12 |
+
labels = []
|
13 |
+
for breed in os.listdir(folder):
|
14 |
+
breed_path = os.path.join(folder, breed)
|
15 |
+
if os.path.isdir(breed_path):
|
16 |
+
for img in os.listdir(breed_path):
|
17 |
+
img_path = os.path.join(breed_path, img)
|
18 |
+
try:
|
19 |
+
image = Image.open(img_path).convert('RGB')
|
20 |
+
image = image.resize(img_size)
|
21 |
+
images.append(np.array(image))
|
22 |
+
labels.append(breed)
|
23 |
+
except Exception as e:
|
24 |
+
print(f"Error loading image {img_path}: {e}")
|
25 |
+
return np.array(images), np.array(labels)
|
26 |
+
|
27 |
+
|
28 |
+
# Lade und verarbeite die Trainings- und Testdaten
|
29 |
+
train_images, train_labels = load_images_from_folder('DataDogs')
|
30 |
+
test_images, test_labels = load_images_from_folder('DataDogs')
|
31 |
+
|
32 |
+
# Label-Encoding für die Labels
|
33 |
+
label_encoder = LabelEncoder()
|
34 |
+
train_labels_encoded = label_encoder.fit_transform(train_labels)
|
35 |
+
test_labels_encoded = label_encoder.transform(test_labels)
|
36 |
+
|
37 |
+
# Definiere das CNN-Modell
|
38 |
+
model = Sequential([
|
39 |
+
Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)),
|
40 |
+
MaxPooling2D((2, 2)),
|
41 |
+
Conv2D(64, (3, 3), activation='relu'),
|
42 |
+
MaxPooling2D((2, 2)),
|
43 |
+
Conv2D(128, (3, 3), activation='relu'),
|
44 |
+
MaxPooling2D((2, 2)),
|
45 |
+
Flatten(),
|
46 |
+
Dense(512, activation='relu'),
|
47 |
+
Dropout(0.5),
|
48 |
+
Dense(len(label_encoder.classes_), activation='softmax')
|
49 |
+
])
|
50 |
+
|
51 |
+
# Kompiliere das Modell
|
52 |
+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
53 |
+
|
54 |
+
# Trainiere das Modell
|
55 |
+
model.fit(train_images, train_labels_encoded, epochs=10, validation_data=(test_images, test_labels_encoded))
|
56 |
+
|
57 |
+
# Speichere das trainierte Modell und den LabelEncoder
|
58 |
+
model.save('dog_breed_classifier.h5')
|
59 |
+
|
60 |
+
with open('label_encoder.pkl', 'wb') as f:
|
61 |
+
pickle.dump(label_encoder, f)
|