Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tensorflow.js demo
const callbacks = {
onEpochEnd: async (epoch, logs) => {
console.log("epoch: " + epoch + JSON.stringify(logs))
}
};
// 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]);
// Build and compile model.
async function basicRegression(){
// Build a sequential model
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
// Train model with fit().
await model.fit(xs, ys, {epochs: 100, validationSplit: 0.1, callbacks: callbacks});
// Run inference with predict().
model.predict(tf.tensor2d([[5]], [1, 1])).print();
}
// Create a basic regression model
basicRegression();
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- load Tensorflow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1>Tensorflow.js Core API</h1>
<!-- <script src="index.js"></script> -->
<script type="text/javascript">
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- load Tensorflow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
</head>
<body>
<h1>Tensorflow.js Core API</h1>
<!-- <script src="index.js"></script> -->
<script type="text/javascript">
const a = tf.tensor([1, 2, 3, 4]);
const b = tf.tensor([10, 20, 30, 40]);
const y = a.add(b); // equivalent to tf.add(a, b)
const z = a.mul(b); // equivalent to tf.mul(a, b)
y.print();
z.print();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.