Playground
TensorFlow.js
머신러닝 모델 학습 & 추론
model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// TensorFlow.js - Linear Regression // Predicting y = 2x + 1 console.log("TensorFlow.js Linear Regression"); console.log("================================\n"); // Training data: y = 2x + 1 const xs = tf.tensor2d([0, 1, 2, 3, 4, 5, 6, 7], [8, 1]); const ys = tf.tensor2d([1, 3, 5, 7, 9, 11, 13, 15], [8, 1]); console.log("Training data: y = 2x + 1"); console.log("x: [0, 1, 2, 3, 4, 5, 6, 7]"); console.log("y: [1, 3, 5, 7, 9, 11, 13, 15]\n"); // Build model const model = tf.sequential(); model.add(tf.layers.dense({ units: 1, inputShape: [1] })); model.compile({ optimizer: tf.train.sgd(0.01), loss: 'meanSquaredError' }); console.log("Training model (200 epochs)..."); const start = performance.now(); await model.fit(xs, ys, { epochs: 200, callbacks: { onEpochEnd: (epoch, logs) => { if ((epoch + 1) % 50 === 0) { console.log(` Epoch ${epoch + 1}: loss = ${logs.loss.toFixed(6)}`); } } } }); const elapsed = ((performance.now() - start) / 1000).toFixed(2); console.log(`\nTraining completed in ${elapsed}s\n`); // Predictions console.log("Predictions:"); const testValues = [10, 20, 50, 100]; for (const x of testValues) { const pred = model.predict(tf.tensor2d([x], [1, 1])); const value = pred.dataSync()[0]; console.log(` x = ${x} → y = ${value.toFixed(2)} (expected: ${2 * x + 1})`); } // Get learned weights const weights = model.getWeights(); console.log(`\nLearned: w = ${weights[0].dataSync()[0].toFixed(4)}, b = ${weights[1].dataSync()[0].toFixed(4)}`); console.log("Expected: w = 2, b = 1");
Preview
Console
TensorFlow.js
model.js
UTF-8
Ln 1, Col 1
Spaces: 2