code added
This commit is contained in:
parent
1ece2081db
commit
b67569536f
201
LICENSE
Normal file
201
LICENSE
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
@ -1,3 +1,6 @@
|
|||||||
# AI-Tech-WKO-Projekt
|
# Flats datasets
|
||||||
|
## Struktura
|
||||||
|
Surowe pliki ze zdjęciami nie są trzymane w repozytorium.
|
||||||
|
|
||||||
Repozytorium do projektu z przedmiotu 'Widzenie komputerowe'
|
Przy pierwszym użyciu surowe dane należy umieścić w katalogu `images/raw`, które później będą
|
||||||
|
preprocesowane przez skrypty i umieszczone odpowiedno w `images/test` i `images/train`.
|
BIN
data/.DS_Store
vendored
Normal file
BIN
data/.DS_Store
vendored
Normal file
Binary file not shown.
0
data/__init__.py
Normal file
0
data/__init__.py
Normal file
BIN
data/images/.DS_Store
vendored
Normal file
BIN
data/images/.DS_Store
vendored
Normal file
Binary file not shown.
0
data/images/raw/.keepdir
Normal file
0
data/images/raw/.keepdir
Normal file
0
data/images/test/.keepdir
Normal file
0
data/images/test/.keepdir
Normal file
0
data/images/train/.keepdir
Normal file
0
data/images/train/.keepdir
Normal file
117
data/loaders.py
Normal file
117
data/loaders.py
Normal file
@ -0,0 +1,117 @@
|
|||||||
|
import os
|
||||||
|
from abc import ABC
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
import cv2 as cv
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from skimage.io import imread
|
||||||
|
from sklearn.preprocessing import LabelEncoder
|
||||||
|
from torch.utils.data import Dataset, DataLoader
|
||||||
|
from torchvision.transforms import transforms
|
||||||
|
|
||||||
|
|
||||||
|
def _load_data(input_dir: str, new_size: int | None = None):
|
||||||
|
image_dir = Path(input_dir)
|
||||||
|
categories_name = {}
|
||||||
|
i = 0
|
||||||
|
for file in os.listdir(image_dir):
|
||||||
|
directory = os.path.join(image_dir, file)
|
||||||
|
if os.path.isdir(directory):
|
||||||
|
categories_name[i] = file
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
folders = [directory for directory in image_dir.iterdir() if directory.is_dir()]
|
||||||
|
|
||||||
|
train_img = []
|
||||||
|
categories_count = len(folders)
|
||||||
|
labels = []
|
||||||
|
for directory in folders:
|
||||||
|
count = 0
|
||||||
|
for obj in directory.iterdir():
|
||||||
|
try:
|
||||||
|
img = imread(obj)
|
||||||
|
if new_size is not None:
|
||||||
|
img = cv.resize(img, (new_size, new_size), interpolation=cv.INTER_AREA)
|
||||||
|
img = img / 255
|
||||||
|
train_img.append(img)
|
||||||
|
labels.append(os.path.basename(os.path.normpath(directory)))
|
||||||
|
count += 1
|
||||||
|
except ValueError:
|
||||||
|
# This can happen when a file is broken, so let's omit it.
|
||||||
|
print(f'Broken file: {obj}')
|
||||||
|
return {
|
||||||
|
"values": np.array(train_img),
|
||||||
|
"categories_count": categories_count,
|
||||||
|
"labels": labels,
|
||||||
|
"categories_name": categories_name
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FlatsDataset(Dataset):
|
||||||
|
def __init__(self, data, device):
|
||||||
|
self.device = device
|
||||||
|
self.x = []
|
||||||
|
for d in data['values']:
|
||||||
|
self.x.append(transforms.ToTensor()(d))
|
||||||
|
self.y = torch.LongTensor(LabelEncoder().fit_transform(data['labels']))
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.x)
|
||||||
|
|
||||||
|
def __getitem__(self, ind):
|
||||||
|
return self.x[ind], self.y[ind]
|
||||||
|
|
||||||
|
|
||||||
|
class FlatsDatasetLoader(Dataset, ABC):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
images_dir: str,
|
||||||
|
resize_to: int or None = None,
|
||||||
|
batch_size: int = 512,
|
||||||
|
device: str = 'cpu',
|
||||||
|
file_loader: Callable[[str, int or None], dict] = _load_data
|
||||||
|
):
|
||||||
|
self.images_dir = images_dir
|
||||||
|
self.resize_to = resize_to
|
||||||
|
self.batch_size = batch_size
|
||||||
|
self.device = device
|
||||||
|
self.loader = file_loader
|
||||||
|
self.train_loader = None
|
||||||
|
self.test_loader = None
|
||||||
|
self.classes_count = 0
|
||||||
|
self.label_names = {}
|
||||||
|
|
||||||
|
def load(self, verbose: bool = True):
|
||||||
|
test_dir = os.path.join(self.images_dir, 'test')
|
||||||
|
train_dir = os.path.join(self.images_dir, 'train')
|
||||||
|
|
||||||
|
if verbose:
|
||||||
|
print('Loading dataset from files...')
|
||||||
|
test_raw = self.loader(test_dir, self.resize_to)
|
||||||
|
train_raw = self.loader(train_dir, self.resize_to)
|
||||||
|
|
||||||
|
self.classes_count = test_raw['categories_count']
|
||||||
|
self.label_names = test_raw['categories_name']
|
||||||
|
if verbose:
|
||||||
|
print('Done. Creating PyTorch datasets...')
|
||||||
|
train_set = FlatsDataset(train_raw, self.device)
|
||||||
|
test_set = FlatsDataset(test_raw, self.device)
|
||||||
|
|
||||||
|
self.train_loader = DataLoader(train_set, batch_size=self.batch_size, shuffle=True)
|
||||||
|
self.test_loader = DataLoader(test_set, batch_size=self.batch_size, shuffle=False)
|
||||||
|
if verbose:
|
||||||
|
print('Done.')
|
||||||
|
|
||||||
|
def get_train_loader(self) -> DataLoader:
|
||||||
|
return self.train_loader
|
||||||
|
|
||||||
|
def get_test_loader(self) -> DataLoader:
|
||||||
|
return self.test_loader
|
||||||
|
|
||||||
|
def get_label_names(self) -> dict:
|
||||||
|
return self.label_names
|
||||||
|
|
||||||
|
def get_classes_count(self) -> int:
|
||||||
|
return self.classes_count
|
58
data/prepare_alpha_dataset.py
Normal file
58
data/prepare_alpha_dataset.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def mkdir_if_not_exists(path):
|
||||||
|
try:
|
||||||
|
os.mkdir(path)
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def bulk_copy(file_names: list[str], input_dir, output):
|
||||||
|
for i, file in enumerate(file_names):
|
||||||
|
shutil.copy(
|
||||||
|
os.path.join(input_dir, file), os.path.join(output, str(i) + '.' + file.split('.')[1])
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def split_houzz_dataset(
|
||||||
|
raw_path: str,
|
||||||
|
train_out_folder: str,
|
||||||
|
test_out_folder: str,
|
||||||
|
train_test_ratio: float = 0.8
|
||||||
|
):
|
||||||
|
image_dir = Path(raw_path)
|
||||||
|
|
||||||
|
classes = []
|
||||||
|
for maybe_dir in os.listdir(image_dir):
|
||||||
|
class_dir = os.path.join(image_dir, maybe_dir)
|
||||||
|
if os.path.isdir(class_dir):
|
||||||
|
classes.append(maybe_dir)
|
||||||
|
|
||||||
|
print(f'Found {len(classes)} classes')
|
||||||
|
for cls in classes:
|
||||||
|
mkdir_if_not_exists(os.path.join(train_out_folder, str(cls)))
|
||||||
|
mkdir_if_not_exists(os.path.join(test_out_folder, str(cls)))
|
||||||
|
|
||||||
|
raw_folders = [directory for directory in image_dir.iterdir() if directory.is_dir()]
|
||||||
|
for raw_directory, cls in zip(raw_folders, classes):
|
||||||
|
raw_files = os.listdir(raw_directory)
|
||||||
|
print(f'{raw_directory}: {len(raw_files)}')
|
||||||
|
split_point = round(len(raw_files) * train_test_ratio)
|
||||||
|
train_files = raw_files[:split_point]
|
||||||
|
print(f'\tTrain files: {len(train_files)}')
|
||||||
|
test_files = raw_files[split_point + 1:]
|
||||||
|
print(f'\tTest files: {len(test_files)}')
|
||||||
|
print('Copying... ', end='')
|
||||||
|
bulk_copy(test_files, raw_directory, os.path.join(TEST_OUTPUT, str(cls)))
|
||||||
|
bulk_copy(train_files, raw_directory, os.path.join(TRAIN_OUTPUT, str(cls)))
|
||||||
|
print('Done.')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
HOUZZ_DATASET_PATH = 'images/raw/houzz'
|
||||||
|
TRAIN_OUTPUT = 'images/train'
|
||||||
|
TEST_OUTPUT = 'images/test'
|
||||||
|
split_houzz_dataset(HOUZZ_DATASET_PATH, TRAIN_OUTPUT, TEST_OUTPUT)
|
0
experiments/__init__.py
Normal file
0
experiments/__init__.py
Normal file
76
experiments/inference.py
Normal file
76
experiments/inference.py
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
import argparse
|
||||||
|
|
||||||
|
import cv2 as cv
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch import nn
|
||||||
|
from torch.utils.data import DataLoader
|
||||||
|
from torchvision.transforms import transforms
|
||||||
|
|
||||||
|
|
||||||
|
def infer(data, network, loss_fn, device_type):
|
||||||
|
x_cpu, y_cpu = data
|
||||||
|
x = x_cpu.to(device_type).float()
|
||||||
|
y = y_cpu.to(device_type).long()
|
||||||
|
output = network(x)
|
||||||
|
loss = loss_fn(output, y)
|
||||||
|
return output, loss
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(
|
||||||
|
network: nn.Module,
|
||||||
|
test_data: DataLoader,
|
||||||
|
loss_fn,
|
||||||
|
device_type: str
|
||||||
|
) -> [np.ndarray, np.ndarray, list[float]]:
|
||||||
|
"""
|
||||||
|
Test a given model and return true, predicted values and loss
|
||||||
|
"""
|
||||||
|
network.eval()
|
||||||
|
preds, losses = np.array([]), []
|
||||||
|
trues = np.array([])
|
||||||
|
with torch.no_grad():
|
||||||
|
for data in test_data:
|
||||||
|
output, loss = infer(data, network, loss_fn, device_type)
|
||||||
|
trues = np.concatenate((trues, data[1].data.numpy()))
|
||||||
|
preds = np.concatenate(
|
||||||
|
(preds, torch.nn.functional.softmax(output, dim=1)
|
||||||
|
.cpu()
|
||||||
|
.data
|
||||||
|
.numpy()
|
||||||
|
.argmax(axis=1))
|
||||||
|
)
|
||||||
|
losses.append(loss.item())
|
||||||
|
return trues, preds, losses
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Load a model and run inference on a source image")
|
||||||
|
parser.add_argument(
|
||||||
|
"-m", "--model", required=True, type=str, help="path to a pickled model to load"
|
||||||
|
)
|
||||||
|
parser.add_argument \
|
||||||
|
("-i", "--image", required=True, type=str, help="path to an image to load"
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
model = torch.load(args.model)
|
||||||
|
image = cv.imread(args.image)
|
||||||
|
image = image / 255
|
||||||
|
processed = transforms.ToTensor()(image).to(device)
|
||||||
|
predicted = model(processed.float().unsqueeze(0))
|
||||||
|
labels = {
|
||||||
|
'0': 'ArtDeco',
|
||||||
|
'1': 'Classic',
|
||||||
|
'2': 'Glamour',
|
||||||
|
'3': 'Industrial',
|
||||||
|
'4': 'Minimalistic',
|
||||||
|
'5': 'Modern',
|
||||||
|
'6': 'Rustic',
|
||||||
|
'7': 'Scandinavian',
|
||||||
|
'8': 'Vintage',
|
||||||
|
}
|
||||||
|
print(labels[str(
|
||||||
|
torch.nn.functional.softmax(predicted, dim=1).cpu().data.numpy().argmax(axis=1)[0]
|
||||||
|
)])
|
35
experiments/metrics.py
Normal file
35
experiments/metrics.py
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
from statistics import mean
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
|
||||||
|
|
||||||
|
|
||||||
|
class Metrics:
|
||||||
|
def __init__(self):
|
||||||
|
self.loss = []
|
||||||
|
self.accuracy = []
|
||||||
|
self.precision = []
|
||||||
|
self.recall = []
|
||||||
|
self.f_score = []
|
||||||
|
|
||||||
|
def add_new(self, preds: np.ndarray, trues: np.ndarray, losses: list[float]):
|
||||||
|
self.loss.append(mean(losses))
|
||||||
|
precision, recall, f_scr, _ = precision_recall_fscore_support(
|
||||||
|
trues,
|
||||||
|
preds,
|
||||||
|
average='weighted',
|
||||||
|
zero_division=1
|
||||||
|
)
|
||||||
|
self.precision.append(precision)
|
||||||
|
self.recall.append(recall)
|
||||||
|
self.f_score.append(f_scr)
|
||||||
|
self.accuracy.append(accuracy_score(trues, preds))
|
||||||
|
|
||||||
|
def as_dict(self):
|
||||||
|
return {
|
||||||
|
"loss": self.loss,
|
||||||
|
"acc": self.accuracy,
|
||||||
|
"precision": self.precision,
|
||||||
|
"recall": self.recall,
|
||||||
|
"f": self.f_score
|
||||||
|
}
|
259
experiments/model_alpha.ipynb
Normal file
259
experiments/model_alpha.ipynb
Normal file
File diff suppressed because one or more lines are too long
0
experiments/models/.keepdir
Normal file
0
experiments/models/.keepdir
Normal file
107
experiments/plots.py
Normal file
107
experiments/plots.py
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
import seaborn as sns
|
||||||
|
from torch.utils.data import Dataset
|
||||||
|
from torchvision.transforms import ToPILImage
|
||||||
|
|
||||||
|
import metrics
|
||||||
|
|
||||||
|
|
||||||
|
def plot_metrics(
|
||||||
|
title: str,
|
||||||
|
test_metrics: metrics.Metrics,
|
||||||
|
train_metrics: metrics.Metrics,
|
||||||
|
n_epochs: int,
|
||||||
|
time: int,
|
||||||
|
image_size: int,
|
||||||
|
device: str = 'cpu'
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Shows a plot from collected metrics
|
||||||
|
:param title: Plot title
|
||||||
|
:param test_metrics: A dict of keyed metric scores with arrays as values.
|
||||||
|
Each metric should have the same # of items.
|
||||||
|
Keys:
|
||||||
|
- l - losses
|
||||||
|
- a - accuracy scores
|
||||||
|
- p - precision scores
|
||||||
|
- r - recall scores
|
||||||
|
- f - f scores
|
||||||
|
:param train_metrics: A dict of keyed metric scores with arrays as values.
|
||||||
|
See `test_metrics` for details
|
||||||
|
:param n_epochs:
|
||||||
|
:param time: Time taken to train the model in seconds
|
||||||
|
:param image_size: A number corresponding to the size of images used to train the model
|
||||||
|
:param device: What was used to train the model
|
||||||
|
:return:
|
||||||
|
"""
|
||||||
|
plt.style.use('classic')
|
||||||
|
sns.set()
|
||||||
|
|
||||||
|
fig, axis = plt.subplot_mosaic([['l', 'l'],
|
||||||
|
['a', 'p'],
|
||||||
|
['r', 'f']],
|
||||||
|
constrained_layout=True, figsize=(10, 10))
|
||||||
|
axis['l'].plot(test_metrics.loss)
|
||||||
|
axis['l'].plot(train_metrics.loss)
|
||||||
|
axis['l'].set_yscale('log')
|
||||||
|
axis['l'].set_title("Loss")
|
||||||
|
|
||||||
|
axis['a'].plot(test_metrics.accuracy)
|
||||||
|
axis['a'].plot(train_metrics.accuracy)
|
||||||
|
axis['a'].set_title("Accuracy")
|
||||||
|
|
||||||
|
axis['p'].plot(test_metrics.precision)
|
||||||
|
axis['p'].plot(train_metrics.precision)
|
||||||
|
axis['p'].set_title("Precision")
|
||||||
|
|
||||||
|
axis['r'].plot(test_metrics.recall)
|
||||||
|
axis['r'].plot(train_metrics.recall)
|
||||||
|
axis['r'].set_title("Recall")
|
||||||
|
|
||||||
|
axis['f'].plot(test_metrics.f_score)
|
||||||
|
axis['f'].plot(train_metrics.f_score)
|
||||||
|
axis['f'].set_title("F-score")
|
||||||
|
fig.tight_layout()
|
||||||
|
fig.subplots_adjust(top=0.90, bottom=0.05)
|
||||||
|
fig.suptitle(title, fontsize=24)
|
||||||
|
fig.legend(axis, labels=['test', 'train'], loc="lower center")
|
||||||
|
|
||||||
|
plt.text(0.30, 0.93,
|
||||||
|
f'{device}, {image_size}x{image_size}, {n_epochs} iteracji, czas treningu: '
|
||||||
|
f'{str(timedelta(seconds=time)).split(".", maxsplit=1)[0]}',
|
||||||
|
fontsize=14,
|
||||||
|
transform=plt.gcf().transFigure)
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
|
||||||
|
def show_missclassified(
|
||||||
|
dataset: Dataset,
|
||||||
|
preds: np.ndarray,
|
||||||
|
label_names: dict,
|
||||||
|
count_per_class: int = 5
|
||||||
|
):
|
||||||
|
results = {}
|
||||||
|
for i in label_names.keys():
|
||||||
|
results[i] = []
|
||||||
|
|
||||||
|
indexes = np.random.permutation(len(preds))
|
||||||
|
for i in indexes:
|
||||||
|
pred = preds[i]
|
||||||
|
image_tensor, true = dataset[i]
|
||||||
|
if len(results[pred]) < count_per_class and pred != int(true):
|
||||||
|
results[pred].append({
|
||||||
|
"image": ToPILImage()(image_tensor),
|
||||||
|
"actual": int(true)
|
||||||
|
})
|
||||||
|
sns.reset_orig()
|
||||||
|
plt.figure(figsize=[20, 30])
|
||||||
|
for row, (label, images) in enumerate(results.items()):
|
||||||
|
for i, image in enumerate(images):
|
||||||
|
plt.subplot(len(label_names.keys()), count_per_class, row * count_per_class + i + 1)
|
||||||
|
plt.imshow(image["image"], interpolation="bicubic")
|
||||||
|
plt.title(f'{label_names[label]}, expected {label_names[image["actual"]]}')
|
||||||
|
plt.axis('off')
|
||||||
|
plt.show()
|
Loading…
Reference in New Issue
Block a user