Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alpha b #233

Merged
merged 19 commits into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,13 @@ Samples/*
/Temp
/Test.md
/Interface/GUI/Data/model_info.json
/ruff_check_results.txt
/ruff_format_results.txt
/Load_Backup.py

# Exclude backup load
/Backup_*_COPY.ipynb
/ruff_check_results.txt
/ruff_format_results.txt

# Temp
/history/Archive
/Test_ENV_G.ipynb
2 changes: 1 addition & 1 deletion .idea/.name

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7,456 changes: 5,209 additions & 2,247 deletions BETA_E_Model_T&T.ipynb

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ The model is a Convolutional Neural Network (CNN) trained on a dataset of 23681
This combined dataset provides a comprehensive set of images for training the model.\

### Model list:
| Model | Base Model | Params | acc | Status |
|----------|-----------------|--------|--------|--------|
| V6 | efficientnet-b7 | 65.4M | 97.12% | ✅ |
| V7 light | efficientnet-b4 | 29.7M | 97.12% | ✅ |
| V8 Super light | efficientnet-b0 | 4.8M | 96.47% | ✅ |
| Model | Base Model | Params | acc | Status | Grad Cam |
|----------|-----------------|--------|--------|--------|----------|
| V6 | efficientnet-b7 | 65.4M | 97.12% | ✅ | ✅ |
| V7 light | efficientnet-b4 | 29.7M | 97.12% | ✅ | ⚠️ |
| V8 Super light | efficientnet-b0 | 4.8M | 96.47% | ✅ | ❌ |

## Training Methods
### The AI model supports two distinct training approaches:
Expand Down
55 changes: 55 additions & 0 deletions Test_ENV_G.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"T\n",
"Timeout!\n"
]
},
{
"data": {
"text/plain": [
"{'user_input': 'N/A', 'input_time': 5, 'default_var_used': True}"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from Utils.Timeout_input import TimeoutInput\n",
"\n",
"TimeoutInput('T', 5, 'N/A').run()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
35 changes: 35 additions & 0 deletions Utils/Other.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,38 @@ def evaluate_model_full(y_test, model_pred, model=None, x_test=None):

# Print the table
print(tabulate(metrics, headers=["Metric", "Value"], tablefmt="pretty"))


def set_optimizer_attribute(optimizer, attribute, value, verbose: bool = False):
"""Sets an attribute on the given optimizer to the specified value.

Args:
optimizer: The optimizer instance to modify.
attribute: The attribute name to set.
value: The value to set the attribute to.
verbose: Whether to print a message if the attribute does not exist.
"""
if hasattr(optimizer, attribute):
setattr(optimizer, attribute, value)
else:
if verbose:
print(f"The optimizer does not have an attribute named '{attribute}'")


def print_optimizer_info(model):
"""Prints information about the optimizer used by a Keras model.

Prints the optimizer class name and its parameter values. Useful
for inspecting optimizer configuration.

Args:
model: The Keras model whose optimizer to print info for.

"""
if model.optimizer:
print_Color(f"~*Optimizer: ~*{model.optimizer.__class__.__name__}", ["cyan", "green"], advanced_mode=True)
print_Color(" <Opt> Parameters:", ["cyan"])
for param, value in model.optimizer.get_config().items():
print_Color(f"~* <Opt> -- ~*{param}: ~*{value}", ["cyan", "light_cyan", "green"], advanced_mode=True)
else:
print_Color("No optimizer found in the model.", ["red"])
2 changes: 2 additions & 0 deletions Utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

## Other.py (by Me)

## Timeout_input.py (by Me)

## FixedDropout.py (by Me)
For EfficientNet model Example:
```python
Expand Down
59 changes: 59 additions & 0 deletions Utils/Timeout_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import threading
import queue
import keyboard


class TimeoutInput:
"""
A class to get user input with a timeout.

Attributes:
prompt (str): The prompt to display to the user.
timeout (int): The time in seconds to wait for user input.
default_var (str): The default value to return if the user does not provide input.
timeout_message (str): The message to display when the input times out.
"""

def __init__(self, prompt, timeout, default_var, timeout_message="\nTimeout!"):
self.prompt = prompt
self.timeout = timeout
self.default_var = default_var
self.timeout_message = timeout_message
self.user_input = None
self.input_queue = queue.Queue()
self.stop_thread = False

def get_input(self):
"""Get user input in a non-blocking manner."""
print(self.prompt, end="", flush=True)
while not self.stop_thread:
if keyboard.is_pressed("\n"):
line = input()
if line:
self.input_queue.put(line.strip())
return

def run(self):
"""
Run the TimeoutInput.

Starts a thread to get user input and waits for the specified timeout.
If the user does not provide input within the timeout, returns the default value.
"""
thread = threading.Thread(target=self.get_input)
thread.start()
thread.join(self.timeout)
if thread.is_alive():
self.stop_thread = True
print(self.timeout_message)
return {"user_input": self.default_var, "input_time": self.timeout, "default_var_used": True}
else:
self.user_input = self.input_queue.get()
return {"user_input": self.user_input, "input_time": self.timeout, "default_var_used": False}


# Example usage
if __name__ == "__main__":
timeout_input = TimeoutInput("Enter something: ", 5, "default", "\nTimeout from TimeoutInput!")
result = timeout_input.run()
print(result)
13 changes: 5 additions & 8 deletions Utils/lr_find.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import keras
import tempfile

import matplotlib.pyplot as plt
import numpy as np

import tensorflow as tf
from tensorflow import keras
from tqdm.auto import tqdm

K = keras.backend
import keras.src.legacy.backend as K


class Scheduler:
Expand Down Expand Up @@ -59,9 +56,9 @@ class LrFinder:

def __init__(
self,
model: tf.keras.Model,
optimizer: tf.keras.optimizers.Optimizer,
loss_fn: tf.keras.losses.Loss,
model: keras.Model,
optimizer: keras.optimizers.Optimizer,
loss_fn: keras.losses.Loss,
) -> None:
self.lrs = []
self.losses = []
Expand Down
6 changes: 2 additions & 4 deletions Utils/one_cycle.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from tensorflow import keras
import keras
import math
import matplotlib.pyplot as plt

K = keras.backend

import keras.src.legacy.backend as K

class OneCycleLr(keras.callbacks.Callback):
"""
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading