A Pen by Shigeru Kobayashi on CodePen.
Last active
August 31, 2018 13:38
-
-
Save kotobuki/104ff3b9770431f3a41bf31220c8c99e to your computer and use it in GitHub Desktop.
Linear Regression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://blog.codepen.io/2016/06/08/can-adjust-infinite-loop-protection-timing/ | |
window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 5000; | |
// Reference | |
// https://gist.github.com/NatuMyers/a55cef9193095ce5485893ee7ca6ffab | |
async function linearRegression() { | |
const model = tf.sequential(); | |
model.add(tf.layers.dense({ units: 1, inputShape: [1] })); | |
model.compile({ optimizer: "sgd", loss: "meanSquaredError" }); | |
// y = 2 * x + 1 | |
const xs = tf.tensor2d([1, 2, 3, 4, 5], [5, 1]); | |
const ys = tf.tensor2d([3, 5, 7, 9, 11], [5, 1]); | |
const numBatches = 10; | |
for (let i = 0; i < numBatches; i++) { | |
const history = await model.fit(xs, ys, { epochs: 10 }); | |
console.log("Loss after batch " + i + ": " + history.history.loss[0]); | |
} | |
// Generates output predictions for the input samples | |
model.predict(tf.tensor2d([3.5], [1, 1])).print(); | |
// Print the weight | |
model.layers[0].getWeights()[0].print(); | |
// Print the bias | |
model.layers[0].getWeights()[1].print(); | |
} | |
linearRegression(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.5/tf.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment