learning_model 1.0.0 → 1.0.2

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.
package/dist/index.html DELETED
@@ -1,13 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <link rel="stylesheet" href="index.css">
5
- <title>My CNN Module</title>
6
- <script defer src="index.bundle.js"></script></head>
7
- <body>
8
- <div id="root"></div>
9
- <div id="container">
10
- <canvas id="canvas"></canvas>
11
- </div>
12
- </body>
13
- </html>
package/dist/index.js DELETED
@@ -1,154 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const image_1 = __importDefault(require("./learning/image"));
16
- // 프로그레스 바를 표시하는 클래스
17
- class StatusBar {
18
- constructor(container) {
19
- this.container = container;
20
- }
21
- update(status, message) {
22
- this.container.innerText = `Status: ${status} ${message}`;
23
- }
24
- }
25
- function appRun() {
26
- return __awaiter(this, void 0, void 0, function* () {
27
- //////////////////////////////////////////////////////////////////////////////////////////
28
- const learningImage = new image_1.default({
29
- epochs: 30,
30
- batchSize: 32,
31
- });
32
- learningImage.onProgress = (progress) => {
33
- const element = document.getElementById('progress-bar');
34
- if (element !== null) {
35
- const bar = new StatusBar(element);
36
- bar.update(progress, '%');
37
- }
38
- };
39
- learningImage.onLoss = (loss) => {
40
- const element = document.getElementById('loss-bar');
41
- if (element !== null) {
42
- const bar = new StatusBar(element);
43
- bar.update(loss, 'loss');
44
- }
45
- };
46
- //////////////////////////////////////////////////////////////////////////////////////////
47
- //////////////////////////////////////////////////////////////////////////////////////////
48
- //////////////////////////////////////////////////////////////////////////////////////////
49
- // root UI
50
- const container = document.createElement('div');
51
- container.id = 'root';
52
- // learning 준비 체크
53
- const learningReadyCheck = () => {
54
- if (!learningImage.ready()) {
55
- window.alert('준비된 데이터가 없습니다.');
56
- return false;
57
- }
58
- if (learningImage.running()) {
59
- window.alert('이미 진행 중입니다.');
60
- return false;
61
- }
62
- return true;
63
- };
64
- // 이미지 저장 버튼 클릭
65
- function handleImageButtonClick(label) {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- // Canvas 생성
68
- const canvas = document.createElement('canvas');
69
- const video = document.createElement('video');
70
- // 웹캠 활성화
71
- if (navigator.mediaDevices.getUserMedia) {
72
- const stream = yield navigator.mediaDevices.getUserMedia({ video: true });
73
- video.srcObject = stream;
74
- }
75
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
76
- video.addEventListener('loadedmetadata', () => {
77
- video.play(); // 비디오 플레이 시작
78
- });
79
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
80
- video.addEventListener('play', () => {
81
- canvas.width = 128;
82
- canvas.height = 128;
83
- const context = canvas.getContext('2d');
84
- if (context) {
85
- context.drawImage(video, 0, 0, canvas.width, canvas.height);
86
- learningImage.addData(label, context.getImageData(0, 0, canvas.width, canvas.height));
87
- }
88
- });
89
- container.appendChild(canvas);
90
- });
91
- }
92
- // 추론하기 버튼
93
- function handleInferButtonClick() {
94
- return __awaiter(this, void 0, void 0, function* () {
95
- if (!learningReadyCheck()) {
96
- return;
97
- }
98
- // Canvas 생성
99
- const canvas = document.createElement('canvas');
100
- const video = document.createElement('video');
101
- // 웹캠 활성화
102
- if (navigator.mediaDevices.getUserMedia) {
103
- const stream = yield navigator.mediaDevices.getUserMedia({ video: true });
104
- video.srcObject = stream;
105
- }
106
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
107
- video.addEventListener('loadedmetadata', () => {
108
- video.play(); // 비디오 플레이 시작
109
- });
110
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
111
- video.addEventListener('play', () => {
112
- canvas.width = 128;
113
- canvas.height = 128;
114
- const context = canvas.getContext('2d');
115
- if (context) {
116
- context.drawImage(video, 0, 0, canvas.width, canvas.height);
117
- learningImage.infer(context.getImageData(0, 0, canvas.width, canvas.height));
118
- }
119
- });
120
- container.appendChild(canvas);
121
- });
122
- }
123
- // Train 학습하기 버튼
124
- function handleTrainButtonClick() {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- if (learningReadyCheck()) {
127
- yield learningImage.train();
128
- }
129
- });
130
- }
131
- // image button UI
132
- const image1Button = document.createElement('button');
133
- image1Button.textContent = '라벨1 이미지';
134
- image1Button.addEventListener('click', () => handleImageButtonClick('라벨1 이미지'));
135
- container.appendChild(image1Button);
136
- // image button UI
137
- const image2Button = document.createElement('button');
138
- image2Button.textContent = '라벨2 이미지';
139
- image2Button.addEventListener('click', () => handleImageButtonClick('라벨2 이미지'));
140
- container.appendChild(image2Button);
141
- // save button UI
142
- const trainButton = document.createElement('button');
143
- trainButton.textContent = '모델 Train';
144
- trainButton.addEventListener('click', handleTrainButtonClick);
145
- container.appendChild(trainButton);
146
- document.body.appendChild(container);
147
- // image button UI
148
- const inferButton = document.createElement('button');
149
- inferButton.textContent = '예측하기';
150
- inferButton.addEventListener('click', () => handleInferButtonClick());
151
- container.appendChild(inferButton);
152
- });
153
- }
154
- appRun();
@@ -1,244 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- };
30
- Object.defineProperty(exports, "__esModule", { value: true });
31
- const tf = __importStar(require("@tensorflow/tfjs"));
32
- class LearningImage {
33
- constructor({ epochs = 10, batchSize = 16 } = {}) {
34
- this.trainImages = [];
35
- this.MOBILE_NET_INPUT_WIDTH = 224;
36
- this.MOBILE_NET_INPUT_HEIGHT = 224;
37
- this.MOBILE_NET_INPUT_CHANNEL = 3;
38
- this.IMAGE_NORMALIZATION_FACTOR = 255.0;
39
- this.onProgress = () => { };
40
- this.onLoss = () => { };
41
- this.model = null;
42
- this.epochs = epochs;
43
- this.batchSize = batchSize;
44
- this.labels = [];
45
- this.isRunning = false;
46
- this.isReady = false;
47
- this.limitSize = 2;
48
- }
49
- // 학습 데이타 등록
50
- addData(label, data) {
51
- try {
52
- const tensor = tf.browser.fromPixels(data);
53
- console.log('addData', tensor);
54
- this.trainImages.push(tensor);
55
- this.labels.push(label);
56
- if (this.labels.length >= this.limitSize) {
57
- this.isReady = true;
58
- }
59
- return;
60
- }
61
- catch (error) {
62
- console.error('Model training failed', error);
63
- throw error;
64
- }
65
- }
66
- // 모델 학습 처리
67
- train() {
68
- return __awaiter(this, void 0, void 0, function* () {
69
- if (this.isRunning) {
70
- return Promise.reject(new Error('Training is already in progress.'));
71
- }
72
- // 콜백 정의
73
- const customCallback = {
74
- onTrainBegin: () => {
75
- console.log('Training has started.');
76
- },
77
- onTrainEnd: () => {
78
- console.log('Training has ended.');
79
- this.isRunning = false;
80
- },
81
- onBatchBegin: (batch, logs) => {
82
- console.log(`Batch ${batch} is starting.`);
83
- },
84
- onBatchEnd: (batch, logs) => {
85
- console.log(`Batch ${batch} has ended.`);
86
- },
87
- onEpochBegin: (epoch, logs) => {
88
- const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
89
- this.onProgress(progress);
90
- console.log(`Epoch ${epoch + 1} is starting.`);
91
- },
92
- onEpochEnd: (epoch, logs) => {
93
- console.log(`Epoch ${epoch + 1} has ended.`);
94
- this.onLoss(logs.loss);
95
- console.log('Loss:', logs.loss);
96
- }
97
- };
98
- try {
99
- this.isRunning = true;
100
- if (this.labels.length < this.limitSize) {
101
- return Promise.reject(new Error('Please train Data need over 2 data length'));
102
- }
103
- this.model = yield this._createModel(this.labels.length);
104
- const inputData = this._preprocessedInputData(this.model);
105
- const targetData = this._preprocessedTargetData();
106
- const history = yield this.model.fit(inputData, targetData, {
107
- epochs: this.epochs,
108
- batchSize: this.batchSize,
109
- callbacks: customCallback
110
- });
111
- console.log('Model training completed', history);
112
- return history;
113
- }
114
- catch (error) {
115
- this.isRunning = false;
116
- console.error('Model training failed', error);
117
- throw error;
118
- }
119
- });
120
- }
121
- // 추론하기
122
- infer(data) {
123
- return __awaiter(this, void 0, void 0, function* () {
124
- if (this.model === null) {
125
- throw new Error('Model is null');
126
- }
127
- try {
128
- const tensor = tf.browser.fromPixels(data);
129
- const resizedTensor = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
130
- const reshapedTensor = resizedTensor.expandDims(0); // 배치 크기 1을 추가하여 4차원으로 변환
131
- const predictions = this.model.predict(reshapedTensor);
132
- const predictionsData = yield predictions.data(); // 예측 텐서의 데이터를 비동기로 가져옴
133
- const classProbabilities = new Map(); // 클래스별 확률 누적값을 저장할 맵
134
- for (let i = 0; i < predictionsData.length; i++) {
135
- const className = this.labels[i]; // 클래스 이름
136
- const probability = predictionsData[i];
137
- const existingProbability = classProbabilities.get(className);
138
- if (existingProbability !== undefined) {
139
- classProbabilities.set(className, existingProbability + probability);
140
- }
141
- else {
142
- classProbabilities.set(className, probability);
143
- }
144
- }
145
- console.log('Class Probabilities:', classProbabilities);
146
- return classProbabilities;
147
- }
148
- catch (error) {
149
- throw error;
150
- }
151
- });
152
- }
153
- // 모델 저장
154
- saveModel() {
155
- console.log('saved model');
156
- }
157
- // 진행중 여부
158
- running() {
159
- return this.isRunning;
160
- }
161
- ready() {
162
- return this.isReady;
163
- }
164
- // target 라벨 데이타
165
- _preprocessedTargetData() {
166
- // 라벨 unique 처리 & 배열 리턴
167
- console.log('uniqueLabels.length', this.labels, this.labels.length);
168
- const labelIndices = this.labels.map((label) => this.labels.indexOf(label));
169
- console.log('labelIndices', labelIndices);
170
- const oneHotEncode = tf.oneHot(tf.tensor1d(labelIndices, 'int32'), this.labels.length);
171
- console.log('oneHotEncode', oneHotEncode);
172
- return oneHotEncode;
173
- }
174
- // 입력 이미지 데이타
175
- _preprocessedInputData(model) {
176
- // 이미지 배열을 배치로 변환 - [null, 224, 224, 3]
177
- const inputShape = model.inputs[0].shape;
178
- console.log('inputShape', inputShape);
179
- // inputShape를 이와 같이 포멧 맞춘다. for reshape to [224, 224, 3]
180
- const inputShapeArray = inputShape.slice(1);
181
- console.log('inputShapeArray', inputShapeArray);
182
- const inputBatch = tf.stack(this.trainImages.map((image) => {
183
- // 이미지 전처리 및 크기 조정 등을 수행한 후에
184
- // 모델의 입력 형태로 변환하여 반환
185
- const xs = this._preprocessData(image); // 전처리 함수는 사용자 정의해야 함
186
- return tf.reshape(xs, inputShapeArray);
187
- }));
188
- return inputBatch;
189
- }
190
- // 모델 학습하기 위한 데이타 전처리 단계
191
- _preprocessData(tensor) {
192
- try {
193
- // mobilenet model summary를 하면 위와 같이 224,224 사이즈의 입력값 설정되어 있다. ex) input_1 (InputLayer) [null,224,224,3]
194
- const resizedImage = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
195
- // 이미지를 [0,1] 범위로 정규화 255로 나뉜 픽셀값
196
- const normalizedImage = resizedImage.div(this.IMAGE_NORMALIZATION_FACTOR);
197
- // expandDims(0)을 하여 차원을 추가하여 4D텐서 반환
198
- return normalizedImage.expandDims(0);
199
- }
200
- catch (error) {
201
- console.error('Failed to _preprocessData data', error);
202
- throw error;
203
- }
204
- }
205
- // 모델 저장
206
- _createModel(numClasses) {
207
- return __awaiter(this, void 0, void 0, function* () {
208
- try {
209
- const inputShape = [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT, this.MOBILE_NET_INPUT_CHANNEL];
210
- const model = tf.sequential();
211
- model.add(tf.layers.conv2d({
212
- inputShape,
213
- filters: 32,
214
- kernelSize: 3,
215
- activation: 'relu'
216
- }));
217
- model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
218
- model.add(tf.layers.conv2d({
219
- filters: 64,
220
- kernelSize: 3,
221
- activation: 'relu'
222
- }));
223
- model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
224
- model.add(tf.layers.flatten());
225
- model.add(tf.layers.dense({
226
- units: numClasses,
227
- activation: 'softmax'
228
- }));
229
- model.compile({
230
- loss: (numClasses === 2) ? 'binaryCrossentropy' : 'categoricalCrossentropy',
231
- optimizer: tf.train.adam(),
232
- metrics: ['accuracy']
233
- });
234
- model.summary();
235
- return model;
236
- }
237
- catch (error) {
238
- console.error('Failed to load model', error);
239
- throw error;
240
- }
241
- });
242
- }
243
- }
244
- exports.default = LearningImage;
@@ -1,248 +0,0 @@
1
- "use strict";
2
- ///////////////////////////////////////////////////////////////////////////
3
- ///////////////////////////////////////////////////////////////////////////
4
- ///////////////////////////////////////////////////////////////////////////
5
- // mobilenet 모델을 이용한 전이학습 방법
6
- ///////////////////////////////////////////////////////////////////////////
7
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
- if (k2 === undefined) k2 = k;
9
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
26
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
27
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
- return new (P || (P = Promise))(function (resolve, reject) {
29
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
- step((generator = generator.apply(thisArg, _arguments || [])).next());
33
- });
34
- };
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- const tf = __importStar(require("@tensorflow/tfjs"));
37
- class LearningMobilenetImage {
38
- constructor({ modelURL = 'https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json', // 디폴트 mobilenet 이미지
39
- epochs = 10, batchSize = 16 } = {}) {
40
- this.trainImages = [];
41
- this.MOBILE_NET_INPUT_WIDTH = 224;
42
- this.MOBILE_NET_INPUT_HEIGHT = 224;
43
- this.MOBILE_NET_INPUT_CHANNEL = 3;
44
- this.IMAGE_NORMALIZATION_FACTOR = 255.0;
45
- // 진행 상태를 나타내는 이벤트를 정의합니다.
46
- this.onProgress = () => { };
47
- this.onLoss = () => { };
48
- this.model = null;
49
- this.epochs = epochs;
50
- this.batchSize = batchSize;
51
- this.labels = [];
52
- this.modelURL = modelURL;
53
- this.isRunning = false;
54
- this.isReady = false;
55
- this.limitSize = 2;
56
- }
57
- // 학습 데이타 등록
58
- addData(label, data) {
59
- try {
60
- const tensor = tf.browser.fromPixels(data);
61
- console.log('addData', tensor);
62
- this.trainImages.push(tensor);
63
- this.labels.push(label);
64
- if (this.labels.length >= this.limitSize) {
65
- this.isReady = true;
66
- }
67
- return;
68
- }
69
- catch (error) {
70
- console.error('Model training failed', error);
71
- throw error;
72
- }
73
- }
74
- // 모델 학습 처리
75
- train() {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- if (this.isRunning) {
78
- return Promise.reject(new Error('Training is already in progress.'));
79
- }
80
- // 콜백 정의
81
- const customCallback = {
82
- onTrainBegin: () => {
83
- console.log('Training has started.');
84
- },
85
- onTrainEnd: () => {
86
- console.log('Training has ended.');
87
- this.isRunning = false;
88
- },
89
- onBatchBegin: (batch, logs) => {
90
- console.log(`Batch ${batch} is starting.`);
91
- },
92
- onBatchEnd: (batch, logs) => {
93
- console.log(`Batch ${batch} has ended.`);
94
- },
95
- onEpochBegin: (epoch, logs) => {
96
- const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
97
- this.onProgress(progress);
98
- console.log(`Epoch ${epoch + 1} is starting.`);
99
- },
100
- onEpochEnd: (epoch, logs) => {
101
- console.log(`Epoch ${epoch + 1} has ended.`);
102
- console.log('Loss:', logs.loss);
103
- }
104
- };
105
- try {
106
- this.isRunning = true;
107
- if (this.labels.length < this.limitSize) {
108
- return Promise.reject(new Error('Please train Data need over 2 data length'));
109
- }
110
- this.model = yield this._createModel(this.labels.length);
111
- const inputData = this._preprocessedInputData(this.model);
112
- const targetData = this._preprocessedTargetData();
113
- const history = yield this.model.fit(inputData, targetData, {
114
- epochs: this.epochs,
115
- batchSize: this.batchSize,
116
- callbacks: customCallback
117
- });
118
- console.log('Model training completed', history);
119
- return history;
120
- }
121
- catch (error) {
122
- this.isRunning = false;
123
- console.error('Model training failed', error);
124
- throw error;
125
- }
126
- });
127
- }
128
- // 추론하기
129
- infer(data) {
130
- return __awaiter(this, void 0, void 0, function* () {
131
- if (this.model === null) {
132
- throw new Error('Model is null');
133
- }
134
- try {
135
- const tensor = tf.browser.fromPixels(data);
136
- const resizedTensor = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
137
- const reshapedTensor = resizedTensor.expandDims(0); // 배치 크기 1을 추가하여 4차원으로 변환
138
- const predictions = this.model.predict(reshapedTensor);
139
- const predictionsData = yield predictions.data(); // 예측 텐서의 데이터를 비동기로 가져옴
140
- const classProbabilities = new Map(); // 클래스별 확률 누적값을 저장할 맵
141
- for (let i = 0; i < predictionsData.length; i++) {
142
- const className = this.labels[i]; // 클래스 이름
143
- const probability = predictionsData[i];
144
- const existingProbability = classProbabilities.get(className);
145
- if (existingProbability !== undefined) {
146
- classProbabilities.set(className, existingProbability + probability);
147
- }
148
- else {
149
- classProbabilities.set(className, probability);
150
- }
151
- }
152
- console.log('Class Probabilities:', classProbabilities);
153
- return classProbabilities;
154
- }
155
- catch (error) {
156
- throw error;
157
- }
158
- });
159
- }
160
- // 모델 저장
161
- saveModel() {
162
- console.log('saved model');
163
- }
164
- // 진행중 여부
165
- running() {
166
- return this.isRunning;
167
- }
168
- ready() {
169
- return this.isReady;
170
- }
171
- // target 라벨 데이타
172
- _preprocessedTargetData() {
173
- // 라벨 unique 처리 & 배열 리턴
174
- console.log('uniqueLabels.length', this.labels, this.labels.length);
175
- const labelIndices = this.labels.map((label) => this.labels.indexOf(label));
176
- console.log('labelIndices', labelIndices);
177
- const oneHotEncode = tf.oneHot(tf.tensor1d(labelIndices, 'int32'), this.labels.length);
178
- console.log('oneHotEncode', oneHotEncode);
179
- return oneHotEncode;
180
- }
181
- // 입력 이미지 데이타
182
- _preprocessedInputData(model) {
183
- // 이미지 배열을 배치로 변환 - [null, 224, 224, 3]
184
- const inputShape = model.inputs[0].shape;
185
- console.log('inputShape', inputShape);
186
- // inputShape를 이와 같이 포멧 맞춘다. for reshape to [224, 224, 3]
187
- const inputShapeArray = inputShape.slice(1);
188
- console.log('inputShapeArray', inputShapeArray);
189
- const inputBatch = tf.stack(this.trainImages.map((image) => {
190
- // 이미지 전처리 및 크기 조정 등을 수행한 후에
191
- // 모델의 입력 형태로 변환하여 반환
192
- const xs = this._preprocessData(image); // 전처리 함수는 사용자 정의해야 함
193
- return tf.reshape(xs, inputShapeArray);
194
- }));
195
- return inputBatch;
196
- }
197
- // 모델 학습하기 위한 데이타 전처리 단계
198
- _preprocessData(tensor) {
199
- try {
200
- // mobilenet model summary를 하면 위와 같이 224,224 사이즈의 입력값 설정되어 있다. ex) input_1 (InputLayer) [null,224,224,3]
201
- const resizedImage = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
202
- // 이미지를 [0,1] 범위로 정규화 255로 나뉜 픽셀값
203
- const normalizedImage = resizedImage.div(this.IMAGE_NORMALIZATION_FACTOR);
204
- // expandDims(0)을 하여 차원을 추가하여 4D텐서 반환
205
- return normalizedImage.expandDims(0);
206
- }
207
- catch (error) {
208
- console.error('Failed to _preprocessData data', error);
209
- throw error;
210
- }
211
- }
212
- // 모델 저장
213
- _createModel(numClasses) {
214
- return __awaiter(this, void 0, void 0, function* () {
215
- try {
216
- const load_model = yield tf.loadLayersModel(this.modelURL);
217
- // 기존 MobileNet 모델에서 마지막 레이어 제외
218
- const truncatedModel = tf.model({
219
- inputs: load_model.inputs,
220
- outputs: load_model.layers[load_model.layers.length - 2].output
221
- });
222
- // 모델을 학습 가능하게 설정하고 선택한 레이어까지 고정
223
- for (let layer of truncatedModel.layers) {
224
- layer.trainable = false;
225
- }
226
- const model = tf.sequential();
227
- model.add(truncatedModel);
228
- model.add(tf.layers.flatten()); // 필요한 경우 Flatten 레이어 추가
229
- model.add(tf.layers.dense({
230
- units: numClasses,
231
- activation: 'softmax'
232
- }));
233
- model.compile({
234
- loss: (numClasses === 2) ? 'binaryCrossentropy' : 'categoricalCrossentropy',
235
- optimizer: tf.train.adam(),
236
- metrics: ['accuracy']
237
- });
238
- model.summary();
239
- return model;
240
- }
241
- catch (error) {
242
- console.error('Failed to load model', error);
243
- throw error;
244
- }
245
- });
246
- }
247
- }
248
- exports.default = LearningMobilenetImage;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateRandomString = void 0;
4
- // 랜덤 string for test
5
- function generateRandomString(length) {
6
- const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7
- let result = '';
8
- for (let i = 0; i < length; i++) {
9
- const randomIndex = Math.floor(Math.random() * characters.length);
10
- result += characters.charAt(randomIndex);
11
- }
12
- return result;
13
- }
14
- exports.generateRandomString = generateRandomString;