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

Add files via upload #606

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
Binary file not shown.
32 changes: 32 additions & 0 deletions Computer Vision/Celestial_Object_Classification/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from src.data_loader import load_data
from src.model import create_model
from src.utils import save_training_plots, save_metrics
import os
from src.config import *

def main():
# Load and preprocess data
print("Loading data...")
x_train, x_test, y_train, y_test = load_data()

# Create and train model
print("Creating and training model...")
model = create_model()
history = model.fit(
x_train, y_train,
epochs=25,
validation_data=(x_test, y_test),
verbose=1
)

# Save results
print("Saving results...")
save_training_plots(history)
save_metrics(model, x_test, y_test)

# Save model
model.save(os.path.join('results', 'model.h5'))
print("Training complete! Results saved in 'results' directory.")

if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
numpy==1.23.5
scipy==1.10.1
scikit-learn==1.2.2
tensorflow==2.12.0
opencv-python==4.7.0.72
matplotlib==3.7.1
seaborn==0.12.2
pandas==2.0.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
precision recall f1-score support

0 0.72 0.66 0.69 189
1 0.90 0.92 0.91 609

accuracy 0.86 798
macro avg 0.81 0.79 0.80 798
weighted avg 0.85 0.86 0.85 798
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
17 changes: 17 additions & 0 deletions Computer Vision/Celestial_Object_Classification/src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

import os

# Directory paths
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(BASE_DIR, 'data')
RESULTS_DIR = os.path.join(BASE_DIR, 'results')

# Ensure results directory exists
os.makedirs(RESULTS_DIR, exist_ok=True)

# Model parameters
IMG_SIZE = 64
BATCH_SIZE = 32
EPOCHS = 25
RANDOM_STATE = 42
TEST_SIZE = 0.2
40 changes: 40 additions & 0 deletions Computer Vision/Celestial_Object_Classification/src/data_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import cv2
import numpy as np
import glob
import os
from sklearn.model_selection import train_test_split
from .config import *

def load_data():
"""Load and preprocess image data."""
data = []
labels = []

# Load galaxy images
galaxy_paths = glob.glob(os.path.join(DATA_DIR, 'galaxy', '*'))
for path in galaxy_paths:
img = cv2.imread(path, 1)
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
data.append(img)
labels.append(0) # 0 for galaxy

# Load star images
star_paths = glob.glob(os.path.join(DATA_DIR, 'star', '*'))
for path in star_paths:
img = cv2.imread(path, 1)
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
data.append(img)
labels.append(1) # 1 for star

data = np.array(data) / 255.0 # Normalize
labels = np.array(labels)

# Split data
x_train, x_test, y_train, y_test = train_test_split(
data, labels,
test_size=TEST_SIZE,
random_state=RANDOM_STATE,
stratify=labels
)

return x_train, x_test, y_train, y_test
22 changes: 22 additions & 0 deletions Computer Vision/Celestial_Object_Classification/src/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from tensorflow.keras import layers, models
from .config import *
def create_model():
"""Create and return the CNN model."""
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(2, activation='softmax') # 2 classes: star and galaxy
])

model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)

return model
73 changes: 73 additions & 0 deletions Computer Vision/Celestial_Object_Classification/src/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, precision_recall_curve
import numpy as np
import os
from .config import RESULTS_DIR
from .config import *

def save_training_plots(history):
"""Save accuracy and loss plots."""
# Accuracy plot
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

# Loss plot
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.tight_layout()
plt.savefig(os.path.join(RESULTS_DIR, 'training_history.png'))
plt.close()

def save_metrics(model, x_test, y_test):
"""Save confusion matrix, ROC curve, PR curve, and classification report."""
# Get predictions
y_pred = model.predict(x_test)
y_pred_classes = np.argmax(y_pred, axis=1)

# Confusion Matrix
cm = confusion_matrix(y_test, y_pred_classes)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix')
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.savefig(os.path.join(RESULTS_DIR, 'confusion_matrix.png'))
plt.close()

# ROC Curve
fpr, tpr, _ = roc_curve(y_test, y_pred[:, 1])
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr)
plt.title('ROC Curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.savefig(os.path.join(RESULTS_DIR, 'roc_curve.png'))
plt.close()

# Precision-Recall Curve
precision, recall, _ = precision_recall_curve(y_test, y_pred[:, 1])
plt.figure(figsize=(8, 6))
plt.plot(recall, precision)
plt.title('Precision-Recall Curve')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.savefig(os.path.join(RESULTS_DIR, 'pr_curve.png'))
plt.close()

# Classification Report
report = classification_report(y_test, y_pred_classes)
with open(os.path.join(RESULTS_DIR, 'classification_report.txt'), 'w') as f:
f.write(report)
Loading