That is my first writing. On this preliminary piece, I want to doc the testing steps I’ve undertaken for this assortment of flower photographs in my analysis undertaking on picture classification utilizing Convolutional Neural Community (CNN) and the Xception mannequin from Keras.
This undertaking includes a group of picture knowledge with 5 folders representing several types of flowers to be labeled, specifically:
1. Lily
2. Lotus
3. Orchid
4. Sunflower
5. Tulip
This dataset might be obtained from the Kaggle platform, with every folder containing 1000 photographs.
The undertaking makes use of the picture classification technique of Convolutional Neural Community (CNN) together with assistance from Dropout layers and the Xception mannequin from Keras.
Convolutional Neural Community (CNN) is a sort of neural community structure particularly designed for picture knowledge processing. CNN incorporates convolutional layers, pooling layers, and classification layers to extract visible options from photographs and predict correct class labels.
Dropout layers are employed to cut back overfitting within the mannequin.
Xception is among the superior CNN structure fashions. Xception combines the elemental idea of convolution with a depthwise separable convolution method, enabling higher characteristic recognition and extraction from photographs. You’ll be able to refer here for proof of why Xception is taken into account a complicated CNN structure mannequin.
The mixture of using Convolutional Neural Community (CNN), Dropout layers, and the Xception mannequin supplies efficient capabilities for classifying flower photographs with excessive accuracy, good generalization, and computational effectivity.
Utilizing Google Colab for the Device and Python Language for Machine Studying Improvement.
Google Colab supplies a robust platform for machine studying improvement, providing a spread of advantages and comfort. Mixed with the Python programming language, it facilitates seamless and environment friendly machine studying experimentation and improvement.
Present authentication for accessing Google Drive to entry the folder containing the picture dataset.
from google.colab import drive
drive.mount('/content material/drive')
Initialize the dataset listing.
import osdataset_path = '/content material/drive/MyDrive/Kumpulan Information/Kumpulan Information Klasifikasi Gambar 5 Jenis Bunga/flower_images'
Detect the out there picture codecs throughout the flower picture dataset folder.
def scan_image_formats(dataset_path):
image_formats = set()for foldername in os.listdir(dataset_path):
folder_path = os.path.be a part of(dataset_path, foldername)
if os.path.isdir(folder_path):
for filename in os.listdir(folder_path):
image_path = os.path.be a part of(folder_path, filename)
_, ext = os.path.splitext(filename)
if ext.decrease() in ['.jpg', '.jpeg', '.png', '.gif']:
image_formats.add(ext.decrease())
return image_formats
image_formats = scan_image_formats(dataset_path)
print("Format gambar yang ditemukan:")
for image_format in image_formats:
print(image_format)
To divide the picture dataset into three subsets, comply with the rules under:
- Coaching Subset: 70% of the picture dataset
- Validation Subset: 20% of the picture dataset
- Check Subset: 10% of the picture dataset
The principle precept behind this division is to make sure that the coaching subset has a sufficiently giant portion of the dataset to successfully prepare the mannequin whereas decreasing the danger of overfitting. The validation and check subsets also needs to include a considerable variety of samples to allow correct analysis.
import random
import shutiltrain_path = '/content material/drive/MyDrive/Colab Notebooks/Pembagian/Klasifikasi Gambar 5 Jenis Bunga/prepare'
val_path = '/content material/drive/MyDrive/Colab Notebooks/Pembagian/Klasifikasi Gambar 5 Jenis Bunga/val'
test_path = '/content material/drive/MyDrive/Colab Notebooks/Pembagian/Klasifikasi Gambar 5 Jenis Bunga/check'
# Cek apakah folder subset sudah ada
if not os.path.exists(train_path) and never os.path.exists(val_path) and never os.path.exists(test_path):
os.makedirs(train_path)
os.makedirs(val_path)
os.makedirs(test_path)
folders = os.listdir(dataset_path)
for folder in folders:
folder_path = os.path.be a part of(dataset_path, folder)
if os.path.isdir(folder_path):
# Membuat path folder baru di subset pelatihan
train_folder = os.path.be a part of(train_path, folder)
os.makedirs(train_folder, exist_ok=True)
# Membuat path folder baru di subset validasi
val_folder = os.path.be a part of(val_path, folder)
os.makedirs(val_folder, exist_ok=True)
# Membuat path folder baru di subset pengujian
test_folder = os.path.be a part of(test_path, folder)
os.makedirs(test_folder, exist_ok=True)
# Mendapatkan daftar file gambar di dalam folder
photographs = os.listdir(folder_path)
random.shuffle(photographs) # Mengacak urutan file gambar
# Menghitung jumlah gambar untuk masing-masing subset
num_images = len(photographs)
train_size = int(0.7 * num_images) # 70% untuk pelatihan
val_size = int(0.2 * num_images) # 20% untuk validasi
test_size = num_images - train_size - val_size # Sisa untuk pengujian
# Memindahkan file gambar ke masing-masing subset
for i, picture in enumerate(photographs):
src = os.path.be a part of(folder_path, picture)
if i < train_size:
dest = os.path.be a part of(train_folder, picture)
elif i < train_size + val_size:
dest = os.path.be a part of(val_folder, picture)
else:
dest = os.path.be a part of(test_folder, picture)
shutil.copy(src, dest)
else:
print("Folder subset sudah ada. Tidak perlu membagi dataset lagi.")
Viewing the Subset Break up Outcomes.
from PIL import Picture
import matplotlib.pyplot as pltsubset_paths = [train_path, val_path, test_path]
subset_names = ['Train', 'Validation', 'Test']
# Loop melalui setiap subset
for subset_path, subset_name in zip(subset_paths, subset_names):
print(f'{subset_name} subset:')
folders = os.listdir(subset_path)
# Loop melalui setiap folder dalam subset
for folder in folders:
folder_path = os.path.be a part of(subset_path, folder)
if os.path.isdir(folder_path):
print(f'Folder: {folder}')
photographs = os.listdir(folder_path)
print(f'Jumlah gambar: {len(photographs)}')
# Tampilkan informasi dan sampel 5 gambar
fig, axes = plt.subplots(1, 5, figsize=(15, 3))
for i in vary(min(5, len(photographs))):
image_path = os.path.be a part of(folder_path, photographs[i])
picture = Picture.open(image_path)
width, top = picture.measurement
print(f'Gambar {i+1}: {photographs[i]}, Ukuran: {width} x {top} piksel')
# Tampilkan gambar dalam mode grafik
axes[i].imshow(picture)
axes[i].axis('off')
axes[i].set_title(f'Gambar {i+1}')
plt.present()
print('n')
Detect the smallest and largest size and width dimensions in a picture dataset.
subset_paths = {'prepare': train_path, 'val': val_path, 'check': test_path}min_width, min_height = float('inf'), float('inf') # Ukuran piksel terkecil
max_width, max_height = float('-inf'), float('-inf') # Ukuran piksel terbesar
min_size_folder = "" # Lokasi folder subset dengan ukuran piksel terkecil
max_size_folder = "" # Lokasi folder subset dengan ukuran piksel terbesar
# Loop melalui setiap subset
for subset, subset_path in subset_paths.objects():
# Loop melalui setiap gambar dalam subset
for root, dirs, recordsdata in os.stroll(subset_path):
for file in recordsdata:
file_path = os.path.be a part of(root, file)
picture = Picture.open(file_path)
width, top = picture.measurement
if width < min_width or top < min_height:
min_width, min_height = width, top
min_size_folder = subset
if width > max_width or top > max_height:
max_width, max_height = width, top
max_size_folder = subset
print(f"Ukuran piksel gambar terkecil: {min_width} x {min_height} pixel, Lokasi folder subset: {min_size_folder}")
print(f"Ukuran piksel gambar terbesar: {max_width} x {max_height} pixel, Lokasi folder subset: {max_size_folder}")
To carry out pre-processing and resize all photographs within the dataset to a measurement of 224 x 224 pixels.
import cv2
import numpy as np# Fungsi untuk melakukan resizing gambar
def resize_image(image_path, target_size):
picture = cv2.imread(image_path)
resized_image = cv2.resize(picture, target_size)
return resized_image
# Path direktori hasil pra-pemrosesan gambar
preprocessed_path = '/content material/drive/MyDrive/Colab Notebooks/Pra-Pemrosesan/Klasifikasi Gambar 5 Jenis Bunga'
target_size = (224, 224)
# Fungsi untuk melakukan pra-pemrosesan pada direktori
def preprocess_directory(input_path, output_path):
# Mengecek apakah direktori pra-pemrosesan sudah ada
if os.path.exists(output_path):
return
# Membuat folder output jika belum ada
os.makedirs(output_path, exist_ok=True)
# Mendapatkan daftar folder dalam direktori enter
folders = os.listdir(input_path)
# Melakukan pra-pemrosesan pada setiap folder
for folder in folders:
folder_path = os.path.be a part of(input_path, folder)
output_folder_path = os.path.be a part of(output_path, folder)
os.makedirs(output_folder_path, exist_ok=True)
# Mendapatkan daftar file gambar dalam folder
image_files = os.listdir(folder_path)
# Melakukan pra-pemrosesan pada setiap gambar
for file in image_files:
image_path = os.path.be a part of(folder_path, file)
resized_image = resize_image(image_path, target_size)
# Menyimpan hasil pra-pemrosesan ke folder output
output_file = os.path.be a part of(output_folder_path, file)
cv2.imwrite(output_file, resized_image)
# Melakukan pra-pemrosesan pada direktori prepare
train_output_path = os.path.be a part of(preprocessed_path, 'prepare')
preprocess_directory(train_path, train_output_path)
# Melakukan pra-pemrosesan pada direktori val
val_output_path = os.path.be a part of(preprocessed_path, 'val')
preprocess_directory(val_path, val_output_path)
# Melakukan pra-pemrosesan pada direktori check
test_output_path = os.path.be a part of(preprocessed_path, 'check')
preprocess_directory(test_path, test_output_path)
# Menghitung jumlah gambar dalam setiap subset
train_count = sum([len(files) for _, _, files in os.walk(train_output_path)])
val_count = sum([len(files) for _, _, files in os.walk(val_output_path)])
test_count = sum([len(files) for _, _, files in os.walk(test_output_path)])
# Menampilkan pesan "Tidak perlu pra-pemrosesan lagi"
if os.path.exists(train_path) and os.path.exists(val_path) and os.path.exists(test_path):
print("Tidak perlu pra-pemrosesan lagi")
print("------------------------------")
# Menampilkan jumlah gambar dalam setiap subset
print(f"Jumlah gambar dalam subset prepare: {train_count}")
print(f"Jumlah gambar dalam subset val: {val_count}")
print(f"Jumlah gambar dalam subset check: {test_count}")
Displaying the Pre-processing Outcomes.
import random# Fungsi untuk melihat hasil prapemrosesan gambar
def show_preprocessed_images(listing, num_images=5):
# Mendapatkan daftar folder subset dalam direktori
subsets = os.listdir(listing)
# Melihat hasil prapemrosesan pada setiap folder subset
for subset in subsets:
subset_path = os.path.be a part of(listing, subset)
if not os.path.isdir(subset_path):
proceed
# Mendapatkan daftar folder jenis bunga dalam subset
flower_folders = os.listdir(subset_path)
# Memilih folder jenis bunga secara acak
random_flower_folders = random.pattern(flower_folders, num_images)
# Melihat hasil prapemrosesan pada setiap folder jenis bunga
for flower_folder in random_flower_folders:
flower_folder_path = os.path.be a part of(subset_path, flower_folder)
if not os.path.isdir(flower_folder_path):
proceed
# Mendapatkan daftar file gambar dalam folder jenis bunga
image_files = os.listdir(flower_folder_path)
# Memilih gambar secara acak
random_images = random.pattern(image_files, 1)
# Menampilkan informasi folder subset dan folder jenis bunga
print(f"Folder subset: {subset}")
print(f"Nama folder jenis bunga: {flower_folder}")
print("------------------------------")
# Menampilkan gambar dan informasi
for image_file in random_images:
image_path = os.path.be a part of(flower_folder_path, image_file)
picture = cv2.imread(image_path)
if picture isn't None:
# Menampilkan gambar
plt.imshow(cv2.cvtColor(picture, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.present()
# Menampilkan informasi gambar
print(f"Informasi gambar: {image_file}")
print(f"Ukuran gambar: {picture.form[1]} x {picture.form[0]} piksel")
print("______________________________")
else:
print(f"Gagal membaca gambar: {image_file}")
print("------------------------------")
# Memanggil fungsi untuk melihat hasil prapemrosesan
show_preprocessed_images(preprocessed_path)
Label subsets and flower varieties
To coach a mannequin, you should label the subsets with the corresponding flower varieties.
def get_label_from_folder(folder_name):
# Misalnya, jika folder_name adalah "sunflower", return 0
# Jika folder_name adalah "rose", return 1
# Dan seterusnya...
if folder_name == "Lilly":
return 0
elif folder_name == "Lotus":
return 1
elif folder_name == "Orchid":
return 2
elif folder_name == "Sunflower":
return 3
elif folder_name == "Tulip":
return 4
else:
return Nonedef get_labels(input_path):
# Mendapatkan daftar folder dalam direktori enter
folders = os.listdir(input_path)
labels = []
# Melakukan iterasi pada setiap folder
for folder in folders:
folder_path = os.path.be a part of(input_path, folder)
# Mendapatkan daftar file gambar dalam folder
image_files = os.listdir(folder_path)
# Mendapatkan label berdasarkan nama folder
label = get_label_from_folder(folder)
# Memastikan label legitimate
if label isn't None:
# Menambahkan label ke dalam record labels
labels.lengthen([label] * len(image_files))
return labels
train_labels = get_labels(train_output_path)
val_labels = get_labels(val_output_path)
test_labels = get_labels(test_output_path)
# Menampilkan pesan bahwa semua subset telah dilabeli
print("Semua subset telah dilabeli.")
Constructing the Neural Community Mannequin Structure
To assemble a neural community mannequin structure that comes with not solely CNN layers but additionally Dropout layers and the Xception mannequin, you should use a mix of various layers from the Keras library in Python.
import tensorflow.keras
from tensorflow.keras.fashions import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.functions import Xception# Membangun arsitektur mannequin CNN
mannequin = Sequential()
# Menambahkan mannequin Xception sebagai lapisan awal
base_model = Xception(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
mannequin.add(base_model)
# Menambahkan lapisan pooling
mannequin.add(MaxPooling2D((2, 2)))
# Meratakan output dari lapisan konvolusi sebelumnya menjadi vektor
mannequin.add(Flatten())
# Menambahkan lapisan totally related pertama
mannequin.add(Dense(64, activation='relu'))
# Menambahkan layer dropout
mannequin.add(Dropout(0.5)) # Menentukan tingkat dropout (misalnya, 50%)
# Menambahkan lapisan totally related kedua
mannequin.add(Dense(5, activation='softmax'))
# Menampilkan ringkasan arsitektur mannequin
mannequin.abstract()
The output of the mannequin:
The output of the mannequin abstract supplies a concise abstract of the details about the mannequin structure.
The output you offered is a illustration of the neural community mannequin structure utilized in a undertaking. It supplies details about the layers concerned within the mannequin and the output form of every layer, in addition to the variety of parameters utilized by every layer.
Right here’s an evidence for every layer within the given output:
xception (Purposeful)
: This means that the mannequin makes use of the Xception structure as the primary layer within the mannequin. Xception is a CNN mannequin developed by François Chollet that’s based mostly on the Inception structure.
- Output Form: (None, 7, 7, 2048) signifies that the output from the Xception layer has dimensions (None, 7, 7, 2048), the place “None” signifies that the batch dimension can differ. The spatial dimensions of 7×7 point out the spatial measurement of the generated options, and 2048 signifies the variety of characteristic filters generated by this layer.
- Param #: 20,861,480 signifies the variety of parameters utilized by the Xception layer.
max_pooling2d (MaxPooling2D)
: It is a MaxPooling2D layer following the Xception layer. This layer is used to cut back the spatial dimensions of the options generated by the earlier layer.
- Output Form: (None, 3, 3, 2048) signifies that the output from the MaxPooling2D layer has dimensions (None, 3, 3, 2048).
flatten (Flatten)
: It is a Flatten layer used to reshape the multidimensional tensor right into a one-dimensional vector earlier than passing it to the following layer.
- Output Form: (None, 18432) signifies that the output from the Flatten layer has dimensions (None, 18432).
dense (Dense)
: It is a Dense (totally related) layer with 64 neuron models.
- Output Form: (None, 64) signifies that the output from the Dense layer has dimensions (None, 64).
- Param #: 1,179,712 signifies the variety of parameters utilized by the Dense layer.
dropout (Dropout)
: It is a Dropout layer used to randomly deactivate a portion of the neuron models within the earlier layer to stop overfitting.
- Output Form: (None, 64) signifies that the output from the Dropout layer has dimensions (None, 64).
dense_1 (Dense)
: That is the second Dense layer with 5 neuron models, which serves because the output layer of the mannequin.
- Output Form: (None, 5) signifies that the output from the second Dense layer has dimensions (None, 5).
- Param #: 325 signifies the variety of parameters utilized by the second Dense layer.
Whole params: 22,041,517 is the whole variety of parameters within the mannequin. Out of the whole variety of parameters, 21,986,989 parameters are trainable, which implies these parameters might be up to date and adjusted throughout the mannequin coaching course of. In the meantime, 54,528 parameters are non-trainable, which can be associated to pre-initialized inner weights.
Initialize train_images
and val_images
The code reads and saves photographs from the `prepare` and `val` directories into the `train_images` and `val_images` lists, respectively. This lets you entry and make the most of the picture knowledge for additional processing or coaching your machine studying fashions.
import numpy as np
import os# Mendefinisikan record train_images
train_images = []
# Melakukan iterasi pada setiap folder di direktori prepare
for folder in os.listdir(train_output_path):
folder_path = os.path.be a part of(train_output_path, folder)
for file in os.listdir(folder_path):
image_path = os.path.be a part of(folder_path, file)
picture = cv2.imread(image_path)
train_images.append(picture)
# Mendefinisikan record val_images
val_images = []
# Melakukan iterasi pada setiap folder di direktori val
for folder in os.listdir(val_output_path):
folder_path = os.path.be a part of(val_output_path, folder)
for file in os.listdir(folder_path):
image_path = os.path.be a part of(folder_path, file)
picture = cv2.imread(image_path)
val_images.append(picture)
Prepare the mannequin and save the skilled mannequin
# Path untuk menyimpan mannequin
model_path = "/content material/drive/MyDrive/Colab Notebooks/Mannequin Latih/Gambar 5 Jenis Bunga/mannequin.h5"# Compile mannequin
mannequin.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Melatih mannequin dengan subset prepare dan melakukan validasi dengan subset val
historical past = mannequin.match(np.array(train_images), np.array(train_labels), epochs=10, validation_data=(np.array(val_images), np.array(val_labels)))
# Simpan mannequin
mannequin.save(model_path)
The code above is an instance implementation for saving, compiling, coaching, and saving a neural community mannequin used for flower classification. Right here’s an evidence of every line of code:
model_path
: A variable that holds the trail or location the place the mannequin might be saved. On this instance, the mannequin might be saved within the listing „/content material/drive/MyDrive/Colab Notebooks/Mannequin Latih/Gambar 5 Jenis Bunga/“ with the file identify „mannequin.h5“. The „.h5“ file format is usually used for saving fashions in Python utilizing the Keras or TensorFlow library.
mannequin.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
: This half compiles the mannequin by setting the required configurations earlier than coaching the mannequin. The compile
technique is used to set the optimizer, loss operate, and metrics for use throughout mannequin coaching. On this instance, the optimizer used is Adam, the loss operate is ready to ’sparse_categorical_crossentropy‘, and the metric calculated is accuracy.
historical past = mannequin.match(np.array(train_images), np.array(train_labels), epochs=10, validation_data=(np.array(val_images), np.array(val_labels)))
: That is the method of coaching the mannequin. The match
technique is used to coach the mannequin with the coaching knowledge (train_images
) and labels (train_labels
). The required variety of epochs is 10, which implies the mannequin will undergo 10 iterations on the coaching dataset. The validation knowledge (val_images
and val_labels
) are additionally included to guage the mannequin at every epoch and monitor its efficiency.
mannequin.save(model_path)
: After the coaching course of is accomplished, the mannequin might be saved to a file utilizing the save
technique. The mannequin might be saved on the location specified within the model_path
variable. On this instance, the mannequin might be saved with the identify „mannequin.h5“ within the specified listing.
The output ought to seem like this:
This output supplies details about the coaching technique of the mannequin. It exhibits the loss and accuracy values for every epoch throughout the coaching section. The coaching loss (loss
) and coaching accuracy (accuracy
) are displayed, in addition to the validation loss (val_loss
) and validation accuracy (val_accuracy
).
For instance, within the first epoch, the coaching loss is 1.4293 and the coaching accuracy is 0.3714. The validation loss is 1.3861 and the validation accuracy is 0.4860. This info helps monitor the efficiency of the mannequin throughout coaching and consider its effectiveness in classifying the flower photographs.
Show the coaching outcomes
# Mendapatkan nilai loss dan accuracy pada akhir pelatihan
train_loss, train_accuracy = mannequin.consider(np.array(train_images), np.array(train_labels))
val_loss, val_accuracy = mannequin.consider(np.array(val_images), np.array(val_labels))# Mengubah format angka menjadi bilangan bulat
train_accuracy_int = int(train_accuracy * 100)
val_accuracy_int = int(val_accuracy * 100)
# Menampilkan hasil pelatihan
print("Prepare Loss:", train_loss)
print("Prepare Accuracy:", train_accuracy_int)
print("Validation Loss:", val_loss)
print("Validation Accuracy:", val_accuracy_int)
Output:
The output offered represents the outcomes of coaching a mannequin utilizing coaching knowledge and validating it utilizing validation knowledge. Right here is an evidence for every line of the output:
“110/110 [====] — 13s 122ms/step — loss: 0.1715 — accuracy: 0.9586”:
- 110/110 signifies that there are 110 steps or batches within the coaching course of.
- [=====] is a visible illustration that exhibits the progress of coaching.
- 13s 122ms/step signifies the time taken for every coaching step.
- loss: 0.1715 signifies the loss worth obtained throughout the coaching section.
- accuracy: 0.9586 signifies the accuracy achieved throughout the coaching section.
“32/32 [====] — 4s 121ms/step — loss: 0.5410 — accuracy: 0.8880”:
- 32/32 signifies that there are 32 steps or batches within the analysis course of on the validation knowledge.
- [====] is a visible illustration that exhibits the progress of analysis.
- 4s 121ms/step signifies the time taken for every analysis step.
- loss: 0.5410 signifies the loss worth obtained throughout the analysis section.
- accuracy: 0.8880 signifies the accuracy achieved throughout the analysis section.
“Prepare Loss: 0.17147813737392426”:
- That is the loss worth throughout the coaching section, which is the typical of all of the batches carried out throughout coaching, amounting to 17%.
“Prepare Accuracy: 95”:
- That is the accuracy charge throughout the coaching section, which is the typical of all of the batches carried out throughout coaching, amounting to 95%.
“Validation Loss: 0.5410242080688477”:
- That is the loss worth throughout the analysis section utilizing the validation knowledge. This loss displays how precisely the mannequin predicts on unseen validation knowledge throughout coaching, amounting to 54%.
“Validation Accuracy: 88”:
- That is the accuracy charge throughout the analysis section utilizing the validation knowledge. This accuracy displays how precisely the mannequin predicts on unseen validation knowledge throughout coaching, amounting to 88%.
Displaying Check Accuracy
With this check accuracy, it might probably assist assess the efficiency of the skilled mannequin on unseen knowledge. The check accuracy supplies a sign of how properly the mannequin generalizes to new and unseen examples. The next check accuracy implies that the mannequin has discovered patterns and options from the coaching knowledge that may successfully classify and predict the goal labels within the check set.
# Mendefinisikan record test_images
test_images = []# Mendefinisikan record test_labels
test_labels = []
# Melakukan iterasi pada setiap folder di direktori check
for folder in os.listdir(test_output_path):
folder_path = os.path.be a part of(test_output_path, folder)
for file in os.listdir(folder_path):
image_path = os.path.be a part of(folder_path, file)
picture = cv2.imread(image_path)
test_images.append(picture)
label = get_label_from_folder(folder)
test_labels.append(label)
# Mengubah record test_images menjadi array numpy
test_images = np.array(test_images)
# Mengubah record test_labels menjadi array numpy
test_labels = np.array(test_labels)
# Evaluasi mannequin menggunakan subset check
loss, accuracy = mannequin.consider(test_images, test_labels)
# Menampilkan hasil evaluasi
# Mengubah format angka menjadi bilangan bulat
accuracy_int = int(accuracy * 100)
print("Check Accuracy:", accuracy_int)
Output:
The output signifies that the mannequin performs exceptionally properly, as evident from the check accuracy of 89%. Beforehand, throughout coaching, it achieved a formidable accuracy of 95%, whereas throughout validation, it achieved 88%. These excessive accuracy scores counsel that the mannequin has efficiently discovered and generalized patterns from the coaching knowledge, enabling it to precisely classify and predict the goal labels. Such sturdy efficiency throughout a number of analysis metrics signifies the effectiveness and reliability of the skilled mannequin in precisely predicting the varieties of flowers.
Menampilkan Laporan Klasifikasi
from tensorflow.keras.fashions import load_modelmannequin = load_model(model_path)
test_predictions = mannequin.predict(test_images)
test_predictions = np.argmax(test_predictions, axis=1)
from sklearn.metrics import classification_report, confusion_matrix
# Menghitung confusion matrix
cm = confusion_matrix(test_labels, test_predictions)
# Menampilkan classification report
target_names = ['Lilly', 'Lotus', 'Orchid', 'Sunflower', 'Tulip']
print("Classification Report:")
print(classification_report(test_labels, test_predictions, target_names=target_names))
# Menampilkan confusion matrix
print("Confusion Matrix:")
print(cm)
Output:
The output represents the outcomes of a classification evaluation carried out on a dataset with 5 totally different courses: Lily, Lotus, Orchid, Sunflower, and Tulip. Right here’s the interpretation of the output:
Precision: Precision measures how precisely the mannequin can establish every class. The next precision worth signifies higher classification accuracy for that class.
- The precision for the Lily class is 0.97, indicating a excessive stage of accuracy in classifying flowers appropriately as Lily.
- The precision for the Lotus class is 0.96, indicating a excessive stage of accuracy in classifying flowers appropriately as Lotus.
- The precision for the Orchid class is 0.84, indicating a barely decrease stage of accuracy in classifying flowers appropriately as Orchid.
- The precision for the Sunflower class is 0.86, indicating a reasonably excessive stage of accuracy in classifying flowers appropriately as Sunflower.
- The precision for the Tulip class is 0.91, indicating a excessive stage of accuracy in classifying flowers appropriately as Tulip.
Recall: Recall measures how properly the mannequin can establish all related samples from a category. The next recall worth signifies higher recognition of all true samples belonging to a category.
- The recall for the Lily class is 0.72, that means the mannequin acknowledges 72% of all true Lily flower samples.
- The recall for the Lotus class is 0.86, indicating the mannequin acknowledges 86% of all true Lotus flower samples.
- The recall for the Orchid class is 0.97, indicating the mannequin acknowledges 97% of all true Orchid flower samples.
- The recall for the Sunflower class is 0.99, indicating the mannequin acknowledges 99% of all true Sunflower flower samples.
- The recall for the Tulip class is 0.96, indicating the mannequin acknowledges 96% of all true Tulip flower samples.
F1-Rating: The F1-score is the harmonic common of precision and recall. It supplies a extra holistic view of the mannequin’s efficiency by contemplating each precision and recall.
- The F1-score for the Lily class is 0.83.
- The F1-score for the Lotus class is 0.91.
- The F1-score for the Orchid class is 0.90.
- The F1-score for the Sunflower class is 0.92.
- The F1-score for the Tulip class is 0.94.
Assist: Assist signifies the variety of samples included in every class within the dataset.
- The variety of samples for the Lily class is 100.
- The variety of samples for the Lotus class is 100.
- The variety of samples for the Orchid class is 100.
- The variety of samples for the Sunflower class is 100.
- The variety of samples for the Tulip class is 100.
Accuracy: Accuracy is a measure of how properly the mannequin can appropriately classify all samples total.
- The general accuracy is 0.90, indicating that the mannequin appropriately classifies 90% of all samples within the dataset.
Macro Common: Macro common calculates the typical analysis metrics (precision, recall, f1-score) for every class with out contemplating the pattern rely in every class. Macro common provides equal weight to every class.
- The macro common precision is 0.91.
- The macro common recall is 0.90.
- The macro common f1-score is 0.90.
Weighted Common: Weighted common calculates the typical analysis metrics (precision, recall, f1-score) for every class contemplating the pattern rely in every class. Weighted common provides extra weight to courses with a bigger pattern rely.
- The weighted common precision is 0.91.
- The weighted common recall is 0.90.
- The weighted common f1-score is 0.90.
Instance, contemplate the primary line:
- There’s a quantity 72, indicating that there are 72 samples from the Lilly class which are appropriately labeled as Lilly.
- The quantity 3 signifies that there are 3 samples from the Lilly class that have been misclassified as Lotus throughout testing.
- The quantity 10 signifies that there are 10 samples from the Lilly class that have been misclassified as Orchid, and so forth.
Let’s visualize the confusion matrix in a graphical type.
import seaborn as sns# Melakukan prediksi pada subset check
test_predictions = mannequin.predict(test_images)
test_predictions = np.argmax(test_predictions, axis=1)
# Menghitung confusion matrix
cm = confusion_matrix(test_labels, test_predictions)
# Membuat plot confusion matrix
plt.determine(figsize=(8, 6))
im = plt.imshow(cm, cmap='Blues')
# Menampilkan angka pada setiap sel
for i in vary(len(cm)):
for j in vary(len(cm)):
plt.textual content(j, i, str(cm[i, j]), ha='heart', va='heart', shade='white' if cm[i, j] > np.max(cm) / 2 else 'black')
# Menampilkan legenda
cbar = plt.colorbar(im)
cbar.ax.set_ylabel('Jumlah Prediksi')
plt.title('Confusion Matrix')
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.present()
Output:
Visualizing the confusion matrix in a graphical type enhances our understanding of the mannequin’s classification efficiency, helps in error evaluation, and facilitates efficient communication of outcomes.
Uji klasifikasi menggunakan gambar dari folder subset uji
from tensorflow.keras.preprocessing import picture
import matplotlib.pyplot as plt
import numpy as np# Masukkan alamat path gambar
image_path = '/content material/drive/MyDrive/Colab Notebooks/Pra-Pemrosesan/Klasifikasi Gambar 5 Jenis Bunga/check/Orchid/Orchid09.jpg'
# Load gambar
img = picture.load_img(image_path, target_size=(224, 224))
imgplot = plt.imshow(img)
x = picture.img_to_array(img)
x = np.expand_dims(x, axis=0)
photographs = np.vstack([x])
courses = mannequin.predict(photographs, batch_size=10)
predicted_class_index = np.argmax(courses)
if predicted_class_index == 0:
print('Lilly')
elif predicted_class_index == 1:
print('Lotus')
elif predicted_class_index == 2:
print('Orchid')
elif predicted_class_index == 3:
print('Sunflower')
else:
print('Tulip')
Let’s check the mannequin utilizing an Orchid picture by copying the listing deal with of the saved Orchid flower picture. We are going to see if the machine can efficiently predict whether or not that is an Orchid flower.
Outcome:
Nice! The machine efficiently predicted it, indicating that the picture classification was profitable.
This undertaking supplies proof that by combining CNN, dropout layers, and the Xception mannequin, we will obtain excessive accuracy. The outcomes exhibit that the mannequin is efficient in precisely classifying photographs of various flower varieties. This method might be additional explored and utilized in varied picture classification duties, providing promising outcomes when it comes to accuracy and efficiency.
For future analysis, it is suggested that readers and people who have examined based mostly on this writing proceed to discover new concepts or develop new approaches to optimize machine studying, notably in picture processing or picture classification duties. There’s nonetheless room for enchancment and innovation on this subject, and additional developments can result in even higher outcomes and extra correct fashions. Moreover, exploring strategies resembling switch studying, knowledge augmentation, or ensemble strategies may contribute to enhancing the efficiency of picture classification fashions. Steady experimentation and innovation are essential in driving progress and reaching breakthroughs within the subject of machine studying.
That is the hyperlink related to the project, utilizing Google Colab.
You’re welcome! I respect your consideration. Be at liberty to debate additional within the remark part.