learning_model 1.0.2 → 1.0.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "learning_model",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "learning model develop",
5
5
  "main": "dist/index.bundle.js",
6
6
  "types": "dist/types/index.d.ts",
package/src/index.ts CHANGED
@@ -1,156 +1,4 @@
1
1
  import LearningImage from './learning/image';
2
- <<<<<<< HEAD
3
2
  import LearningMobilenetImage from './learning/mobilenet_image';
4
- =======
5
-
6
- // 프로그레스 바를 표시하는 클래스
7
- class StatusBar {
8
- constructor(private container: HTMLElement) {}
9
- update(status: number, message: string) {
10
- this.container.innerText = `Status: ${status} ${message}`;
11
- }
12
- }
13
-
14
-
15
- async function appRun() {
16
- //////////////////////////////////////////////////////////////////////////////////////////
17
- const learningImage = new LearningImage({
18
- epochs: 30,
19
- batchSize: 32
20
- });
21
- learningImage.onProgress = (progress: number) => {
22
- const element = document.getElementById('progress-bar');
23
- if (element !== null) {
24
- const bar = new StatusBar(element);
25
- bar.update(progress, '%');
26
- }
27
- }
28
- learningImage.onLoss = (loss: number) => {
29
- const element = document.getElementById('loss-bar');
30
- if (element !== null) {
31
- const bar = new StatusBar(element);
32
- bar.update(loss, 'loss');
33
- }
34
- }
35
- //////////////////////////////////////////////////////////////////////////////////////////
36
- //////////////////////////////////////////////////////////////////////////////////////////
37
- //////////////////////////////////////////////////////////////////////////////////////////
38
-
39
- // root UI
40
- const container = document.createElement('div');
41
- container.id = 'root';
42
-
43
- // learning 준비 체크
44
- const learningReadyCheck = () => {
45
- if (!learningImage.ready()) {
46
- window.alert('준비된 데이터가 없습니다.');
47
- return false;
48
- }
49
- if (learningImage.running()) {
50
- window.alert('이미 진행 중입니다.');
51
- return false;
52
- }
53
- return true;
54
- };
55
-
56
- // 이미지 저장 버튼 클릭
57
- async function handleImageButtonClick(label: string) {
58
- // Canvas 생성
59
- const canvas = document.createElement('canvas');
60
- const video = document.createElement('video');
61
-
62
- // 웹캠 활성화
63
- if (navigator.mediaDevices.getUserMedia) {
64
- const stream = await navigator.mediaDevices.getUserMedia({ video: true });
65
- video.srcObject = stream;
66
- }
67
-
68
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
69
- video.addEventListener('loadedmetadata', () => {
70
- video.play(); // 비디오 플레이 시작
71
- });
72
-
73
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
74
- video.addEventListener('play', () => {
75
- canvas.width = 128;
76
- canvas.height = 128;
77
- const context = canvas.getContext('2d');
78
- if (context) {
79
- context.drawImage(video, 0, 0, canvas.width, canvas.height);
80
- learningImage.addData(label, context.getImageData(0, 0, canvas.width, canvas.height));
81
- }
82
- });
83
- container.appendChild(canvas);
84
- }
85
-
86
- // 추론하기 버튼
87
- async function handleInferButtonClick() {
88
- if(!learningReadyCheck()) {
89
- return;
90
- }
91
-
92
- // Canvas 생성
93
- const canvas = document.createElement('canvas');
94
- const video = document.createElement('video');
95
-
96
- // 웹캠 활성화
97
- if (navigator.mediaDevices.getUserMedia) {
98
- const stream = await navigator.mediaDevices.getUserMedia({ video: true });
99
- video.srcObject = stream;
100
- }
101
-
102
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
103
- video.addEventListener('loadedmetadata', () => {
104
- video.play(); // 비디오 플레이 시작
105
- });
106
-
107
- // 비디오가 메타데이터 로딩되면 캔버스에 그리고 이미지 캡처
108
- video.addEventListener('play', () => {
109
- canvas.width = 128;
110
- canvas.height = 128;
111
- const context = canvas.getContext('2d');
112
- if (context) {
113
- context.drawImage(video, 0, 0, canvas.width, canvas.height);
114
- learningImage.infer(context.getImageData(0, 0, canvas.width, canvas.height));
115
- }
116
- });
117
- container.appendChild(canvas);
118
- }
119
-
120
- // Train 학습하기 버튼
121
- async function handleTrainButtonClick() {
122
- if(learningReadyCheck()) {
123
- await learningImage.train();
124
- }
125
- }
126
-
127
- // image button UI
128
- const image1Button = document.createElement('button');
129
- image1Button.textContent = '라벨1 이미지';
130
- image1Button.addEventListener('click', () => handleImageButtonClick('라벨1 이미지'));
131
- container.appendChild(image1Button);
132
-
133
- // image button UI
134
- const image2Button = document.createElement('button');
135
- image2Button.textContent = '라벨2 이미지';
136
- image2Button.addEventListener('click', () => handleImageButtonClick('라벨2 이미지'));
137
- container.appendChild(image2Button);
138
-
139
- // save button UI
140
- const trainButton = document.createElement('button');
141
- trainButton.textContent = '모델 Train';
142
- trainButton.addEventListener('click', handleTrainButtonClick);
143
- container.appendChild(trainButton);
144
- document.body.appendChild(container);
145
-
146
- // image button UI
147
- const inferButton = document.createElement('button');
148
- inferButton.textContent = '예측하기';
149
- inferButton.addEventListener('click', () => handleInferButtonClick());
150
- container.appendChild(inferButton);
151
-
152
-
153
- }
154
- >>>>>>> 68f03c4696aa804e510cdbd6ebf6efd9e8eda5a4
155
3
 
156
4
  export { LearningImage, LearningMobilenetImage };
@@ -23,6 +23,10 @@ interface LearningInterface {
23
23
  // loss 정보
24
24
  onLoss(loss: number): void;
25
25
 
26
+ onTrainBegin(log: any): void;
27
+
28
+ onTrainEnd(log: any): void;
29
+
26
30
  // 학습 데이타 추가 data는 다른 클래스에 맞게 any로 설정
27
31
  addData(label: string, data: any): void;
28
32
  // 학습 진행
@@ -18,8 +18,9 @@ class LearningImage implements LearningInterface {
18
18
 
19
19
  constructor({
20
20
  epochs = 10,
21
- batchSize = 16
22
- }: { modelURL?: string, epochs?: number, batchSize?: number} = {}) {
21
+ batchSize = 16,
22
+ limitSize = 2,
23
+ }: { modelURL?: string, epochs?: number, batchSize?: number, limitSize?: number} = {}) {
23
24
  this.model = null;
24
25
  this.epochs = epochs;
25
26
  this.batchSize = batchSize;
@@ -33,6 +34,10 @@ class LearningImage implements LearningInterface {
33
34
 
34
35
  public onLoss: (loss: number) => void = () => {};
35
36
 
37
+ public onTrainBegin: (log: any) => void = () => {};
38
+
39
+ public onTrainEnd: (log: any) => void = () => {};
40
+
36
41
  // 학습 데이타 등록
37
42
  public addData(label: string, data: any): void {
38
43
  try {
@@ -58,10 +63,12 @@ class LearningImage implements LearningInterface {
58
63
 
59
64
  // 콜백 정의
60
65
  const customCallback = {
61
- onTrainBegin: () => {
66
+ onTrainBegin: (log: any) => {
67
+ this.onTrainBegin(log);
62
68
  console.log('Training has started.');
63
69
  },
64
- onTrainEnd: () => {
70
+ onTrainEnd: (log: any) => {
71
+ this.onTrainEnd(log);
65
72
  console.log('Training has ended.');
66
73
  this.isRunning = false;
67
74
  },
@@ -72,8 +79,8 @@ class LearningImage implements LearningInterface {
72
79
  console.log(`Batch ${batch} has ended.`);
73
80
  },
74
81
  onEpochBegin: (epoch: number, logs: any) => {
75
- const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
76
- this.onProgress(progress);
82
+ //const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
83
+ this.onProgress(epoch+1);
77
84
  console.log(`Epoch ${epoch+1} is starting.`);
78
85
  },
79
86
  onEpochEnd: (epoch: number, logs: any) => {
@@ -26,8 +26,9 @@ class LearningMobilenetImage implements LearningInterface {
26
26
  constructor({
27
27
  modelURL = 'https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json', // 디폴트 mobilenet 이미지
28
28
  epochs = 10,
29
- batchSize = 16
30
- }: { modelURL?: string, epochs?: number, batchSize?: number} = {}) {
29
+ batchSize = 16,
30
+ limitSize = 2,
31
+ }: { modelURL?: string, epochs?: number, batchSize?: number, limitSize?: number} = {}) {
31
32
  this.model = null;
32
33
  this.epochs = epochs;
33
34
  this.batchSize = batchSize;
@@ -35,14 +36,18 @@ class LearningMobilenetImage implements LearningInterface {
35
36
  this.modelURL = modelURL;
36
37
  this.isRunning = false;
37
38
  this.isReady = false;
38
- this.limitSize = 2;
39
+ this.limitSize = limitSize;
39
40
  }
40
41
 
41
42
  // 진행 상태를 나타내는 이벤트를 정의합니다.
42
43
  public onProgress: (progress: number) => void = () => {};
43
44
 
44
45
  public onLoss: (loss: number) => void = () => {};
45
-
46
+
47
+ public onTrainBegin: (log: any) => void = () => {};
48
+
49
+ public onTrainEnd: (log: any) => void = () => {};
50
+
46
51
  // 학습 데이타 등록
47
52
  public addData(label: string, data: any): void {
48
53
  try {
@@ -68,10 +73,12 @@ class LearningMobilenetImage implements LearningInterface {
68
73
 
69
74
  // 콜백 정의
70
75
  const customCallback = {
71
- onTrainBegin: () => {
76
+ onTrainBegin: (log: any) => {
77
+ this.onTrainBegin(log);
72
78
  console.log('Training has started.');
73
79
  },
74
- onTrainEnd: () => {
80
+ onTrainEnd: (log: any) => {
81
+ this.onTrainEnd(log);
75
82
  console.log('Training has ended.');
76
83
  this.isRunning = false;
77
84
  },
@@ -82,8 +89,8 @@ class LearningMobilenetImage implements LearningInterface {
82
89
  console.log(`Batch ${batch} has ended.`);
83
90
  },
84
91
  onEpochBegin: (epoch: number, logs: any) => {
85
- const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
86
- this.onProgress(progress);
92
+ //const progress = Math.floor(((epoch + 1) / this.epochs) * 100);
93
+ this.onProgress(epoch+1);
87
94
  console.log(`Epoch ${epoch+1} is starting.`);
88
95
  },
89
96
  onEpochEnd: (epoch: number, logs: any) => {
package/tsconfig.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES5",
3
+ "target": "ES6",
4
4
  "module": "CommonJS",
5
5
  "outDir": "build",
6
6
  "strict": true,
package/build/base.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/build/image.js DELETED
@@ -1,306 +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
- 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
- var __generator = (this && this.__generator) || function (thisArg, body) {
35
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
- function verb(n) { return function (v) { return step([n, v]); }; }
38
- function step(op) {
39
- if (f) throw new TypeError("Generator is already executing.");
40
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
41
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
- if (y = 0, t) op = [op[0] & 2, t.value];
43
- switch (op[0]) {
44
- case 0: case 1: t = op; break;
45
- case 4: _.label++; return { value: op[1], done: false };
46
- case 5: _.label++; y = op[1]; op = [0]; continue;
47
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
- default:
49
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
- if (t[2]) _.ops.pop();
54
- _.trys.pop(); continue;
55
- }
56
- op = body.call(thisArg, _);
57
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
- }
60
- };
61
- Object.defineProperty(exports, "__esModule", { value: true });
62
- var tf = __importStar(require("@tensorflow/tfjs"));
63
- var LearningImage = /** @class */ (function () {
64
- function LearningImage(_a) {
65
- var _b = _a === void 0 ? {} : _a, _c = _b.epochs, epochs = _c === void 0 ? 10 : _c, _d = _b.batchSize, batchSize = _d === void 0 ? 16 : _d;
66
- this.trainImages = [];
67
- this.MOBILE_NET_INPUT_WIDTH = 224;
68
- this.MOBILE_NET_INPUT_HEIGHT = 224;
69
- this.MOBILE_NET_INPUT_CHANNEL = 3;
70
- this.IMAGE_NORMALIZATION_FACTOR = 255.0;
71
- this.onProgress = function () { };
72
- this.onLoss = function () { };
73
- this.model = null;
74
- this.epochs = epochs;
75
- this.batchSize = batchSize;
76
- this.labels = [];
77
- this.isRunning = false;
78
- this.isReady = false;
79
- this.limitSize = 2;
80
- }
81
- // 학습 데이타 등록
82
- LearningImage.prototype.addData = function (label, data) {
83
- try {
84
- var tensor = tf.browser.fromPixels(data);
85
- console.log('addData', tensor);
86
- this.trainImages.push(tensor);
87
- this.labels.push(label);
88
- if (this.labels.length >= this.limitSize) {
89
- this.isReady = true;
90
- }
91
- return;
92
- }
93
- catch (error) {
94
- console.error('Model training failed', error);
95
- throw error;
96
- }
97
- };
98
- // 모델 학습 처리
99
- LearningImage.prototype.train = function () {
100
- return __awaiter(this, void 0, void 0, function () {
101
- var customCallback, _a, inputData, targetData, history_1, error_1;
102
- var _this = this;
103
- return __generator(this, function (_b) {
104
- switch (_b.label) {
105
- case 0:
106
- if (this.isRunning) {
107
- return [2 /*return*/, Promise.reject(new Error('Training is already in progress.'))];
108
- }
109
- customCallback = {
110
- onTrainBegin: function () {
111
- console.log('Training has started.');
112
- },
113
- onTrainEnd: function () {
114
- console.log('Training has ended.');
115
- _this.isRunning = false;
116
- },
117
- onBatchBegin: function (batch, logs) {
118
- console.log("Batch ".concat(batch, " is starting."));
119
- },
120
- onBatchEnd: function (batch, logs) {
121
- console.log("Batch ".concat(batch, " has ended."));
122
- },
123
- onEpochBegin: function (epoch, logs) {
124
- var progress = Math.floor(((epoch + 1) / _this.epochs) * 100);
125
- _this.onProgress(progress);
126
- console.log("Epoch ".concat(epoch + 1, " is starting."));
127
- },
128
- onEpochEnd: function (epoch, logs) {
129
- console.log("Epoch ".concat(epoch + 1, " has ended."));
130
- _this.onLoss(logs.loss);
131
- console.log('Loss:', logs.loss);
132
- }
133
- };
134
- _b.label = 1;
135
- case 1:
136
- _b.trys.push([1, 4, , 5]);
137
- this.isRunning = true;
138
- if (this.labels.length < this.limitSize) {
139
- return [2 /*return*/, Promise.reject(new Error('Please train Data need over 2 data length'))];
140
- }
141
- _a = this;
142
- return [4 /*yield*/, this._createModel(this.labels.length)];
143
- case 2:
144
- _a.model = _b.sent();
145
- inputData = this._preprocessedInputData(this.model);
146
- targetData = this._preprocessedTargetData();
147
- return [4 /*yield*/, this.model.fit(inputData, targetData, {
148
- epochs: this.epochs,
149
- batchSize: this.batchSize,
150
- callbacks: customCallback
151
- })];
152
- case 3:
153
- history_1 = _b.sent();
154
- console.log('Model training completed', history_1);
155
- return [2 /*return*/, history_1];
156
- case 4:
157
- error_1 = _b.sent();
158
- this.isRunning = false;
159
- console.error('Model training failed', error_1);
160
- throw error_1;
161
- case 5: return [2 /*return*/];
162
- }
163
- });
164
- });
165
- };
166
- // 추론하기
167
- LearningImage.prototype.infer = function (data) {
168
- return __awaiter(this, void 0, void 0, function () {
169
- var tensor, resizedTensor, reshapedTensor, predictions, predictionsData, classProbabilities, i, className, probability, existingProbability, error_2;
170
- return __generator(this, function (_a) {
171
- switch (_a.label) {
172
- case 0:
173
- if (this.model === null) {
174
- throw new Error('Model is null');
175
- }
176
- _a.label = 1;
177
- case 1:
178
- _a.trys.push([1, 3, , 4]);
179
- tensor = tf.browser.fromPixels(data);
180
- resizedTensor = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
181
- reshapedTensor = resizedTensor.expandDims(0);
182
- predictions = this.model.predict(reshapedTensor);
183
- return [4 /*yield*/, predictions.data()];
184
- case 2:
185
- predictionsData = _a.sent();
186
- classProbabilities = new Map();
187
- for (i = 0; i < predictionsData.length; i++) {
188
- className = this.labels[i];
189
- probability = predictionsData[i];
190
- existingProbability = classProbabilities.get(className);
191
- if (existingProbability !== undefined) {
192
- classProbabilities.set(className, existingProbability + probability);
193
- }
194
- else {
195
- classProbabilities.set(className, probability);
196
- }
197
- }
198
- console.log('Class Probabilities:', classProbabilities);
199
- return [2 /*return*/, classProbabilities];
200
- case 3:
201
- error_2 = _a.sent();
202
- throw error_2;
203
- case 4: return [2 /*return*/];
204
- }
205
- });
206
- });
207
- };
208
- // 모델 저장
209
- LearningImage.prototype.saveModel = function () {
210
- console.log('saved model');
211
- };
212
- // 진행중 여부
213
- LearningImage.prototype.running = function () {
214
- return this.isRunning;
215
- };
216
- LearningImage.prototype.ready = function () {
217
- return this.isReady;
218
- };
219
- // target 라벨 데이타
220
- LearningImage.prototype._preprocessedTargetData = function () {
221
- var _this = this;
222
- // 라벨 unique 처리 & 배열 리턴
223
- console.log('uniqueLabels.length', this.labels, this.labels.length);
224
- var labelIndices = this.labels.map(function (label) { return _this.labels.indexOf(label); });
225
- console.log('labelIndices', labelIndices);
226
- var oneHotEncode = tf.oneHot(tf.tensor1d(labelIndices, 'int32'), this.labels.length);
227
- console.log('oneHotEncode', oneHotEncode);
228
- return oneHotEncode;
229
- };
230
- // 입력 이미지 데이타
231
- LearningImage.prototype._preprocessedInputData = function (model) {
232
- var _this = this;
233
- // 이미지 배열을 배치로 변환 - [null, 224, 224, 3]
234
- var inputShape = model.inputs[0].shape;
235
- console.log('inputShape', inputShape);
236
- // inputShape를 이와 같이 포멧 맞춘다. for reshape to [224, 224, 3]
237
- var inputShapeArray = inputShape.slice(1);
238
- console.log('inputShapeArray', inputShapeArray);
239
- var inputBatch = tf.stack(this.trainImages.map(function (image) {
240
- // 이미지 전처리 및 크기 조정 등을 수행한 후에
241
- // 모델의 입력 형태로 변환하여 반환
242
- var xs = _this._preprocessData(image); // 전처리 함수는 사용자 정의해야 함
243
- return tf.reshape(xs, inputShapeArray);
244
- }));
245
- return inputBatch;
246
- };
247
- // 모델 학습하기 위한 데이타 전처리 단계
248
- LearningImage.prototype._preprocessData = function (tensor) {
249
- try {
250
- // mobilenet model summary를 하면 위와 같이 224,224 사이즈의 입력값 설정되어 있다. ex) input_1 (InputLayer) [null,224,224,3]
251
- var resizedImage = tf.image.resizeBilinear(tensor, [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT]);
252
- // 이미지를 [0,1] 범위로 정규화 255로 나뉜 픽셀값
253
- var normalizedImage = resizedImage.div(this.IMAGE_NORMALIZATION_FACTOR);
254
- // expandDims(0)을 하여 차원을 추가하여 4D텐서 반환
255
- return normalizedImage.expandDims(0);
256
- }
257
- catch (error) {
258
- console.error('Failed to _preprocessData data', error);
259
- throw error;
260
- }
261
- };
262
- // 모델 저장
263
- LearningImage.prototype._createModel = function (numClasses) {
264
- return __awaiter(this, void 0, void 0, function () {
265
- var inputShape, model;
266
- return __generator(this, function (_a) {
267
- try {
268
- inputShape = [this.MOBILE_NET_INPUT_WIDTH, this.MOBILE_NET_INPUT_HEIGHT, this.MOBILE_NET_INPUT_CHANNEL];
269
- model = tf.sequential();
270
- model.add(tf.layers.conv2d({
271
- inputShape: inputShape,
272
- filters: 32,
273
- kernelSize: 3,
274
- activation: 'relu'
275
- }));
276
- model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
277
- model.add(tf.layers.conv2d({
278
- filters: 64,
279
- kernelSize: 3,
280
- activation: 'relu'
281
- }));
282
- model.add(tf.layers.maxPooling2d({ poolSize: 2 }));
283
- model.add(tf.layers.flatten());
284
- model.add(tf.layers.dense({
285
- units: numClasses,
286
- activation: 'softmax'
287
- }));
288
- model.compile({
289
- loss: (numClasses === 2) ? 'binaryCrossentropy' : 'categoricalCrossentropy',
290
- optimizer: tf.train.adam(),
291
- metrics: ['accuracy']
292
- });
293
- model.summary();
294
- return [2 /*return*/, model];
295
- }
296
- catch (error) {
297
- console.error('Failed to load model', error);
298
- throw error;
299
- }
300
- return [2 /*return*/];
301
- });
302
- });
303
- };
304
- return LearningImage;
305
- }());
306
- exports.default = LearningImage;
package/build/index.js DELETED
@@ -1,10 +0,0 @@
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
- var image_1 = __importDefault(require("./learning/image"));
8
- exports.LearningImage = image_1.default;
9
- var mobilenet_image_1 = __importDefault(require("./learning/mobilenet_image"));
10
- exports.LearningMobilenetImage = mobilenet_image_1.default;
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });