diff --git a/imageClasification/Classificator.py b/imageClasification/Classificator.py index 4f9d2fd..e69de29 100644 --- a/imageClasification/Classificator.py +++ b/imageClasification/Classificator.py @@ -1,136 +0,0 @@ -import matplotlib.pyplot as plt -import numpy as np -import os -import PIL -import tensorflow as tf - -from tensorflow import keras -from tensorflow.keras import layers -from tensorflow.keras.models import Sequential - - -class Classificator(): - - def __init__(self, data_dir: str) -> None: - super().__init__() - self.data = self.train_model(data_dir) - - def train_model(self, data_dir): - batch_size = 32 - img_height = 180 - img_width = 180 - - train_ds = tf.keras.utils.image_dataset_from_directory( - data_dir, - validation_split=0.2, - subset="training", - seed=123, - image_size=(img_height, img_width), - batch_size=batch_size) - - val_ds = tf.keras.utils.image_dataset_from_directory( - data_dir, - validation_split=0.2, - subset="validation", - seed=123, - image_size=(img_height, img_width), - batch_size=batch_size) - - class_names = train_ds.class_names - print(class_names) - - plt.figure(figsize=(10, 10)) - for images, labels in train_ds.take(1): - for i in range(9): - ax = plt.subplot(3, 3, i + 1) - plt.imshow(images[i].numpy().astype("uint8")) - plt.title(class_names[labels[i]]) - plt.axis("off") - - for image_batch, labels_batch in train_ds: - print(image_batch.shape) - print(labels_batch.shape) - break - - AUTOTUNE = tf.data.AUTOTUNE - - train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE) - val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE) - - normalization_layer = layers.Rescaling(1. / 255) - - normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y)) - image_batch, labels_batch = next(iter(normalized_ds)) - first_image = image_batch[0] - # Notice the pixel values are now in `[0,1]`. - print(np.min(first_image), np.max(first_image)) - - num_classes = len(class_names) - - model = Sequential([ - layers.Rescaling(1. / 255, input_shape=(img_height, img_width, 3)), - layers.Conv2D(16, 3, padding='same', activation='relu'), - layers.MaxPooling2D(), - layers.Conv2D(32, 3, padding='same', activation='relu'), - layers.MaxPooling2D(), - layers.Conv2D(64, 3, padding='same', activation='relu'), - layers.MaxPooling2D(), - layers.Flatten(), - layers.Dense(128, activation='relu'), - layers.Dense(num_classes) - ]) - - model.compile(optimizer='adam', - loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), - metrics=['accuracy']) - - # model.summary() - - epochs = 10 - history = model.fit( - train_ds, - validation_data=val_ds, - epochs=epochs - ) - - acc = history.history['accuracy'] - val_acc = history.history['val_accuracy'] - - loss = history.history['loss'] - val_loss = history.history['val_loss'] - - epochs_range = range(epochs) - - plt.figure(figsize=(8, 8)) - plt.subplot(1, 2, 1) - plt.plot(epochs_range, acc, label='Training Accuracy') - plt.plot(epochs_range, val_acc, label='Validation Accuracy') - plt.legend(loc='lower right') - plt.title('Training and Validation Accuracy') - - plt.subplot(1, 2, 2) - plt.plot(epochs_range, loss, label='Training Loss') - plt.plot(epochs_range, val_loss, label='Validation Loss') - plt.legend(loc='upper right') - plt.title('Training and Validation Loss') - plt.show() - return model, class_names, img_width, img_height - - def image_clasification(self,image_path): - # ścieżka do sprawdzanego obrazu - # image_path = "./th-367101945.jpg" - - img = tf.keras.utils.load_img( - image_path, target_size=(180, 180) - ) - img_array = tf.keras.utils.img_to_array(img) - img_array = tf.expand_dims(img_array, 0) # Create a batch - - predictions = self.data[0].predict(img_array) - score = tf.nn.softmax(predictions[0]) - - print( - "This image most likely belongs to {} with a {:.2f} percent confidence." - .format(self.data[1][np.argmax(score)], 100 * np.max(score)) - ) - return self.data[1][np.argmax(score)] diff --git a/imageClasification/my_model/keras_metadata.pb b/imageClasification/my_model/keras_metadata.pb new file mode 100644 index 0000000..3e8a78a --- /dev/null +++ b/imageClasification/my_model/keras_metadata.pb @@ -0,0 +1,15 @@ + +Troot"_tf_keras_sequential*T{"name": "sequential", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "must_restore_from_config": false, "class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "rescaling_1_input"}}, {"class_name": "Rescaling", "config": {"name": "rescaling_1", "trainable": true, "batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "dtype": "float32", "scale": 0.00392156862745098, "offset": 0.0}}, {"class_name": "Conv2D", "config": {"name": "conv2d", "trainable": true, "dtype": "float32", "filters": 16, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "dtype": "float32", "filters": 32, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}}, {"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "dtype": "float32", "filters": 64, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}}, {"class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "data_format": "channels_last"}}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 3, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, "shared_object_id": 21, "input_spec": [{"class_name": "InputSpec", "config": {"dtype": null, "shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "ndim": 4, "max_ndim": null, "min_ndim": null, "axes": {}}}], "build_input_shape": {"class_name": "TensorShape", "items": [null, 180, 180, 3]}, "is_graph_network": true, "full_save_spec": {"class_name": "__tuple__", "items": [[{"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 180, 180, 3]}, "float32", "rescaling_1_input"]}], {}]}, "save_spec": {"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 180, 180, 3]}, "float32", "rescaling_1_input"]}, "keras_version": "2.9.0", "backend": "tensorflow", "model_config": {"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "rescaling_1_input"}, "shared_object_id": 0}, {"class_name": "Rescaling", "config": {"name": "rescaling_1", "trainable": true, "batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "dtype": "float32", "scale": 0.00392156862745098, "offset": 0.0}, "shared_object_id": 1}, {"class_name": "Conv2D", "config": {"name": "conv2d", "trainable": true, "dtype": "float32", "filters": 16, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 5}, {"class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "dtype": "float32", "filters": 32, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 6}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 7}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 8}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 9}, {"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "dtype": "float32", "filters": 64, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 10}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 11}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 12}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 13}, {"class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "data_format": "channels_last"}, "shared_object_id": 14}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 15}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 16}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 17}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 3, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 18}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 19}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 20}]}}, "training_config": {"loss": {"class_name": "SparseCategoricalCrossentropy", "config": {"reduction": "auto", "name": "sparse_categorical_crossentropy", "from_logits": true}, "shared_object_id": 23}, "metrics": [[{"class_name": "MeanMetricWrapper", "config": {"name": "accuracy", "dtype": "float32", "fn": "sparse_categorical_accuracy"}, "shared_object_id": 24}]], "weighted_metrics": null, "loss_weights": null, "optimizer_config": {"class_name": "Adam", "config": {"name": "Adam", "learning_rate": 0.0010000000474974513, "decay": 0.0, "beta_1": 0.8999999761581421, "beta_2": 0.9990000128746033, "epsilon": 1e-07, "amsgrad": false}}}}2 + root.layer-0"_tf_keras_layer*{"name": "rescaling_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "stateful": false, "must_restore_from_config": false, "class_name": "Rescaling", "config": {"name": "rescaling_1", "trainable": true, "batch_input_shape": {"class_name": "__tuple__", "items": [null, 180, 180, 3]}, "dtype": "float32", "scale": 0.00392156862745098, "offset": 0.0}, "shared_object_id": 1}2 + root.layer_with_weights-0"_tf_keras_layer* {"name": "conv2d", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Conv2D", "config": {"name": "conv2d", "trainable": true, "dtype": "float32", "filters": 16, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 4, "axes": {"-1": 3}}, "shared_object_id": 25}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 180, 180, 3]}}2 + root.layer-2"_tf_keras_layer*{"name": "max_pooling2d", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 5, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": 4, "max_ndim": null, "min_ndim": null, "axes": {}}, "shared_object_id": 26}}2 + root.layer_with_weights-1"_tf_keras_layer* {"name": "conv2d_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "dtype": "float32", "filters": 32, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 6}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 7}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 8, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 4, "axes": {"-1": 16}}, "shared_object_id": 27}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 90, 90, 16]}}2 + root.layer-4"_tf_keras_layer*{"name": "max_pooling2d_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 9, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": 4, "max_ndim": null, "min_ndim": null, "axes": {}}, "shared_object_id": 28}}2 + root.layer_with_weights-2"_tf_keras_layer* {"name": "conv2d_2", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "dtype": "float32", "filters": 64, "kernel_size": {"class_name": "__tuple__", "items": [3, 3]}, "strides": {"class_name": "__tuple__", "items": [1, 1]}, "padding": "same", "data_format": "channels_last", "dilation_rate": {"class_name": "__tuple__", "items": [1, 1]}, "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 10}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 11}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 12, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 4, "axes": {"-1": 32}}, "shared_object_id": 29}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 45, 45, 32]}}2 + root.layer-6"_tf_keras_layer*{"name": "max_pooling2d_2", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": "float32", "pool_size": {"class_name": "__tuple__", "items": [2, 2]}, "padding": "valid", "strides": {"class_name": "__tuple__", "items": [2, 2]}, "data_format": "channels_last"}, "shared_object_id": 13, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": 4, "max_ndim": null, "min_ndim": null, "axes": {}}, "shared_object_id": 30}}2 + root.layer-7"_tf_keras_layer*{"name": "flatten", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "data_format": "channels_last"}, "shared_object_id": 14, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 1, "axes": {}}, "shared_object_id": 31}}2 + root.layer_with_weights-3"_tf_keras_layer*{"name": "dense", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 128, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 15}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 16}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 17, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 30976}}, "shared_object_id": 32}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 30976]}}2 + +root.layer_with_weights-4"_tf_keras_layer*{"name": "dense_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 3, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 18}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 19}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 20, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 128}}, "shared_object_id": 33}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 128]}}2 +root.keras_api.metrics.0"_tf_keras_metric*{"class_name": "Mean", "name": "loss", "dtype": "float32", "config": {"name": "loss", "dtype": "float32"}, "shared_object_id": 34}2 +root.keras_api.metrics.1"_tf_keras_metric*{"class_name": "MeanMetricWrapper", "name": "accuracy", "dtype": "float32", "config": {"name": "accuracy", "dtype": "float32", "fn": "sparse_categorical_accuracy"}, "shared_object_id": 24}2 \ No newline at end of file diff --git a/imageClasification/my_model/saved_model.pb b/imageClasification/my_model/saved_model.pb new file mode 100644 index 0000000..df3330f Binary files /dev/null and b/imageClasification/my_model/saved_model.pb differ diff --git a/imageClasification/my_model.h5 b/imageClasification/my_model/variables/variables.data-00000-of-00001 similarity index 78% rename from imageClasification/my_model.h5 rename to imageClasification/my_model/variables/variables.data-00000-of-00001 index 4a0305e..915516e 100644 Binary files a/imageClasification/my_model.h5 and b/imageClasification/my_model/variables/variables.data-00000-of-00001 differ diff --git a/imageClasification/my_model/variables/variables.index b/imageClasification/my_model/variables/variables.index new file mode 100644 index 0000000..31ff088 Binary files /dev/null and b/imageClasification/my_model/variables/variables.index differ diff --git a/imageClasification/usedAssets/ClassificatorInside.py b/imageClasification/usedAssets/ClassificatorInside.py new file mode 100644 index 0000000..4f9d2fd --- /dev/null +++ b/imageClasification/usedAssets/ClassificatorInside.py @@ -0,0 +1,136 @@ +import matplotlib.pyplot as plt +import numpy as np +import os +import PIL +import tensorflow as tf + +from tensorflow import keras +from tensorflow.keras import layers +from tensorflow.keras.models import Sequential + + +class Classificator(): + + def __init__(self, data_dir: str) -> None: + super().__init__() + self.data = self.train_model(data_dir) + + def train_model(self, data_dir): + batch_size = 32 + img_height = 180 + img_width = 180 + + train_ds = tf.keras.utils.image_dataset_from_directory( + data_dir, + validation_split=0.2, + subset="training", + seed=123, + image_size=(img_height, img_width), + batch_size=batch_size) + + val_ds = tf.keras.utils.image_dataset_from_directory( + data_dir, + validation_split=0.2, + subset="validation", + seed=123, + image_size=(img_height, img_width), + batch_size=batch_size) + + class_names = train_ds.class_names + print(class_names) + + plt.figure(figsize=(10, 10)) + for images, labels in train_ds.take(1): + for i in range(9): + ax = plt.subplot(3, 3, i + 1) + plt.imshow(images[i].numpy().astype("uint8")) + plt.title(class_names[labels[i]]) + plt.axis("off") + + for image_batch, labels_batch in train_ds: + print(image_batch.shape) + print(labels_batch.shape) + break + + AUTOTUNE = tf.data.AUTOTUNE + + train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE) + val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE) + + normalization_layer = layers.Rescaling(1. / 255) + + normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y)) + image_batch, labels_batch = next(iter(normalized_ds)) + first_image = image_batch[0] + # Notice the pixel values are now in `[0,1]`. + print(np.min(first_image), np.max(first_image)) + + num_classes = len(class_names) + + model = Sequential([ + layers.Rescaling(1. / 255, input_shape=(img_height, img_width, 3)), + layers.Conv2D(16, 3, padding='same', activation='relu'), + layers.MaxPooling2D(), + layers.Conv2D(32, 3, padding='same', activation='relu'), + layers.MaxPooling2D(), + layers.Conv2D(64, 3, padding='same', activation='relu'), + layers.MaxPooling2D(), + layers.Flatten(), + layers.Dense(128, activation='relu'), + layers.Dense(num_classes) + ]) + + model.compile(optimizer='adam', + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), + metrics=['accuracy']) + + # model.summary() + + epochs = 10 + history = model.fit( + train_ds, + validation_data=val_ds, + epochs=epochs + ) + + acc = history.history['accuracy'] + val_acc = history.history['val_accuracy'] + + loss = history.history['loss'] + val_loss = history.history['val_loss'] + + epochs_range = range(epochs) + + plt.figure(figsize=(8, 8)) + plt.subplot(1, 2, 1) + plt.plot(epochs_range, acc, label='Training Accuracy') + plt.plot(epochs_range, val_acc, label='Validation Accuracy') + plt.legend(loc='lower right') + plt.title('Training and Validation Accuracy') + + plt.subplot(1, 2, 2) + plt.plot(epochs_range, loss, label='Training Loss') + plt.plot(epochs_range, val_loss, label='Validation Loss') + plt.legend(loc='upper right') + plt.title('Training and Validation Loss') + plt.show() + return model, class_names, img_width, img_height + + def image_clasification(self,image_path): + # ścieżka do sprawdzanego obrazu + # image_path = "./th-367101945.jpg" + + img = tf.keras.utils.load_img( + image_path, target_size=(180, 180) + ) + img_array = tf.keras.utils.img_to_array(img) + img_array = tf.expand_dims(img_array, 0) # Create a batch + + predictions = self.data[0].predict(img_array) + score = tf.nn.softmax(predictions[0]) + + print( + "This image most likely belongs to {} with a {:.2f} percent confidence." + .format(self.data[1][np.argmax(score)], 100 * np.max(score)) + ) + return self.data[1][np.argmax(score)]