#!/usr/bin/env nodeconst tf = require(`@tensorflow/tfjs-node${process.env.GPU === 'true' ? '-gpu' : ''}`);const model = tf.sequential();const featuresCount = 1;model.add(tf.layers.dense({ inputDim: featuresCount, units: 128 }));model.add(tf.layers.dense({ inputDim: 128, units: 128 }));model.add(tf.layers.dense({ inputDim: 128, units: 1 }));
async function time(str, fn) { if (str) { process.stdout.write(`${str}... `); } const start = Date.now(); const out = await (fn || str)(); console.log(`done in ${(Date.now() - start) / 1000}s`); return Promise.resolve(out);}
const AMOUNT = 10000;const EPOCHS = 50;const LEARNING_RATE = 0.001;
time(`Training ${EPOCHS} epochs`, async () => { for (let i = 0; i < EPOCHS; i += 1) { tf.tidy(() => { const xs = tf.tensor2d(Array(AMOUNT).fill(0).map((x, i) => [Math.random()])); const ys = tf.tensor2d(Array(AMOUNT).fill(0).map((x, i) => [Math.random() + 10])); tf.train.sgd(LEARNING_RATE).minimize(() => model.apply(xs).sub(ys).square().mean()); }); }});
#!/usr/bin/env python3import tensorflow as tfimport numpy as npimport timeimport sysimport random
features_count = 1model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(128, input_shape=[1]))model.add(tf.keras.layers.Dense(128))model.add(tf.keras.layers.Dense(1))
class Timer: def __init__(self, title=None): self.title = title def __enter__(self): self.start = time.time() if self.title: sys.stdout.write(f'{self.title}... ') sys.stdout.flush() def __exit__(self, *args): duration = time.time() - self.start print(f'done in {duration}s')
AMOUNT = 10000EPOCHS = 50LEARNING_RATE = 0.001
with Timer(f'Training {EPOCHS} epochs'): sess = tf.keras.backend.get_session() inputs = tf.placeholder(shape=[AMOUNT, features_count], dtype=tf.float32) labels = tf.placeholder(shape=[AMOUNT, 1], dtype=tf.float32) loss = tf.reduce_mean(tf.square(labels - model(inputs))) optimizer = tf.train.GradientDescentOptimizer(LEARNING_RATE) train = optimizer.minimize(loss, var_list=model.trainable_variables) for i in range(EPOCHS): xs = np.random.random((AMOUNT, 1)) ys = np.random.random((AMOUNT, 1)) + 10 sess.run(train, feed_dict = { inputs: xs, labels: ys })
--
You received this message because you are subscribed to the Google Groups "TensorFlow.js Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to tfjs+uns...@tensorflow.org.
Visit this group at https://groups.google.com/a/tensorflow.org/group/tfjs/.
To view this discussion on the web visit https://groups.google.com/a/tensorflow.org/d/msgid/tfjs/bb5ef9f7-05b4-4111-9d2d-c0db37d12aa0%40tensorflow.org.
#!/usr/bin/env node
const tf = require(`@tensorflow/tfjs-node${process.env.GPU === 'true' ? '-gpu' : ''}`);
async function time(str, fn) { if (str) { process.stdout.write(`${str}... `); } const start = Date.now(); const out = await (fn || str)(); console.log(`done in ${(Date.now() - start) / 1000}s`); return Promise.resolve(out);}
(async () => {
const AMOUNT = 2000;
function randomTensor() { const data = Array(AMOUNT).fill(0).map((x, i) => [Math.random()]); return tf.tensor2d(data);}
await time(`Creating ${AMOUNT} tensors`, async () => { for (let i = 0; i < AMOUNT; i++) { randomTensor().dispose(); }});
console.log();console.log("Now, let's pass shape to tf.tensor:");
function fasterRandomTensor() { const data = Array(AMOUNT).fill(0).map((x, i) => Math.random()); return tf.tensor(data, [AMOUNT, 1], 'float32');}
await time(`Creating ${AMOUNT} "faster" tensors`, async () => { for (let i = 0; i < AMOUNT; i++) { fasterRandomTensor().dispose(); }});
console.log();console.log("Now, let's pass shape and Float32Arrays to tf.tensor:");
function fastestRandomTensor() { const data = new Float32Array(Array(AMOUNT).fill(0).map((x, i) => Math.random())); return tf.tensor(data, [AMOUNT, 1], 'float32');}
await time(`Creating ${AMOUNT} "fastest" tensors`, async () => { for (let i = 0; i < AMOUNT; i++) { fastestRandomTensor().dispose(); }});
})().catch(console.error);
Creating 2000 tensors... done in 10.484s
Now, let's pass shape to tf.tensor:Creating 2000 "faster" tensors... done in 2.026s
Now, let's pass shape and Float32Arrays to tf.tensor:Creating 2000 "fastest" tensors... done in 0.211s
--
You received this message because you are subscribed to the Google Groups "TensorFlow.js Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to tfjs+uns...@tensorflow.org.
Visit this group at https://groups.google.com/a/tensorflow.org/group/tfjs/.
To view this discussion on the web visit https://groups.google.com/a/tensorflow.org/d/msgid/tfjs/cf3ecf69-7601-4138-a8e0-bf8f5d143a3b%40tensorflow.org.