learning_model 1.0.23 → 1.0.25

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.
@@ -0,0 +1,335 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2017 Google LLC. All Rights Reserved.
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ * =============================================================================
16
+ */
17
+
18
+ /**
19
+ * @license
20
+ * Copyright 2018 Google LLC
21
+ *
22
+ * Use of this source code is governed by an MIT-style
23
+ * license that can be found in the LICENSE file or at
24
+ * https://opensource.org/licenses/MIT.
25
+ * =============================================================================
26
+ */
27
+
28
+ /**
29
+ * @license
30
+ * Copyright 2018 Google LLC. All Rights Reserved.
31
+ * Licensed under the Apache License, Version 2.0 (the "License");
32
+ * you may not use this file except in compliance with the License.
33
+ * You may obtain a copy of the License at
34
+ *
35
+ * http://www.apache.org/licenses/LICENSE-2.0
36
+ *
37
+ * Unless required by applicable law or agreed to in writing, software
38
+ * distributed under the License is distributed on an "AS IS" BASIS,
39
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
40
+ * See the License for the specific language governing permissions and
41
+ * limitations under the License.
42
+ *
43
+ * =============================================================================
44
+ */
45
+
46
+ /**
47
+ * @license
48
+ * Copyright 2018 Google LLC. All Rights Reserved.
49
+ * Licensed under the Apache License, Version 2.0 (the "License");
50
+ * you may not use this file except in compliance with the License.
51
+ * You may obtain a copy of the License at
52
+ *
53
+ * http://www.apache.org/licenses/LICENSE-2.0
54
+ *
55
+ * Unless required by applicable law or agreed to in writing, software
56
+ * distributed under the License is distributed on an "AS IS" BASIS,
57
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
58
+ * See the License for the specific language governing permissions and
59
+ * limitations under the License.
60
+ * =============================================================================
61
+ */
62
+
63
+ /**
64
+ * @license
65
+ * Copyright 2019 Google LLC
66
+ *
67
+ * Use of this source code is governed by an MIT-style
68
+ * license that can be found in the LICENSE file or at
69
+ * https://opensource.org/licenses/MIT.
70
+ * =============================================================================
71
+ */
72
+
73
+ /**
74
+ * @license
75
+ * Copyright 2019 Google LLC. All Rights Reserved.
76
+ * Licensed under the Apache License, Version 2.0 (the "License");
77
+ * you may not use this file except in compliance with the License.
78
+ * You may obtain a copy of the License at
79
+ *
80
+ * http://www.apache.org/licenses/LICENSE-2.0
81
+ *
82
+ * Unless required by applicable law or agreed to in writing, software
83
+ * distributed under the License is distributed on an "AS IS" BASIS,
84
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
85
+ * See the License for the specific language governing permissions and
86
+ * limitations under the License.
87
+ *
88
+ * =============================================================================
89
+ */
90
+
91
+ /**
92
+ * @license
93
+ * Copyright 2019 Google LLC. All Rights Reserved.
94
+ * Licensed under the Apache License, Version 2.0 (the "License");
95
+ * you may not use this file except in compliance with the License.
96
+ * You may obtain a copy of the License at
97
+ *
98
+ * http://www.apache.org/licenses/LICENSE-2.0
99
+ *
100
+ * Unless required by applicable law or agreed to in writing, software
101
+ * distributed under the License is distributed on an "AS IS" BASIS,
102
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
103
+ * See the License for the specific language governing permissions and
104
+ * limitations under the License.
105
+ * =============================================================================
106
+ */
107
+
108
+ /**
109
+ * @license
110
+ * Copyright 2020 Google Inc. All Rights Reserved.
111
+ * Licensed under the Apache License, Version 2.0 (the "License");
112
+ * you may not use this file except in compliance with the License.
113
+ * You may obtain a copy of the License at
114
+ *
115
+ * http://www.apache.org/licenses/LICENSE-2.0
116
+ *
117
+ * Unless required by applicable law or agreed to in writing, software
118
+ * distributed under the License is distributed on an "AS IS" BASIS,
119
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
120
+ * See the License for the specific language governing permissions and
121
+ * limitations under the License.
122
+ * =============================================================================
123
+ */
124
+
125
+ /**
126
+ * @license
127
+ * Copyright 2020 Google LLC
128
+ *
129
+ * Use of this source code is governed by an MIT-style
130
+ * license that can be found in the LICENSE file or at
131
+ * https://opensource.org/licenses/MIT.
132
+ * =============================================================================
133
+ */
134
+
135
+ /**
136
+ * @license
137
+ * Copyright 2020 Google LLC. All Rights Reserved.
138
+ * Licensed under the Apache License, Version 2.0 (the "License");
139
+ * you may not use this file except in compliance with the License.
140
+ * You may obtain a copy of the License at
141
+ *
142
+ * http://www.apache.org/licenses/LICENSE-2.0
143
+ *
144
+ * Unless required by applicable law or agreed to in writing, software
145
+ * distributed under the License is distributed on an "AS IS" BASIS,
146
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
147
+ * See the License for the specific language governing permissions and
148
+ * limitations under the License.
149
+ * =============================================================================
150
+ */
151
+
152
+ /**
153
+ * @license
154
+ * Copyright 2020 Google LLC. All Rights Reserved.
155
+ * Licensed under the Apache License, Version 2.0 (the License);
156
+ * you may not use this file except in compliance with the License.
157
+ * You may obtain a copy of the License at
158
+ *
159
+ * http://www.apache.org/licenses/LICENSE-2.0
160
+ *
161
+ * Unless required by applicable law or agreed to in writing, software
162
+ * distributed under the License is distributed on an AS IS BASIS,
163
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
164
+ * See the License for the specific language governing permissions and
165
+ * limitations under the License.
166
+ * =============================================================================
167
+ */
168
+
169
+ /**
170
+ * @license
171
+ * Copyright 2021 Google LLC. All Rights Reserved.
172
+ * Licensed under the Apache License, Version 2.0 (the "License");
173
+ * you may not use this file except in compliance with the License.
174
+ * You may obtain a copy of the License at
175
+ *
176
+ * http://www.apache.org/licenses/LICENSE-2.0
177
+ *
178
+ * Unless required by applicable law or agreed to in writing, software
179
+ * distributed under the License is distributed on an "AS IS" BASIS,
180
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
181
+ * See the License for the specific language governing permissions and
182
+ * limitations under the License.
183
+ * =============================================================================
184
+ */
185
+
186
+ /**
187
+ * @license
188
+ * Copyright 2021 Google LLC. All Rights Reserved.
189
+ * Licensed under the Apache License, Version 2.0 (the "License");
190
+ * you may not use this file except in compliance with the License.
191
+ * You may obtain a copy of the License at
192
+ *
193
+ * https://www.apache.org/licenses/LICENSE-2.0
194
+ *
195
+ * Unless required by applicable law or agreed to in writing, software
196
+ * distributed under the License is distributed on an "AS IS" BASIS,
197
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
198
+ * See the License for the specific language governing permissions and
199
+ * limitations under the License.
200
+ * =============================================================================
201
+ */
202
+
203
+ /**
204
+ * @license
205
+ * Copyright 2022 CodeSmith LLC
206
+ *
207
+ * Use of this source code is governed by an MIT-style
208
+ * license that can be found in the LICENSE file or at
209
+ * https://opensource.org/licenses/MIT.
210
+ * =============================================================================
211
+ */
212
+
213
+ /**
214
+ * @license
215
+ * Copyright 2022 Google Inc. All Rights Reserved.
216
+ * Licensed under the Apache License, Version 2.0 (the "License");
217
+ * you may not use this file except in compliance with the License.
218
+ * You may obtain a copy of the License at
219
+ *
220
+ * http://www.apache.org/licenses/LICENSE-2.0
221
+ *
222
+ * Unless required by applicable law or agreed to in writing, software
223
+ * distributed under the License is distributed on an "AS IS" BASIS,
224
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
225
+ * See the License for the specific language governing permissions and
226
+ * limitations under the License.
227
+ * =============================================================================
228
+ */
229
+
230
+ /**
231
+ * @license
232
+ * Copyright 2022 Google LLC
233
+ *
234
+ * Use of this source code is governed by an MIT-style
235
+ * license that can be found in the LICENSE file or at
236
+ * https://opensource.org/licenses/MIT.
237
+ * =============================================================================
238
+ */
239
+
240
+ /**
241
+ * @license
242
+ * Copyright 2022 Google LLC.
243
+ * Licensed under the Apache License, Version 2.0 (the "License");
244
+ * you may not use this file except in compliance with the License.
245
+ * You may obtain a copy of the License at
246
+ *
247
+ * http://www.apache.org/licenses/LICENSE-2.0
248
+ *
249
+ * Unless required by applicable law or agreed to in writing, software
250
+ * distributed under the License is distributed on an "AS IS" BASIS,
251
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
252
+ * See the License for the specific language governing permissions and
253
+ * limitations under the License.
254
+ * =============================================================================
255
+ */
256
+
257
+ /**
258
+ * @license
259
+ * Copyright 2022 Google LLC. All Rights Reserved.
260
+ * Licensed under the Apache License, Version 2.0 (the "License");
261
+ * you may not use this file except in compliance with the License.
262
+ * You may obtain a copy of the License at
263
+ *
264
+ * http://www.apache.org/licenses/LICENSE-2.0
265
+ *
266
+ * Unless required by applicable law or agreed to in writing, software
267
+ * distributed under the License is distributed on an "AS IS" BASIS,
268
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
269
+ * See the License for the specific language governing permissions and
270
+ * limitations under the License.
271
+ * =============================================================================
272
+ */
273
+
274
+ /**
275
+ * @license
276
+ * Copyright 2022 Google LLC. All Rights Reserved.
277
+ * Licensed under the Apache License, Version 2.0 (the 'License');
278
+ * you may not use this file except in compliance with the License.
279
+ * You may obtain a copy of the License at
280
+ *
281
+ * http://www.apache.org/licenses/LICENSE-2.0
282
+ *
283
+ * Unless required by applicable law or agreed to in writing, software
284
+ * distributed under the License is distributed on an 'AS IS' BASIS,
285
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
286
+ * See the License for the specific language governing permissions and
287
+ * limitations under the License.
288
+ * =============================================================================
289
+ */
290
+
291
+ /**
292
+ * @license
293
+ * Copyright 2023 CodeSmith LLC
294
+ *
295
+ * Use of this source code is governed by an MIT-style
296
+ * license that can be found in the LICENSE file or at
297
+ * https://opensource.org/licenses/MIT.
298
+ * =============================================================================
299
+ */
300
+
301
+ /**
302
+ * @license
303
+ * Copyright 2023 Google LLC.
304
+ * Licensed under the Apache License, Version 2.0 (the "License");
305
+ * you may not use this file except in compliance with the License.
306
+ * You may obtain a copy of the License at
307
+ *
308
+ * http://www.apache.org/licenses/LICENSE-2.0
309
+ *
310
+ * Unless required by applicable law or agreed to in writing, software
311
+ * distributed under the License is distributed on an "AS IS" BASIS,
312
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
313
+ * See the License for the specific language governing permissions and
314
+ * limitations under the License.
315
+ * =============================================================================
316
+ */
317
+
318
+ /**
319
+ * @license
320
+ * Copyright 2023 Google LLC. All Rights Reserved.
321
+ * Licensed under the Apache License, Version 2.0 (the "License");
322
+ * you may not use this file except in compliance with the License.
323
+ * You may obtain a copy of the License at
324
+ *
325
+ * http://www.apache.org/licenses/LICENSE-2.0
326
+ *
327
+ * Unless required by applicable law or agreed to in writing, software
328
+ * distributed under the License is distributed on an "AS IS" BASIS,
329
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
330
+ * See the License for the specific language governing permissions and
331
+ * limitations under the License.
332
+ * =============================================================================
333
+ */
334
+
335
+ /** @license See the LICENSE file. */
@@ -0,0 +1,3 @@
1
+ import LearningImage from './learning/image';
2
+ import LearningMobilenetImage from './learning/mobilenet_image';
3
+ export { LearningImage, LearningMobilenetImage };
@@ -0,0 +1 @@
1
+ <!doctype html><html><head><link rel="stylesheet" href="index.css"><title>My CNN Module</title><script defer="defer" src="index.bundle.js"></script></head><body><div id="loss-bar"></div><div id="progress-bar"></div><div id="root"></div><div id="container"><canvas id="canvas"></canvas></div></body></html>
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.LearningMobilenetImage = exports.LearningImage = void 0;
7
+ const image_1 = __importDefault(require("./learning/image"));
8
+ exports.LearningImage = image_1.default;
9
+ const mobilenet_image_1 = __importDefault(require("./learning/mobilenet_image"));
10
+ exports.LearningMobilenetImage = mobilenet_image_1.default;
@@ -0,0 +1,19 @@
1
+ import * as tf from '@tensorflow/tfjs';
2
+ interface LearningInterface {
3
+ model: tf.LayersModel | null;
4
+ labels: string[];
5
+ isRunning: boolean;
6
+ isReady: boolean;
7
+ onProgress(progress: number): void;
8
+ onLoss(loss: number): void;
9
+ onEvents(logs: any): void;
10
+ onTrainBegin(log: any): void;
11
+ onTrainEnd(log: any): void;
12
+ addData(label: string, data: any): Promise<void>;
13
+ train(): Promise<tf.History>;
14
+ infer(data: any): Promise<any>;
15
+ saveModel(): void;
16
+ running(): boolean;
17
+ ready(): boolean;
18
+ }
19
+ export default LearningInterface;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,42 @@
1
+ import * as tf from '@tensorflow/tfjs';
2
+ import LearningInterface from './base';
3
+ declare class LearningImage implements LearningInterface {
4
+ model: tf.LayersModel | null;
5
+ epochs: number;
6
+ batchSize: number;
7
+ learningRate: number;
8
+ validateRate: number;
9
+ labels: string[];
10
+ isRunning: boolean;
11
+ isReady: boolean;
12
+ limitSize: number;
13
+ trainImages: tf.Tensor3D[];
14
+ readonly MOBILE_NET_INPUT_WIDTH = 224;
15
+ readonly MOBILE_NET_INPUT_HEIGHT = 224;
16
+ readonly MOBILE_NET_INPUT_CHANNEL = 3;
17
+ readonly IMAGE_NORMALIZATION_FACTOR = 255;
18
+ constructor({ epochs, batchSize, limitSize, learningRate, validateRate, }?: {
19
+ modelURL?: string;
20
+ epochs?: number;
21
+ batchSize?: number;
22
+ limitSize?: number;
23
+ learningRate?: number;
24
+ validateRate?: number;
25
+ });
26
+ onProgress: (progress: number) => void;
27
+ onLoss: (loss: number) => void;
28
+ onEvents: (logs: any) => void;
29
+ onTrainBegin: (log: any) => void;
30
+ onTrainEnd: (log: any) => void;
31
+ addData(label: string, data: any): Promise<void>;
32
+ train(): Promise<tf.History>;
33
+ infer(data: any): Promise<Map<string, number>>;
34
+ saveModel(): void;
35
+ running(): boolean;
36
+ ready(): boolean;
37
+ private _preprocessedTargetData;
38
+ private _preprocessedInputData;
39
+ private _preprocessData;
40
+ private _createModel;
41
+ }
42
+ export default LearningImage;
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ const tf = __importStar(require("@tensorflow/tfjs"));
36
+ class LearningImage {
37
+ constructor({ epochs = 10, batchSize = 16, limitSize = 2, learningRate = 0.001, validateRate = 0.2, } = {}) {
38
+ this.trainImages = [];
39
+ this.MOBILE_NET_INPUT_WIDTH = 224;
40
+ this.MOBILE_NET_INPUT_HEIGHT = 224;
41
+ this.MOBILE_NET_INPUT_CHANNEL = 3;
42
+ this.IMAGE_NORMALIZATION_FACTOR = 255.0;
43
+ this.onProgress = () => { };
44
+ this.onLoss = () => { };
45
+ this.onEvents = () => { };
46
+ this.onTrainBegin = () => { };
47
+ this.onTrainEnd = () => { };
48
+ this.model = null;
49
+ this.epochs = epochs;
50
+ this.batchSize = batchSize;
51
+ this.learningRate = learningRate;
52
+ this.validateRate = validateRate;
53
+ this.labels = [];
54
+ this.isRunning = false;
55
+ this.isReady = false;
56
+ this.limitSize = 2;
57
+ }
58
+ // 학습 데이타 등록
59
+ addData(label, data) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ try {
62
+ const tensor = tf.browser.fromPixels(data);
63
+ console.log('addData', tensor);
64
+ this.trainImages.push(tensor);
65
+ this.labels.push(label);
66
+ if (this.labels.length >= this.limitSize) {
67
+ this.isReady = true;
68
+ }
69
+ return Promise.resolve();
70
+ }
71
+ catch (error) {
72
+ console.error('Model training failed', error);
73
+ throw error;
74
+ }
75
+ });
76
+ }
77
+ // 모델 학습 처리
78
+ train() {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ if (this.isRunning) {
81
+ return Promise.reject(new Error('Training is already in progress.'));
82
+ }
83
+ // 콜백 정의
84
+ const customCallback = {
85
+ onTrainBegin: (log) => {
86
+ this.onTrainBegin(log);
87
+ console.log('Training has started.');
88
+ },
89
+ onTrainEnd: (log) => {
90
+ this.onTrainEnd(log);
91
+ console.log('Training has ended.');
92
+ this.isRunning = false;
93
+ },
94
+ onBatchBegin: (batch, logs) => {
95
+ console.log(`Batch ${batch} is starting.`);
96
+ },
97
+ onBatchEnd: (batch, logs) => {
98
+ console.log(`Batch ${batch} has ended.`);
99
+ },
100
+ onEpochBegin: (epoch, logs) => {
101
+ console.log(`Epoch ${epoch + 1} is starting.`, logs);
102
+ },
103
+ onEpochEnd: (epoch, logs) => {
104
+ console.log(`Epoch ${epoch + 1} has ended.`);
105
+ this.onLoss(logs.loss);
106
+ console.log('Loss:', logs);
107
+ this.onEvents(logs);
108
+ this.onProgress(epoch + 1);
109
+ }
110
+ };
111
+ try {
112
+ this.isRunning = true;
113
+ if (this.labels.length < this.limitSize) {
114
+ return Promise.reject(new Error('Please train Data need over 2 data length'));
115
+ }
116
+ this.model = yield this._createModel(this.labels.length);
117
+ const inputData = this._preprocessedInputData(this.model);
118
+ console.log('inputData', inputData);
119
+ const targetData = this._preprocessedTargetData();
120
+ console.log('targetData', targetData);
121
+ const history = yield this.model.fit(inputData, targetData, {
122
+ epochs: this.epochs,
123
+ batchSize: this.batchSize,
124
+ validationSplit: this.validateRate,
125
+ callbacks: customCallback
126
+ });
127
+ console.log('Model training completed', history);
128
+ return history;
129
+ }
130
+ catch (error) {
131
+ this.isRunning = false;
132
+ console.error('Model training failed', error);
133
+ throw error;
134
+ }
135
+ });
136
+ }
137
+ // 추론하기
138
+ infer(data) {
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ if (this.model === null) {
141
+ throw new Error('Model is null');
142
+ }
143
+ try {
144
+ const tensor = tf.browser.fromPixels(data);
145
+ const resizedTensor = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
146
+ const reshapedTensor = resizedTensor.expandDims(0); // 배치 크기 1을 추가하여 4차원으로 변환
147
+ const predictions = this.model.predict(reshapedTensor);
148
+ const predictionsData = yield predictions.data(); // 예측 텐서의 데이터를 비동기로 가져옴
149
+ const classProbabilities = new Map(); // 클래스별 확률 누적값을 저장할 맵
150
+ for (let i = 0; i < predictionsData.length; i++) {
151
+ const className = this.labels[i]; // 클래스 이름
152
+ const probability = predictionsData[i];
153
+ const existingProbability = classProbabilities.get(className);
154
+ if (existingProbability !== undefined) {
155
+ classProbabilities.set(className, existingProbability + probability);
156
+ }
157
+ else {
158
+ classProbabilities.set(className, probability);
159
+ }
160
+ }
161
+ console.log('Class Probabilities:', classProbabilities);
162
+ return classProbabilities;
163
+ }
164
+ catch (error) {
165
+ throw error;
166
+ }
167
+ });
168
+ }
169
+ // 모델 저장
170
+ saveModel() {
171
+ console.log('saved model');
172
+ }
173
+ // 진행중 여부
174
+ running() {
175
+ return this.isRunning;
176
+ }
177
+ ready() {
178
+ return this.isReady;
179
+ }
180
+ // target 라벨 데이타
181
+ _preprocessedTargetData() {
182
+ // 라벨 unique 처리 & 배열 리턴
183
+ console.log('uniqueLabels.length', this.labels, this.labels.length);
184
+ const labelIndices = this.labels.map((label) => this.labels.indexOf(label));
185
+ console.log('labelIndices', labelIndices);
186
+ const oneHotEncode = tf.oneHot(tf.tensor1d(labelIndices, 'int32'), this.labels.length);
187
+ console.log('oneHotEncode', oneHotEncode);
188
+ return oneHotEncode;
189
+ }
190
+ // 입력 이미지 데이타
191
+ _preprocessedInputData(model) {
192
+ // 이미지 배열을 배치로 변환 - [null, 224, 224, 3]
193
+ const inputShape = model.inputs[0].shape;
194
+ console.log('inputShape', inputShape);
195
+ // inputShape를 이와 같이 포멧 맞춘다. for reshape to [224, 224, 3]
196
+ const inputShapeArray = inputShape.slice(1);
197
+ console.log('inputShapeArray', inputShapeArray);
198
+ const inputBatch = tf.stack(this.trainImages.map((image) => {
199
+ // 이미지 전처리 및 크기 조정 등을 수행한 후에
200
+ // 모델의 입력 형태로 변환하여 반환
201
+ const xs = this._preprocessData(image); // 전처리 함수는 사용자 정의해야 함
202
+ return tf.reshape(xs, inputShapeArray);
203
+ }));
204
+ return inputBatch;
205
+ }
206
+ // 모델 학습하기 위한 데이타 전처리 단계
207
+ _preprocessData(tensor) {
208
+ try {
209
+ // mobilenet model summary를 하면 위와 같이 224,224 사이즈의 입력값 설정되어 있다. ex) input_1 (InputLayer) [null,224,224,3]
210
+ const resizedImage = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
211
+ // 이미지를 [0,1] 범위로 정규화 255로 나뉜 픽셀값
212
+ const normalizedImage = resizedImage.div(this.IMAGE_NORMALIZATION_FACTOR);
213
+ // expandDims(0)을 하여 차원을 추가하여 4D텐서 반환
214
+ return normalizedImage.expandDims(0);
215
+ }
216
+ catch (error) {
217
+ console.error('Failed to _preprocessData data', error);
218
+ throw error;
219
+ }
220
+ }
221
+ // 모델 저장
222
+ _createModel(numClasses) {
223
+ return __awaiter(this, void 0, void 0, function* () {
224
+ try {
225
+ const inputShape = [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT, this.MOBILE_NET_INPUT_CHANNEL];
226
+ const model = tf.sequential();
227
+ model.add(tf.layers.conv2d({
228
+ inputShape,
229
+ filters: 32,
230
+ kernelSize: 3,
231
+ activation: 'relu'
232
+ }));
233
+ model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
234
+ model.add(tf.layers.conv2d({
235
+ filters: 64,
236
+ kernelSize: 3,
237
+ activation: 'relu'
238
+ }));
239
+ model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
240
+ model.add(tf.layers.flatten());
241
+ model.add(tf.layers.dense({
242
+ units: numClasses,
243
+ activation: 'softmax'
244
+ }));
245
+ const optimizer = tf.train.adam(this.learningRate); // Optimizer를 생성하고 학습률을 설정합니다.
246
+ model.compile({
247
+ loss: (numClasses === 2) ? 'binaryCrossentropy' : 'categoricalCrossentropy',
248
+ optimizer: optimizer,
249
+ metrics: ['accuracy', 'acc']
250
+ });
251
+ model.summary();
252
+ return model;
253
+ }
254
+ catch (error) {
255
+ console.error('Failed to load model', error);
256
+ throw error;
257
+ }
258
+ });
259
+ }
260
+ }
261
+ exports.default = LearningImage;