Vous êtes sur la page 1sur 7

MACHINE LEARNING

OLEH : Fatan Kasyidi & Ridwan Ilyas

Regresi Linier

index.html
<script
src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.15.3/dist/tf.min.js"></s
cript>
<script src="regresi.js"></script>

regresi.js
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.


const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.


model.fit(xs, ys, {epochs: 10}).then(() => {
// Use the model to do inference on a data point the model hasn't seen
before:
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});

Tugas:
1. Cek hasil pada console browser
Lakukan refresh beberapa kali
Analisis hasilnya
2. Jelaskan semua syntax dari tensorflow.js sesuai dokumentasi pada
https://js.tensorflow.org/api/latest/index.html
3. Lakukan analis regresi untuk data:
Stres kerja Kinerja
1 28 21
2 21 24
3 23 27
4 17 26
5 25 20
6 22 23
7 19 21

1
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

index2.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.1">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.dom.js"></s
cript>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>

sketch.js
// Linear Regression with TensorFlow.js and p5 js
let x_variable = [];
let y_variable = [];

let m, b;

const learningRate = 0.5;


const optimizer = tf.train.sgd(learningRate);

function setup() {
createCanvas(400, 400);
m = tf.variable(tf.scalar(random(1)));
b = tf.variable(tf.scalar(random(1)));
}

function loss(pred, labels) {


return pred.sub(labels).square().mean();
}

function predict(x) {
const xs = tf.tensor1d(x);
// y = mx + b;
const ys = xs.mul(m).add(b);
return ys;
}

function mousePressed() {
let x = map(mouseX, 0, width, 0, 1);
let y = map(mouseY, 0, height, 1, 0);
x_variable.push(x);
y_variable.push(y);
}

function draw() {

2
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

tf.tidy(() => {
if (x_variable.length > 0) {
const ys = tf.tensor1d(y_variable);
optimizer.minimize(() => loss(predict(x_variable), ys));
}
});

background(0);

stroke(255);
strokeWeight(8);
for (let i = 0; i < x_variable.length; i++) {
let px = map(x_variable[i], 0, 1, 0, width);
let py = map(y_variable[i], 0, 1, height, 0);
point(px, py);
}

const lineX = [0, 1];

const ys = tf.tidy(() => predict(lineX));


let lineY = ys.dataSync();
ys.dispose();

let x1 = map(lineX[0], 0, 1, 0, width);


let x2 = map(lineX[1], 0, 1, 0, width);

let y1 = map(lineY[0], 0, 1, height, 0);


let y2 = map(lineY[1], 0, 1, height, 0);

strokeWeight(2);
line(x1, y1, x2, y2);

console.log(tf.memory().numTensors);
//noLoop();
}

Tugas:
1. Cek hasil program pada browser
2. Buat ulasan materi strategi numerik menggunakan regresi

3
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

Regresi Polinomial

index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.1">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.dom.js"></s
cript>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>

sketch.js
let x_variable = [];
let y_variable = [];

let a, b, c, d;
let dragging = false;

const learningRate = 0.2;


const optimizer = tf.train.adam(learningRate);

function setup() {
createCanvas(400, 400);
a = tf.variable(tf.scalar(random(-1, 1)));
b = tf.variable(tf.scalar(random(-1, 1)));
c = tf.variable(tf.scalar(random(-1, 1)));
d = tf.variable(tf.scalar(random(-1, 1)));
}

function loss(pred, labels) {


return pred.sub(labels).square().mean();
}

function predict(x) {
const xs = tf.tensor1d(x);
// y = ax^3 + bx^2 + cx + d
const ys = xs.pow(tf.scalar(3)).mul(a)
.add(xs.square().mul(b))
.add(xs.mul(c))
.add(d);
return ys;
}

4
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

function mousePressed() {
dragging = true;
}
function mouseReleased() {
dragging = false;
}
function draw() {
if (dragging) {
let x = map(mouseX, 0, width, -1, 1);
let y = map(mouseY, 0, height, 1, -1);
x_variable.push(x);
y_variable.push(y);
} else {
tf.tidy(() => {
if (x_variable.length > 0) {
const ys = tf.tensor1d(y_variable);
optimizer.minimize(() => loss(predict(x_variable), ys));
}
});
}

background(0);
stroke(255);
strokeWeight(8);
for (let i = 0; i < x_variable.length; i++) {
let px = map(x_variable[i], -1, 1, 0, width);
let py = map(y_variable[i], -1, 1, height, 0);
point(px, py);
}

const curveX = [];


for (let x = -1; x <= 1; x += 0.05) {
curveX.push(x);
}

const ys = tf.tidy(() => predict(curveX));


let curveY = ys.dataSync();
ys.dispose();

beginShape();
noFill();
stroke(255);
strokeWeight(2);
for (let i = 0; i < curveX.length; i++) {
let x = map(curveX[i], -1, 1, 0, width);
let y = map(curveY[i], -1, 1, height, 0);
vertex(x, y);
}
endShape();
}
Tugas:
1. Cek hasil program pada browser
2. Buat ulasan materi strategi numerik menggunakan regresi polynomial

5
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

Layer, Dense
index.html
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest">
</script>
</head>
<body>
<h4>Tiny TFJS example<hr/></h4>
<script src="./model.js"></script>
</body>
</html>

model.js
// Build and compile model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});

// Generate some synthetic data for training.


const xs = tf.tensor2d([[1], [2], [3], [4]], [4, 1]);
const ys = tf.tensor2d([[1], [3], [5], [7]], [4, 1]);

// Train model with fit().


await model.fit(xs, ys, {epochs: 1000});

// Run inference with predict().


model.predict(tf.tensor2d([[5]], [1, 1])).print();

Tugas:
1. Cek hasil pada console browser
Lakukan refresh beberapa kali
Analisis hasilnya
2. Berikan penjelasan tentang tf.sequential() dan seluruh fungsi yang
dimilikinya

6
MACHINE LEARNING
OLEH : Fatan Kasyidi & Ridwan Ilyas

index2.html
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest">
</script>
</head>
<body>
<h4>Tiny TFJS example<hr/></h4>
<div id="micro-out-div">Training...</div>
<script src="./model2.js"></script>
</body>
</html>

model2.js
async function run() {
// Create a simple model.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training. (y = 2x - 1)


const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

// Train the model using the data.


await model.fit(xs, ys, {epochs: 250});

// Use the model to do inference on a data point the model hasn't seen.
// Should print approximately 39.
document.getElementById('micro-out-div').innerText =
model.predict(tf.tensor2d([20], [1, 1])).dataSync();
}

run();
Tugas:
1. Cek hasil pada browser
2. Jelaskan perbedaan dengan model.js
3. Buatlah sebuah multilayer perseptron dengan 2 layer dense untuk data
yang sama

Vous aimerez peut-être aussi