aaa-ml-datasets-course 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- aaa_ml_datasets_course-1.0.0/LICENSE +201 -0
- aaa_ml_datasets_course-1.0.0/PKG-INFO +30 -0
- aaa_ml_datasets_course-1.0.0/heuristics/active_learning.py +111 -0
- aaa_ml_datasets_course-1.0.0/heuristics/heuristics.py +110 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/classifier.py +59 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/dataset.py +81 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/metrics.py +43 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/settings.py +39 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/trainer.py +258 -0
- aaa_ml_datasets_course-1.0.0/heuristics/model/utils.py +144 -0
- aaa_ml_datasets_course-1.0.0/pyproject.toml +41 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: aaa-ml-datasets-course
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Репозиторий курса по созданию датасетов Академии Аналитиков Авито
|
|
5
|
+
Author: Avito
|
|
6
|
+
Requires-Python: >=3.10,<3.13
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Requires-Dist: dotenv (==0.9.9)
|
|
12
|
+
Requires-Dist: ipykernel (==6.29.4)
|
|
13
|
+
Requires-Dist: ipywidgets (==8.1.6)
|
|
14
|
+
Requires-Dist: matplotlib (==3.8.4)
|
|
15
|
+
Requires-Dist: nltk (==3.8.1)
|
|
16
|
+
Requires-Dist: notebook (==7.4.1)
|
|
17
|
+
Requires-Dist: numpy (==1.26.4)
|
|
18
|
+
Requires-Dist: opencv-python (==4.9.0.80)
|
|
19
|
+
Requires-Dist: pandas (==2.2.3)
|
|
20
|
+
Requires-Dist: protobuf (==4.25.3)
|
|
21
|
+
Requires-Dist: scikit-learn (==1.4.2)
|
|
22
|
+
Requires-Dist: scipy (==1.13.1)
|
|
23
|
+
Requires-Dist: seaborn (==0.13.2)
|
|
24
|
+
Requires-Dist: tensorboard (==2.16.2)
|
|
25
|
+
Requires-Dist: together (==1.4.6)
|
|
26
|
+
Requires-Dist: toloka-kit (==1.2.1)
|
|
27
|
+
Requires-Dist: torch (==2.2.2)
|
|
28
|
+
Requires-Dist: torchvision (==0.17.2)
|
|
29
|
+
Requires-Dist: tqdm (==4.67.1)
|
|
30
|
+
Requires-Dist: transformers (==4.39.3)
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
import numpy as np
|
|
3
|
+
from typing import Tuple, List, Dict
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_num_samples_per_class(class_counts: Dict, sample_size: int) -> Dict[int, int]:
|
|
7
|
+
"""
|
|
8
|
+
Принимает на вход словарь class_id -> class_count
|
|
9
|
+
Возвращает словарь class_id -> sample_size
|
|
10
|
+
так как не во всех классах есть хотя бы sample_size // n_classes примеров,
|
|
11
|
+
то основной смысл функции сделать выборку равномернее и добрать
|
|
12
|
+
примеров из более многочисленных классов
|
|
13
|
+
Args:
|
|
14
|
+
class_counts: словарь с кол-во примеров в выборке по каждому
|
|
15
|
+
классу {0:100, 1: 234, ..., 19: 33}
|
|
16
|
+
sample_size: итоговый размер семпла который хочется получить
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
|
|
20
|
+
"""
|
|
21
|
+
class_counts_rest = class_counts.copy()
|
|
22
|
+
|
|
23
|
+
n_classes = len(class_counts)
|
|
24
|
+
sample_size_per_target = sample_size // n_classes
|
|
25
|
+
|
|
26
|
+
class_to_sample_size = {}
|
|
27
|
+
current_sample_size = sample_size_per_target
|
|
28
|
+
ready_targets = []
|
|
29
|
+
|
|
30
|
+
while True:
|
|
31
|
+
values = [target for target, count in class_counts_rest.items() if
|
|
32
|
+
count <= current_sample_size]
|
|
33
|
+
if len(values) > 0:
|
|
34
|
+
ready_targets += values
|
|
35
|
+
for value in values:
|
|
36
|
+
class_to_sample_size[value] = class_counts_rest.pop(value)
|
|
37
|
+
if n_classes == len(ready_targets):
|
|
38
|
+
break
|
|
39
|
+
current_sample_size = (sample_size - sum(class_to_sample_size.values())) // (
|
|
40
|
+
n_classes - len(ready_targets)
|
|
41
|
+
)
|
|
42
|
+
else:
|
|
43
|
+
for target in class_counts_rest.keys():
|
|
44
|
+
class_to_sample_size[target] = current_sample_size
|
|
45
|
+
class_counts_rest[target] -= current_sample_size
|
|
46
|
+
|
|
47
|
+
break
|
|
48
|
+
|
|
49
|
+
s = sum(class_to_sample_size.values())
|
|
50
|
+
for target, count in class_counts_rest.items():
|
|
51
|
+
if s >= sample_size:
|
|
52
|
+
break
|
|
53
|
+
if count > 0:
|
|
54
|
+
class_to_sample_size[target] += 1
|
|
55
|
+
s += 1
|
|
56
|
+
|
|
57
|
+
return class_to_sample_size
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def max_min_with_diversity(probas: np.ndarray, sample_size: int) -> Tuple[List, Dict]:
|
|
61
|
+
"""
|
|
62
|
+
Семплирование примеров, где самый вероятный класс имеет
|
|
63
|
+
наименьшую вероятность среди остальных примеров
|
|
64
|
+
Args:
|
|
65
|
+
probas: матрица NxC - вероятности по всем классам C -(кол-во классов)
|
|
66
|
+
sample_size: размер итогового семпла
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
|
|
70
|
+
"""
|
|
71
|
+
class_counts = Counter(probas.argmax(axis=1))
|
|
72
|
+
sample_size_per_target = get_num_samples_per_class(class_counts, sample_size)
|
|
73
|
+
|
|
74
|
+
indexes = []
|
|
75
|
+
|
|
76
|
+
for target, sample_size in sample_size_per_target.items():
|
|
77
|
+
target_indexes = np.argwhere(probas.argmax(axis=1) == target)[:, 0]
|
|
78
|
+
max_probas = probas[target_indexes, :].max(axis=1)
|
|
79
|
+
|
|
80
|
+
max_indexes = np.argsort(max_probas)[:sample_size]
|
|
81
|
+
|
|
82
|
+
indexes += list(target_indexes[max_indexes])
|
|
83
|
+
|
|
84
|
+
return indexes, sample_size_per_target
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def margin_with_diversity(probas: np.ndarray, sample_size: int) -> Tuple[List, Dict]:
|
|
88
|
+
"""
|
|
89
|
+
Семплирование примеров где модель сомневается между 2 классами
|
|
90
|
+
Args:
|
|
91
|
+
probas: матрица NxC - вероятности по всем классам C -(кол-во классов)
|
|
92
|
+
sample_size: размер итогового семпла
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
|
|
96
|
+
"""
|
|
97
|
+
class_counts = Counter(probas.argmax(axis=1))
|
|
98
|
+
sample_size_per_target = get_num_samples_per_class(class_counts, sample_size)
|
|
99
|
+
|
|
100
|
+
indexes = []
|
|
101
|
+
|
|
102
|
+
for target, sample_size in sample_size_per_target.items():
|
|
103
|
+
target_indexes = np.argwhere(probas.argmax(axis=1) == target)[:, 0]
|
|
104
|
+
probas_sorted = np.sort(probas[target_indexes, :], axis=1)
|
|
105
|
+
margin = probas_sorted[:, -1] - probas_sorted[:, -2]
|
|
106
|
+
|
|
107
|
+
margin_indexes = np.argsort(margin)[:sample_size]
|
|
108
|
+
|
|
109
|
+
indexes += list(target_indexes[margin_indexes])
|
|
110
|
+
|
|
111
|
+
return indexes, sample_size_per_target
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from typing import List, Tuple, Union
|
|
3
|
+
import cv2
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import re
|
|
6
|
+
from PIL import Image
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def order_points(points: np.ndarray) -> np.ndarray:
|
|
10
|
+
"""
|
|
11
|
+
Упорядочивает точки по часовой стрелке.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
points: набор точек (n, 2)
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
Упорядоченный набор точек (n, 2)
|
|
18
|
+
|
|
19
|
+
"""
|
|
20
|
+
if len(points.shape) != 2 and points.shape[0] == 0 and points.shape[1] != 2:
|
|
21
|
+
raise ValueError('points: набор точек (n, 2)')
|
|
22
|
+
|
|
23
|
+
center = points.mean(axis=0)
|
|
24
|
+
points = np.array(
|
|
25
|
+
sorted(
|
|
26
|
+
points,
|
|
27
|
+
key=lambda point: np.arctan2(point[1] - center[1], point[0] - center[0]),
|
|
28
|
+
),
|
|
29
|
+
dtype=np.float32,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
points_sort_x = sorted(points, key=lambda point: point[0])[:2]
|
|
33
|
+
point_sort_x_y = sorted(points_sort_x, key=lambda point: point[1])[0]
|
|
34
|
+
ind = [
|
|
35
|
+
ind for ind, point in enumerate(points) \
|
|
36
|
+
if point[0] == point_sort_x_y[0] and point[1] == point_sort_x_y[1]
|
|
37
|
+
][0]
|
|
38
|
+
|
|
39
|
+
points = np.concatenate([points[ind:], points[:ind]]).astype(np.float32)
|
|
40
|
+
|
|
41
|
+
return points
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def image_average_color(image: np.array) -> np.array:
|
|
45
|
+
average_color_row = np.average(image, axis=0)
|
|
46
|
+
average_color = np.average(average_color_row, axis=0)
|
|
47
|
+
|
|
48
|
+
return average_color
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def catalog_flag(
|
|
52
|
+
image: Union[np.array, str],
|
|
53
|
+
crop_coord: List[float],
|
|
54
|
+
fill_color: Tuple[int, int, int] = (255, 255, 255),
|
|
55
|
+
threshold: float = 247.0,
|
|
56
|
+
):
|
|
57
|
+
if isinstance(image, str):
|
|
58
|
+
image = Image.open(image)
|
|
59
|
+
image = np.array(image)
|
|
60
|
+
|
|
61
|
+
points = order_points(np.array(crop_coord).reshape(-1, 2)) * np.array(
|
|
62
|
+
[image.shape[1], image.shape[0]]
|
|
63
|
+
)
|
|
64
|
+
result_image = cv2.rectangle(
|
|
65
|
+
image,
|
|
66
|
+
(int(points[0][0]), int(points[0][1])),
|
|
67
|
+
(int(points[1][0] + 0.5), int(points[1][1] + 0.5)),
|
|
68
|
+
fill_color,
|
|
69
|
+
-1,
|
|
70
|
+
)
|
|
71
|
+
average_color = image_average_color(result_image)
|
|
72
|
+
|
|
73
|
+
return all(average_color >= threshold)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_text_patterns(
|
|
77
|
+
text: str, include_re: List[re.Pattern], exclude_re: List[re.Pattern] = None
|
|
78
|
+
):
|
|
79
|
+
text = text.lower()
|
|
80
|
+
if not exclude_re:
|
|
81
|
+
return int(any([pattern.findall(text) for pattern in include_re]))
|
|
82
|
+
return int(
|
|
83
|
+
all(
|
|
84
|
+
[
|
|
85
|
+
any([pattern.findall(text) for pattern in include_re]),
|
|
86
|
+
not any([pattern.findall(text) for pattern in exclude_re]),
|
|
87
|
+
]
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def calculate_text_heuristics(
|
|
93
|
+
title_desc_df: pd.DataFrame, include_re: List[re.Pattern], exclude_re: List[re.Pattern] = None
|
|
94
|
+
):
|
|
95
|
+
title_desc_df['title_match'] = title_desc_df['title'].apply(
|
|
96
|
+
lambda x: find_text_patterns(
|
|
97
|
+
text=x,
|
|
98
|
+
include_re=include_re,
|
|
99
|
+
exclude_re=exclude_re,
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
title_desc_df['description_match'] = title_desc_df['description'].apply(
|
|
103
|
+
lambda x: find_text_patterns(
|
|
104
|
+
text=x,
|
|
105
|
+
include_re=include_re,
|
|
106
|
+
exclude_re=exclude_re,
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return title_desc_df
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Dict, Optional
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
from torch import nn
|
|
6
|
+
from torchvision.models import (
|
|
7
|
+
resnet18,
|
|
8
|
+
resnet34,
|
|
9
|
+
resnet101,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from .settings import NUM_CLASSES
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BaseModel(nn.Module):
|
|
16
|
+
def __init__(self, num_classes=NUM_CLASSES):
|
|
17
|
+
super().__init__()
|
|
18
|
+
self.feature_extractor = None
|
|
19
|
+
self.clf = None
|
|
20
|
+
self.num_classes = num_classes
|
|
21
|
+
|
|
22
|
+
def get_model_saving_params(self):
|
|
23
|
+
model_params = {'num_classes': self.num_classes}
|
|
24
|
+
return model_params
|
|
25
|
+
|
|
26
|
+
def save_pretrained(self, model_path: str, meta_info: Optional[Dict] = None):
|
|
27
|
+
self.cpu()
|
|
28
|
+
meta_info = meta_info or {}
|
|
29
|
+
meta_info['model_state'] = self.feature_extractor.state_dict()
|
|
30
|
+
meta_info['model_params'] = self.get_model_saving_params()
|
|
31
|
+
|
|
32
|
+
os.makedirs(os.path.dirname(model_path), exist_ok=True)
|
|
33
|
+
torch.save(meta_info, model_path)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_pretrained(cls, model_path):
|
|
37
|
+
model_state = torch.load(model_path)
|
|
38
|
+
instance = cls(**model_state.pop('model_params'))
|
|
39
|
+
instance.feature_extractor.load_state_dict(model_state.pop('model_state'))
|
|
40
|
+
|
|
41
|
+
instance.eval()
|
|
42
|
+
|
|
43
|
+
return instance, model_state
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RoomModel(BaseModel):
|
|
47
|
+
def __init__(self, num_classes=NUM_CLASSES):
|
|
48
|
+
super().__init__(num_classes)
|
|
49
|
+
self.feature_extractor = resnet18(pretrained=True)
|
|
50
|
+
# без послденего слоя
|
|
51
|
+
# self.feature_extractor = torch.nn.Sequential(*(list(feature_extractor.children())[:-1]))
|
|
52
|
+
self.feature_extractor.fc = nn.Linear(
|
|
53
|
+
self.feature_extractor.fc.in_features, out_features=num_classes
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def forward(self, batch):
|
|
57
|
+
out = self.feature_extractor(batch)
|
|
58
|
+
|
|
59
|
+
return out
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Dict, Optional
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from PIL import Image
|
|
6
|
+
from torch.utils.data import Dataset
|
|
7
|
+
from torchvision import transforms
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TorchDataset(Dataset):
|
|
11
|
+
image_id_column: str = 'image_id_ext'
|
|
12
|
+
label_column: str = 'result'
|
|
13
|
+
img_path_column: str = 'img_path'
|
|
14
|
+
sample_weight_column: str = 'sample_weight'
|
|
15
|
+
img_extension: str = 'jpg'
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
df: pd.DataFrame,
|
|
20
|
+
image_dir: str = None,
|
|
21
|
+
transformer: Optional[transforms.transforms.Compose] = None,
|
|
22
|
+
normalize_sample_weights: bool = True,
|
|
23
|
+
with_cache=True,
|
|
24
|
+
):
|
|
25
|
+
super(TorchDataset, self).__init__()
|
|
26
|
+
self.image_dir = image_dir
|
|
27
|
+
self.df = df.reset_index(drop=True)
|
|
28
|
+
|
|
29
|
+
if normalize_sample_weights and (self.sample_weight_column in self.df.columns):
|
|
30
|
+
self.df[self.sample_weight_column] /= self.df[self.sample_weight_column].mean()
|
|
31
|
+
# self.df = self.df[self.df['result'] != -1]
|
|
32
|
+
self.transformer = transformer
|
|
33
|
+
self.image_cache = {}
|
|
34
|
+
self.with_cache = with_cache
|
|
35
|
+
|
|
36
|
+
def img_path_from_id(self, image_id):
|
|
37
|
+
path = os.path.join(self.image_dir, f'{image_id}.{self.img_extension}')
|
|
38
|
+
|
|
39
|
+
return path
|
|
40
|
+
|
|
41
|
+
def get_image_path(self, item: pd.Series):
|
|
42
|
+
if item.get(self.img_path_column) is None and item.get(self.image_id_column) is None:
|
|
43
|
+
raise ValueError('image_id or image_path should be specified')
|
|
44
|
+
image_path = item.get(self.img_path_column) or self.img_path_from_id(
|
|
45
|
+
item.get(self.image_id_column)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
return image_path
|
|
49
|
+
|
|
50
|
+
def load_img(self, idx: int, item: pd.Series):
|
|
51
|
+
# img = self.img_cache.get(idx)
|
|
52
|
+
# if img is None:
|
|
53
|
+
path = self.get_image_path(item)
|
|
54
|
+
img = Image.open(path)
|
|
55
|
+
# self.img_cache[idx] = img
|
|
56
|
+
|
|
57
|
+
return img
|
|
58
|
+
|
|
59
|
+
def __getitem__(self, idx):
|
|
60
|
+
item = self.df.iloc[idx]
|
|
61
|
+
label = int(item.get(self.label_column, 0))
|
|
62
|
+
sample_weight = float(item.get(self.sample_weight_column, 1))
|
|
63
|
+
|
|
64
|
+
img = self.image_cache.get(idx)
|
|
65
|
+
if img is None:
|
|
66
|
+
img = self.load_img(idx, item)
|
|
67
|
+
if self.transformer is not None:
|
|
68
|
+
img = self.transformer(img)
|
|
69
|
+
if self.with_cache:
|
|
70
|
+
self.image_cache[idx] = img
|
|
71
|
+
|
|
72
|
+
# item = {
|
|
73
|
+
# 'img': img,
|
|
74
|
+
# 'label': item_series['result'],
|
|
75
|
+
# 'label_name': item_series['label']
|
|
76
|
+
# }
|
|
77
|
+
|
|
78
|
+
return img, label, sample_weight
|
|
79
|
+
|
|
80
|
+
def __len__(self):
|
|
81
|
+
return len(self.df)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
from sklearn.metrics import (
|
|
5
|
+
ConfusionMatrixDisplay,
|
|
6
|
+
accuracy_score,
|
|
7
|
+
classification_report,
|
|
8
|
+
confusion_matrix,
|
|
9
|
+
f1_score,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Metrics:
|
|
16
|
+
def __init__(self, class_mapping):
|
|
17
|
+
self.class_mapping = class_mapping
|
|
18
|
+
|
|
19
|
+
def plot_cf_matrix(self, targets, predictions):
|
|
20
|
+
labels_ordered = [item[0] for item in (Counter(targets).most_common())]
|
|
21
|
+
cm = confusion_matrix(
|
|
22
|
+
targets, predictions, labels=labels_ordered, normalize='true'
|
|
23
|
+
)
|
|
24
|
+
cm_disp = ConfusionMatrixDisplay(
|
|
25
|
+
confusion_matrix=cm,
|
|
26
|
+
display_labels=[self.class_mapping.get(label, 'None') for label in labels_ordered],
|
|
27
|
+
)
|
|
28
|
+
fig, ax = plt.subplots(figsize=(15, 15))
|
|
29
|
+
cm_disp.plot(ax=ax, xticks_rotation='vertical')
|
|
30
|
+
|
|
31
|
+
def get_accuracies_df(self, targets, predictions):
|
|
32
|
+
df = pd.DataFrame(
|
|
33
|
+
classification_report(
|
|
34
|
+
targets,
|
|
35
|
+
predictions,
|
|
36
|
+
labels=list(self.class_mapping.keys()),
|
|
37
|
+
target_names=list(self.class_mapping.values()),
|
|
38
|
+
output_dict=True,
|
|
39
|
+
zero_division=0,
|
|
40
|
+
)
|
|
41
|
+
).T.reset_index().sort_values('support', ascending=False)
|
|
42
|
+
|
|
43
|
+
return df
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from collections import namedtuple
|
|
2
|
+
|
|
3
|
+
MAX_IMG_SIZE = (1280, 960)
|
|
4
|
+
MAX_IMG_SIZE_STR = '1280x960'
|
|
5
|
+
NUM_CLASSES = 20
|
|
6
|
+
IMAGES_DIR = '/data/images/'
|
|
7
|
+
LABELS_PATH = '/app/data/labels.csv'
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
ROOM_TYPE = namedtuple('ROOM_TYPE', ['name', 'value_id', 'exclude'])
|
|
11
|
+
|
|
12
|
+
ROOM_TYPES = (
|
|
13
|
+
ROOM_TYPE('ошибка загрузки изображения', -1, True),
|
|
14
|
+
ROOM_TYPE('кухня / столовая', 0, False),
|
|
15
|
+
ROOM_TYPE('кухня-гостиная', 1, False),
|
|
16
|
+
ROOM_TYPE('универсальная комната', 2, False),
|
|
17
|
+
ROOM_TYPE('гостиная', 3, False),
|
|
18
|
+
ROOM_TYPE('спальня', 4, False),
|
|
19
|
+
ROOM_TYPE('кабинет', 5, False),
|
|
20
|
+
ROOM_TYPE('детская', 6, False),
|
|
21
|
+
ROOM_TYPE('ванная комната', 7, False),
|
|
22
|
+
ROOM_TYPE('туалет', 8, False),
|
|
23
|
+
ROOM_TYPE('совмещенный санузел', 9, False),
|
|
24
|
+
ROOM_TYPE('коридор / прихожая', 10, False),
|
|
25
|
+
ROOM_TYPE('гардеробная / кладовая / постирочная', 11, False),
|
|
26
|
+
ROOM_TYPE('балкон / лоджия', 12, False),
|
|
27
|
+
ROOM_TYPE('вид из окна / с балкона', 13, False),
|
|
28
|
+
ROOM_TYPE('дом снаружи / двор', 14, False),
|
|
29
|
+
ROOM_TYPE('подъезд / лестничная площадка', 15, False),
|
|
30
|
+
ROOM_TYPE('другое', 16, False),
|
|
31
|
+
ROOM_TYPE('предметы интерьера / быт.техника', 17, False),
|
|
32
|
+
ROOM_TYPE('не могу дать ответ / не ясно', 18, True),
|
|
33
|
+
ROOM_TYPE ('комната без мебели', 19, False),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
VALID_ROOM_TYPES = tuple(filter(lambda x: not x.exclude, ROOM_TYPES))
|
|
38
|
+
|
|
39
|
+
CLASS_NAME_MAPPING = {room_type.value_id: room_type.name for room_type in VALID_ROOM_TYPES}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from typing import (
|
|
4
|
+
Dict,
|
|
5
|
+
List,
|
|
6
|
+
Optional,
|
|
7
|
+
Tuple,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import torch
|
|
13
|
+
from sklearn.metrics import accuracy_score
|
|
14
|
+
from torch.nn.functional import softmax as torch_softmax
|
|
15
|
+
from torch.utils.data import DataLoader
|
|
16
|
+
from torch.utils.tensorboard import SummaryWriter
|
|
17
|
+
from tqdm import tqdm
|
|
18
|
+
from tqdm.notebook import tqdm as tqdm_notebook
|
|
19
|
+
|
|
20
|
+
from .classifier import RoomModel
|
|
21
|
+
from .dataset import TorchDataset
|
|
22
|
+
from .utils import get_preprocessor
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TrainerUtils:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
device='cpu',
|
|
29
|
+
tensorboard_dir: Optional[str] = None,
|
|
30
|
+
experiment_tag: Optional[str] = None,
|
|
31
|
+
run_in_notebook=True,
|
|
32
|
+
model_checkpoint_path: str = '/app/data/models/',
|
|
33
|
+
):
|
|
34
|
+
self.device: str = device
|
|
35
|
+
self.loss_fn = torch.nn.CrossEntropyLoss(reduction='none')
|
|
36
|
+
self._global_steps_num = 0
|
|
37
|
+
self.tensorboard: Optional[SummaryWriter] = None
|
|
38
|
+
if tensorboard_dir is not None:
|
|
39
|
+
if experiment_tag is not None:
|
|
40
|
+
tensorboard_dir = os.path.join(tensorboard_dir, experiment_tag)
|
|
41
|
+
self.tensorboard = SummaryWriter(tensorboard_dir)
|
|
42
|
+
self.run_in_notebook = run_in_notebook
|
|
43
|
+
self.best_score: float = 0
|
|
44
|
+
self.best_epoch: int = -1
|
|
45
|
+
self.accuracies: List[float] = []
|
|
46
|
+
self.checkpoint_path: str = os.path.join(model_checkpoint_path, f'model_{experiment_tag}')
|
|
47
|
+
|
|
48
|
+
def get_progress_bar(self, epoch_len):
|
|
49
|
+
if self.run_in_notebook:
|
|
50
|
+
pbar = tqdm_notebook(total=epoch_len)
|
|
51
|
+
else:
|
|
52
|
+
pbar = tqdm(total=epoch_len)
|
|
53
|
+
|
|
54
|
+
return pbar
|
|
55
|
+
|
|
56
|
+
def log_metrics_loss(self, loss, name, step):
|
|
57
|
+
self.tensorboard.add_scalar(f'Loss/{name}', loss, step)
|
|
58
|
+
|
|
59
|
+
def log_metrics_accuracy(self, accuracy, name, step):
|
|
60
|
+
self.tensorboard.add_scalar(f'Accuracy/{name}', accuracy, step)
|
|
61
|
+
|
|
62
|
+
def do_checkpoint(
|
|
63
|
+
self,
|
|
64
|
+
epoch: int,
|
|
65
|
+
score: float,
|
|
66
|
+
model,
|
|
67
|
+
accuracy_df: pd.DataFrame = None
|
|
68
|
+
):
|
|
69
|
+
self.accuracies.append(score)
|
|
70
|
+
better_than_previous = score > self.best_score
|
|
71
|
+
|
|
72
|
+
if accuracy_df is not None:
|
|
73
|
+
f1_score = accuracy_df.loc[accuracy_df['index'] == 'macro avg']['f1-score'].values[0]
|
|
74
|
+
better_than_previous = f1_score > self.best_f1
|
|
75
|
+
|
|
76
|
+
if better_than_previous:
|
|
77
|
+
self.best_score = score
|
|
78
|
+
|
|
79
|
+
self.best_epoch = epoch
|
|
80
|
+
model_state = {
|
|
81
|
+
'epoch': epoch,
|
|
82
|
+
'score': score,
|
|
83
|
+
}
|
|
84
|
+
model.save_pretrained(self.checkpoint_path, model_state)
|
|
85
|
+
|
|
86
|
+
def forward_step(self, batch, model) -> Tuple[torch.Tensor, float, list, list, torch.Tensor]:
|
|
87
|
+
labels, sample_weights = batch[1], batch[2]
|
|
88
|
+
logits = model(batch[0])
|
|
89
|
+
|
|
90
|
+
loss_batch = self.loss_fn(logits, labels)
|
|
91
|
+
if sample_weights is not None:
|
|
92
|
+
loss_batch = loss_batch * sample_weights
|
|
93
|
+
|
|
94
|
+
loss = loss_batch.mean()
|
|
95
|
+
|
|
96
|
+
# loss = self.loss_fn(logits, labels)
|
|
97
|
+
logits = logits.detach().cpu()
|
|
98
|
+
labels_predicted = logits.argmax(dim=1).tolist()
|
|
99
|
+
labels = labels.detach().cpu().tolist()
|
|
100
|
+
|
|
101
|
+
accuracy = accuracy_score(labels, labels_predicted)
|
|
102
|
+
|
|
103
|
+
return loss, accuracy, labels_predicted, labels, logits
|
|
104
|
+
|
|
105
|
+
def training_step(
|
|
106
|
+
self, model, batch: List[torch.Tensor], optimizer, scheduler, grad_clipping_norm
|
|
107
|
+
):
|
|
108
|
+
model.train()
|
|
109
|
+
batch[0] = batch[0].to(self.device)
|
|
110
|
+
batch[1] = batch[1].to(self.device)
|
|
111
|
+
batch[2] = batch[2].to(self.device)
|
|
112
|
+
optimizer.zero_grad()
|
|
113
|
+
|
|
114
|
+
loss, accuracy, labels_predicted, labels, logits = self.forward_step(batch, model)
|
|
115
|
+
|
|
116
|
+
loss.backward()
|
|
117
|
+
if grad_clipping_norm is not None:
|
|
118
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clipping_norm)
|
|
119
|
+
optimizer.step()
|
|
120
|
+
if scheduler is not None:
|
|
121
|
+
scheduler.step()
|
|
122
|
+
|
|
123
|
+
return loss.item(), accuracy
|
|
124
|
+
|
|
125
|
+
def test_step(
|
|
126
|
+
self, model, batch: List[torch.Tensor]
|
|
127
|
+
) -> Tuple[float, float, list, list, torch.Tensor]:
|
|
128
|
+
model.eval()
|
|
129
|
+
batch[0] = batch[0].to(self.device)
|
|
130
|
+
batch[1] = batch[1].to(self.device)
|
|
131
|
+
batch[2] = batch[2].to(self.device)
|
|
132
|
+
with torch.no_grad():
|
|
133
|
+
loss, accuracy, labels_predicted, targets, logits = self.forward_step(batch, model)
|
|
134
|
+
|
|
135
|
+
return loss.item(), accuracy, labels_predicted, targets, logits
|
|
136
|
+
|
|
137
|
+
def training_loop(
|
|
138
|
+
self,
|
|
139
|
+
model,
|
|
140
|
+
train_dataloader,
|
|
141
|
+
val_dataloader,
|
|
142
|
+
optimizer,
|
|
143
|
+
epoch_num=1,
|
|
144
|
+
scheduler=None,
|
|
145
|
+
grad_clipping_norm=None,
|
|
146
|
+
validate_every=10,
|
|
147
|
+
verbose=True,
|
|
148
|
+
metrics_scorer=None,
|
|
149
|
+
):
|
|
150
|
+
val_loss = np.inf
|
|
151
|
+
val_accuracy = 0
|
|
152
|
+
|
|
153
|
+
epoch_len = len(train_dataloader)
|
|
154
|
+
|
|
155
|
+
for epoch in range(epoch_num):
|
|
156
|
+
iter_loader = iter(train_dataloader)
|
|
157
|
+
pbar = self.get_progress_bar(epoch_len)
|
|
158
|
+
model.to(self.device)
|
|
159
|
+
for step_number in range(epoch_len):
|
|
160
|
+
batch = next(iter_loader)
|
|
161
|
+
self._global_steps_num += 1
|
|
162
|
+
train_loss, train_accuracy = self.training_step(
|
|
163
|
+
model, batch, optimizer, scheduler, grad_clipping_norm
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
if step_number % validate_every == 0:
|
|
167
|
+
batch = next(iter(val_dataloader))
|
|
168
|
+
val_loss, val_accuracy, _, _, _ = self.test_step(model, batch)
|
|
169
|
+
if verbose:
|
|
170
|
+
pbar.update(1)
|
|
171
|
+
pbar.set_description(
|
|
172
|
+
f'train loss: {round(train_loss, 3)}, ' f'val loss: {round(val_loss, 3)}'
|
|
173
|
+
)
|
|
174
|
+
if self.tensorboard is not None and step_number % validate_every == 0:
|
|
175
|
+
self.log_metrics_loss(train_loss, 'train', self._global_steps_num)
|
|
176
|
+
self.log_metrics_loss(train_loss, 'val', self._global_steps_num)
|
|
177
|
+
self.log_metrics_accuracy(train_accuracy, 'train', self._global_steps_num)
|
|
178
|
+
self.log_metrics_accuracy(val_accuracy, 'val', self._global_steps_num)
|
|
179
|
+
|
|
180
|
+
# прогоняем модель на тесте/вале и сохраняем если она лучше по accuracy
|
|
181
|
+
predictions, _, targets, _ = self.predict(model, val_dataloader, verbose=verbose)
|
|
182
|
+
|
|
183
|
+
accuracy_df = None
|
|
184
|
+
f1_score = None
|
|
185
|
+
if metrics_scorer is not None:
|
|
186
|
+
accuracy_df = metrics_scorer.get_accuracies_df(targets, predictions)
|
|
187
|
+
f1_score = accuracy_df.loc[accuracy_df['index'] == 'macro avg'
|
|
188
|
+
]['f1-score'].values[0]
|
|
189
|
+
|
|
190
|
+
accuracy = accuracy_score(targets, predictions)
|
|
191
|
+
logging.info(f'val accuracy after epoch {epoch}: {round(accuracy, 4)}')
|
|
192
|
+
if f1_score:
|
|
193
|
+
logging.info(f'val f1_score after epoch {epoch}: {round(f1_score, 4)}')
|
|
194
|
+
|
|
195
|
+
self.do_checkpoint(epoch, f1_score or accuracy, model)
|
|
196
|
+
|
|
197
|
+
def predict(
|
|
198
|
+
self, model, dataloader, num_iterations=-1, with_all_probas=False, verbose=True,
|
|
199
|
+
) -> Tuple[List, List, List, List]:
|
|
200
|
+
predictions_all = []
|
|
201
|
+
probas_all = []
|
|
202
|
+
targets_all = []
|
|
203
|
+
all_class_probas = []
|
|
204
|
+
model.to(self.device)
|
|
205
|
+
epoch_len = len(dataloader)
|
|
206
|
+
pbar = self.get_progress_bar(epoch_len)
|
|
207
|
+
for i, batch in enumerate(dataloader):
|
|
208
|
+
_, _, predictions, targets, logits = self.test_step(model, batch)
|
|
209
|
+
soft_probas = torch_softmax(logits, dim=1)
|
|
210
|
+
probas = soft_probas.max(dim=1).values.tolist()
|
|
211
|
+
if with_all_probas:
|
|
212
|
+
all_class_probas.extend(soft_probas.tolist())
|
|
213
|
+
predictions_all.extend(predictions)
|
|
214
|
+
probas_all.extend(probas)
|
|
215
|
+
targets_all.extend(targets)
|
|
216
|
+
if verbose:
|
|
217
|
+
pbar.update(1)
|
|
218
|
+
pbar.set_description('testing')
|
|
219
|
+
if i == num_iterations:
|
|
220
|
+
break
|
|
221
|
+
|
|
222
|
+
return predictions_all, probas_all, targets_all, all_class_probas
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def predict_img_batch(
|
|
226
|
+
image_paths: Optional[List[str]] = None,
|
|
227
|
+
image_dir: Optional[str] = None,
|
|
228
|
+
batch_size: int = 32,
|
|
229
|
+
model_path: str = '/app/data/models/model_resnet18',
|
|
230
|
+
labels: Optional[List[int]] = None,
|
|
231
|
+
with_all_probas: bool = False,
|
|
232
|
+
device='cuda:0',
|
|
233
|
+
):
|
|
234
|
+
if (image_paths is None and image_dir is None) or (
|
|
235
|
+
image_paths is not None and image_dir is not None
|
|
236
|
+
):
|
|
237
|
+
raise ValueError('only one from image_paths or image_dir should be specified')
|
|
238
|
+
|
|
239
|
+
if image_dir is not None:
|
|
240
|
+
image_paths = [os.path.join(image_dir, filename) for filename in os.listdir(image_dir)]
|
|
241
|
+
|
|
242
|
+
test_df = pd.DataFrame({TorchDataset.img_path_column: image_paths})
|
|
243
|
+
|
|
244
|
+
if labels is not None:
|
|
245
|
+
test_df[TorchDataset.label_column] = labels
|
|
246
|
+
|
|
247
|
+
dataset = TorchDataset(df=test_df, transformer=get_preprocessor(), with_cache=False)
|
|
248
|
+
|
|
249
|
+
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
|
|
250
|
+
|
|
251
|
+
room_clf, _ = RoomModel.from_pretrained(model_path)
|
|
252
|
+
|
|
253
|
+
trainer = TrainerUtils(device=device)
|
|
254
|
+
predictions_all, probas_all, targets_all, all_class_probas = trainer.predict(
|
|
255
|
+
room_clf, dataloader, with_all_probas=with_all_probas
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
return predictions_all, probas_all, targets_all, all_class_probas
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import (
|
|
3
|
+
Any,
|
|
4
|
+
List,
|
|
5
|
+
Optional,
|
|
6
|
+
Tuple,
|
|
7
|
+
Union,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
import urllib
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
from collections import Counter
|
|
15
|
+
import numpy as np
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
import matplotlib.image as mpimg
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
from PIL import Image
|
|
21
|
+
from torchvision import transforms
|
|
22
|
+
from torchvision.transforms import functional as F
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
from .settings import MAX_IMG_SIZE
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PadCustom(transforms.Pad):
|
|
29
|
+
"""
|
|
30
|
+
принимает на вход до какого размера нужно заппадить,
|
|
31
|
+
а transforms.Pad на сколько нужно западдить
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def forward(self, img: Union[Image.Image, torch.Tensor]):
|
|
35
|
+
"""
|
|
36
|
+
Args:
|
|
37
|
+
img (PIL Image or Tensor): Image to be padded.
|
|
38
|
+
Returns:
|
|
39
|
+
PIL Image or Tensor: Padded image.
|
|
40
|
+
"""
|
|
41
|
+
if isinstance(img, torch.Tensor):
|
|
42
|
+
img_size = img.size()[1:]
|
|
43
|
+
else:
|
|
44
|
+
img_size = img.size
|
|
45
|
+
|
|
46
|
+
height_diff = self.padding[0] - img_size[0]
|
|
47
|
+
width_diff = self.padding[1] - img_size[1]
|
|
48
|
+
|
|
49
|
+
padding = (
|
|
50
|
+
height_diff // 2,
|
|
51
|
+
width_diff // 2,
|
|
52
|
+
height_diff // 2 + height_diff % 2,
|
|
53
|
+
width_diff // 2 + width_diff % 2,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
return F.pad(img, padding, self.fill, self.padding_mode)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_preprocessor(pad_size=MAX_IMG_SIZE):
|
|
60
|
+
preprocessor = transforms.Compose(
|
|
61
|
+
[
|
|
62
|
+
PadCustom(pad_size),
|
|
63
|
+
transforms.Resize(256),
|
|
64
|
+
transforms.CenterCrop(224),
|
|
65
|
+
transforms.ToTensor(),
|
|
66
|
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
|
67
|
+
]
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
return preprocessor
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def plot_imgs_with_labels(
|
|
74
|
+
image_paths: List[str],
|
|
75
|
+
labels_1: Tuple[List[Any], str] = None,
|
|
76
|
+
labels_2: Tuple[List[Any], str] = None,
|
|
77
|
+
labels_3: Tuple[List[Any], str] = None,
|
|
78
|
+
):
|
|
79
|
+
plt.figure(figsize=(20, 20))
|
|
80
|
+
|
|
81
|
+
n_subplots = len(image_paths)
|
|
82
|
+
n_lines = int((n_subplots + 2) // 3)
|
|
83
|
+
|
|
84
|
+
for i in range(n_subplots):
|
|
85
|
+
plt.subplot(n_lines, 3, i+1)
|
|
86
|
+
img = mpimg.imread(image_paths[i])
|
|
87
|
+
title = ''
|
|
88
|
+
if labels_1 is not None:
|
|
89
|
+
title += f'{labels_1[1]}: {labels_1[0][i]}'
|
|
90
|
+
if labels_2 is not None:
|
|
91
|
+
if isinstance(labels_2[0][i], float):
|
|
92
|
+
labels_2[0][i] = round(labels_2[0][i], 4)
|
|
93
|
+
title += f'\n{labels_2[1]}: {labels_2[0][i]}'
|
|
94
|
+
|
|
95
|
+
if labels_3 is not None:
|
|
96
|
+
if isinstance(labels_3[0][i], float):
|
|
97
|
+
labels_3[0][i] = round(labels_3[0][i], 4)
|
|
98
|
+
title += f'\n{labels_3[1]}: {labels_3[0][i]}'
|
|
99
|
+
|
|
100
|
+
plt.title(title)
|
|
101
|
+
plt.imshow(img)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def plot_sample(test_df, value='детская', column='label_pred', size=10):
|
|
105
|
+
plot_df = test_df[test_df[column] == value]
|
|
106
|
+
sample_size = min(plot_df.shape[0], size)
|
|
107
|
+
|
|
108
|
+
sample_df = plot_df.sample(sample_size).reset_index()
|
|
109
|
+
|
|
110
|
+
plot_imgs_with_labels(sample_df['img_path'],
|
|
111
|
+
(sample_df['label'], 'label'),
|
|
112
|
+
(sample_df['label_pred'], 'label_pred'),
|
|
113
|
+
(sample_df['proba'], 'proba'))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _load_images(urls, save_dir):
|
|
117
|
+
results = []
|
|
118
|
+
|
|
119
|
+
def getter(url, dest):
|
|
120
|
+
results.append(urllib.request.urlretrieve(url, dest))
|
|
121
|
+
|
|
122
|
+
os.makedirs(save_dir, exist_ok=True)
|
|
123
|
+
|
|
124
|
+
threads = []
|
|
125
|
+
for url in urls:
|
|
126
|
+
filename = os.path.split(url)[-1]
|
|
127
|
+
t = threading.Thread(target=getter, args=(url, os.path.join(save_dir, filename)))
|
|
128
|
+
t.start()
|
|
129
|
+
threads.append(t)
|
|
130
|
+
|
|
131
|
+
map(lambda t: t.join(), threads)
|
|
132
|
+
|
|
133
|
+
image_paths = [os.path.join(save_dir, os.path.split(url)[-1]) for url in urls]
|
|
134
|
+
|
|
135
|
+
return image_paths
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def load_images(urls, save_dir, max_threads_num=50):
|
|
139
|
+
image_paths = []
|
|
140
|
+
for i in range(0, len(urls), max_threads_num):
|
|
141
|
+
new_image_paths = _load_images(urls[i:i+max_threads_num], save_dir)
|
|
142
|
+
image_paths.extend(new_image_paths)
|
|
143
|
+
|
|
144
|
+
return image_paths
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "aaa-ml-datasets-course"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Репозиторий курса по созданию датасетов Академии Аналитиков Авито"
|
|
5
|
+
authors = ["Avito"]
|
|
6
|
+
|
|
7
|
+
packages = [
|
|
8
|
+
{ include = "heuristics", from = "."},
|
|
9
|
+
]
|
|
10
|
+
exclude = [
|
|
11
|
+
"**/*.ipynb",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[tool.poetry.dependencies]
|
|
15
|
+
python = ">=3.10,<3.13"
|
|
16
|
+
pandas = "2.2.3"
|
|
17
|
+
matplotlib = "3.8.4"
|
|
18
|
+
seaborn = "0.13.2"
|
|
19
|
+
scipy = "1.13.1"
|
|
20
|
+
numpy = "1.26.4"
|
|
21
|
+
scikit-learn = "1.4.2"
|
|
22
|
+
transformers = "4.39.3"
|
|
23
|
+
tensorboard = "2.16.2"
|
|
24
|
+
nltk = "3.8.1"
|
|
25
|
+
torch = "2.2.2"
|
|
26
|
+
torchvision = "0.17.2"
|
|
27
|
+
protobuf = "4.25.3"
|
|
28
|
+
opencv-python = "4.9.0.80"
|
|
29
|
+
|
|
30
|
+
toloka-kit = "1.2.1"
|
|
31
|
+
tqdm = "4.67.1"
|
|
32
|
+
ipykernel = "6.29.4"
|
|
33
|
+
notebook = "7.4.1"
|
|
34
|
+
ipywidgets = "8.1.6"
|
|
35
|
+
|
|
36
|
+
together = "1.4.6"
|
|
37
|
+
dotenv = "0.9.9"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["poetry-core>=1.2.0"]
|
|
41
|
+
build-backend = "poetry.core.masonry.api"
|