-
Notifications
You must be signed in to change notification settings - Fork 2
Horus: added a pre-trained model - ResNet and checkpoint support. #9
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
Open
haichangsi
wants to merge
9
commits into
Lunicen:main
Choose a base branch
from
haichangsi:train
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
068bf3a
added utils to clear project and small return fixes
haichangsi 0b18e51
horus: added a pretrained resnet
haichangsi 582bbba
horus: added early stopping, fixed checkpoint cb
haichangsi be73ff6
Horus: added support for multiple batch sizes
haichangsi b2bb4b1
Horus: added support for multiple learning rates
haichangsi 726573f
Horus: reformatted the project to meet pep8 standards
haichangsi 9aa93c7
Remove Early stopping
jereml99 0552e63
Add more metric
jereml99 f38f22d
Add testing model
jereml99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,11 @@ | ||
| librosa==0.10.0.post2 | ||
| matplotlib==3.5.3 | ||
| noisereduce==2.0.1 | ||
| numpy==1.23.3 | ||
| pydub==0.25.1 | ||
| pytorch_lightning==2.0.2 | ||
| requests==2.28.1 | ||
| scikit_learn==1.2.2 | ||
| scipy==1.10.1 | ||
| seaborn==0.12.2 | ||
| soundfile==0.12.1 | ||
| torch==2.0.0 |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import torch | ||
| from torch import nn | ||
| from torch.nn import functional as F | ||
| import pytorch_lightning as pl | ||
| from torchvision.models.resnet import ResNet, ResNet50_Weights | ||
| from torchvision.models import resnet50 | ||
| from torchmetrics import Precision, Accuracy, F1Score, Recall, ConfusionMatrix, AUROC | ||
|
|
||
| class BirdClassifierResNet(pl.LightningModule): | ||
| def __init__(self, num_classes, learning_rate=0.001): | ||
| super(BirdClassifierResNet, self).__init__() | ||
|
|
||
| # Load pre-trained ResNet50 | ||
| self.feature_extractor = resnet50(weights=ResNet50_Weights.DEFAULT) | ||
| # Replace the last fully connected layer | ||
| # Parameters of newly constructed modules have requires_grad=True by default | ||
| num_ftrs = self.feature_extractor.fc.in_features | ||
| self.feature_extractor.fc = nn.Linear(num_ftrs, num_classes) | ||
|
|
||
| self.learning_rate = learning_rate | ||
|
|
||
| # Define metrics | ||
| self.train_acc = Accuracy() | ||
| self.val_acc = Accuracy() | ||
| self.precision_metric = Precision(num_classes=num_classes) | ||
| self.recall = Recall(num_classes=num_classes) | ||
| self.f1 = F1Score(num_classes=num_classes) | ||
| self.auroc = AUROC(num_classes=num_classes) | ||
|
|
||
| def forward(self, x): | ||
| return self.feature_extractor(x) | ||
|
|
||
| def training_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| logits = self(x) | ||
| loss = F.cross_entropy(logits, y) | ||
| preds = torch.argmax(logits, dim=1) | ||
|
|
||
| # Update metrics | ||
| self.train_acc(preds, y) | ||
| self.precision_metric(preds, y) | ||
| self.recall(preds, y) | ||
| self.f1(preds, y) | ||
|
|
||
| self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True, logger=True) | ||
| self.log('train_acc', self.train_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True) | ||
| return loss | ||
|
|
||
| def validation_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| logits = self(x) | ||
| loss = F.cross_entropy(logits, y) | ||
| preds = torch.argmax(logits, dim=1) | ||
|
|
||
| # Update metrics | ||
| self.val_acc(preds, y) | ||
| self.precision_metric(preds, y) | ||
| self.recall(preds, y) | ||
| self.f1(preds, y) | ||
| # Convert logits to probabilities | ||
| probs = torch.softmax(logits, dim=1) | ||
| self.auroc(probs, y) | ||
|
|
||
| self.log('val_loss', loss, prog_bar=True) | ||
| self.log('val_acc', self.val_acc, prog_bar=True) | ||
| self.log('val_precision', self.precision, prog_bar=True) | ||
| self.log('val_recall', self.recall, prog_bar=True) | ||
| self.log('val_f1', self.f1, prog_bar=True) | ||
| self.log('val_auroc', self.auroc, prog_bar=True) | ||
| return loss | ||
|
|
||
| def test_step(self, batch, batch_idx): | ||
| x, y = batch | ||
| logits = self(x) | ||
| loss = F.cross_entropy(logits, y) | ||
| preds = torch.argmax(logits, dim=1) | ||
|
|
||
| # Update metrics | ||
| self.val_acc(preds, y) | ||
| self.precision_metric(preds, y) | ||
| self.recall(preds, y) | ||
| self.f1(preds, y) | ||
| # Convert logits to probabilities | ||
| probs = torch.softmax(logits, dim=1) | ||
| self.auroc(probs, y) | ||
|
|
||
| self.log('test_loss', loss, prog_bar=True) | ||
| self.log('test_acc', self.val_acc, prog_bar=True) | ||
| self.log('test_precision', self.precision_metric, prog_bar=True) | ||
| self.log('test_recall', self.recall, prog_bar=True) | ||
| self.log('test_f1', self.f1, prog_bar=True) | ||
| self.log('test_auroc', self.auroc, prog_bar=True) | ||
| return loss | ||
|
|
||
|
|
||
| def configure_optimizers(self): | ||
| return torch.optim.Adam(self.parameters(), lr=self.learning_rate) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ | |
| import numpy as np | ||
| from AudioProcessor import AudioPreprocessor | ||
|
|
||
|
|
||
| class BirdSpectrogramDataset(Dataset): | ||
| def __init__(self, root_dir, split="train"): | ||
| self.root_dir = Path(root_dir) | ||
|
|
@@ -19,10 +20,14 @@ def __init__(self, root_dir, split="train"): | |
| if class_dir.name not in self.label_map: | ||
| self.label_map[class_dir.name] = len(self.label_map) | ||
| for file in class_dir.glob("*.mp3"): | ||
| if file is None: | ||
| continue | ||
| trimed_audio, sr = self.audio_preprocessor.load_and_trim_audio(file) | ||
| if trimed_audio is None: | ||
| continue | ||
| mel_spec = self.audio_preprocessor.create_mel_spectrogram_from_audio(trimed_audio, sr) | ||
| mel_spec = self.audio_preprocessor.create_mel_spectrogram_from_audio( | ||
| trimed_audio, sr | ||
| ) | ||
| label = self.label_map[class_dir.name] | ||
| self.data.append((mel_spec, label)) | ||
|
|
||
|
|
@@ -32,19 +37,24 @@ def __len__(self): | |
| def __getitem__(self, idx): | ||
| mel_spec, label = self.data[idx] | ||
| mel_spec = torch.from_numpy(mel_spec).unsqueeze(0) # Add channel dimension | ||
| mel_spec = mel_spec.expand(3, -1, -1) # Expand single channel to three channels | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. W sumie dlaczego? |
||
| return mel_spec, label | ||
|
|
||
|
|
||
| class BirdSpectrogramDataModule(pl.LightningDataModule): | ||
| def __init__(self, root_dir, batch_size=16): | ||
| def __init__(self, root_dir, batch_size=16, num_workers=4): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice |
||
| super().__init__() | ||
| self.root_dir = root_dir | ||
| self.batch_size = batch_size | ||
| self.num_workers = num_workers | ||
|
|
||
| def setup(self, stage=None): | ||
| if stage == "fit" or stage is None: | ||
| self.train_dataset, self.val_dataset = self._create_datasets("train", "validation") | ||
| self.train_dataset, self.val_dataset = self._create_datasets( | ||
| "train", "validation" | ||
| ) | ||
| if stage == "test" or stage is None: | ||
| self.test_dataset, _ = self._create_datasets("test") | ||
| self.test_dataset = self._create_datasets("test")[0] | ||
|
|
||
| def _create_datasets(self, *splits): | ||
| datasets = [] | ||
|
|
@@ -54,10 +64,25 @@ def _create_datasets(self, *splits): | |
| return datasets | ||
|
|
||
| def train_dataloader(self): | ||
| return DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=True) | ||
| return DataLoader( | ||
| self.train_dataset, | ||
| batch_size=self.batch_size, | ||
| shuffle=True, | ||
| num_workers=self.num_workers, | ||
| ) | ||
|
|
||
| def val_dataloader(self): | ||
| return DataLoader(self.val_dataset, batch_size=self.batch_size, shuffle=False) | ||
| return DataLoader( | ||
| self.val_dataset, | ||
| batch_size=self.batch_size, | ||
| shuffle=False, | ||
| num_workers=self.num_workers, | ||
| ) | ||
|
|
||
| def test_dataloader(self): | ||
| return DataLoader(self.test_dataset, batch_size=self.batch_size, shuffle=False) | ||
| return DataLoader( | ||
| self.test_dataset, | ||
| batch_size=self.batch_size, | ||
| shuffle=False, | ||
| num_workers=self.num_workers, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| from pathlib import Path | ||
| import pytorch_lightning as pl | ||
| from BirdClassifierResNet import BirdClassifierResNet | ||
| from bird_spectrogram_classifier import BirdClassifier | ||
| from spectrogram_dataset import BirdSpectrogramDataModule | ||
| from pytorch_lightning.loggers import WandbLogger | ||
| import torch | ||
| import wandb | ||
|
|
||
| root_dirs = { | ||
| "split1": "data/split_raw", | ||
| "split2": "data/split_aug", | ||
| "split3": "data/split_wrong", | ||
| } | ||
| num_classes = 7 | ||
| batch_size = 32 # single batch size | ||
| learning_rate = 0.001 # single learning rate | ||
|
|
||
| models = [ | ||
| Path(f"split{num}_bird_classifier_rest.ckpt") for num in range(1,4) | ||
| ] | ||
|
|
||
|
|
||
| def main(): | ||
| for split_name, root_dir in root_dirs.items(): | ||
| data_module = BirdSpectrogramDataModule(root_dir, batch_size=batch_size) | ||
| data_module.setup() | ||
| data_loders = [("train_subset", data_module.train_dataloader()), ("val_subset", data_module.val_dataloader()), ("test_subset", data_module.test_dataloader())] | ||
| for model_path in models: | ||
| # Initialize the model | ||
| model = BirdClassifierResNet.load_from_checkpoint(model_path, num_classes=num_classes, learning_rate=learning_rate) | ||
|
|
||
| for subset_name, data_loder in data_loders: | ||
| # Set up the Weights & Biases logger | ||
| wandb_logger = WandbLogger( | ||
| project="bird-classification", | ||
| name=f"{split_name}_{model_path.name}_{subset_name}", | ||
| ) | ||
|
|
||
| # Test the model | ||
| trainer = pl.Trainer(logger=wandb_logger) | ||
| trainer.test(model, dataloaders=data_loder) | ||
|
|
||
| wandb_logger.experiment.config.update({ | ||
| "split_name": split_name, | ||
| "model_name": model_path.name, | ||
| "subset_name": subset_name | ||
| }) | ||
| wandb_logger.experiment.finish() | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A gdzie podajemy liczbę cech na wejście sieci?