Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScriptでディープラーニング

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.
Avatar for Aipa Aipa
July 08, 2018

 JavaScriptでディープラーニング

Tensorflow.jsを使ってみた

Avatar for Aipa

Aipa

July 08, 2018
Tweet

More Decks by Aipa

Other Decks in Technology

Transcript

  1. TDSJQUλάͰϩʔυ <head> <!-- Load TensorFlow.js --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"> </script> <!--

    Place your code in the script tag below. You can also use an external .js file --> <script> const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); 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).then(() => { model.predict(tf.tensor2d([5], [1, 1])).print(); }); </script> </head>
  2. OQNͰΠϯετʔϧ $ npm install @tensorflow/tfjs w QZUIPO͕ඞཁHZQ͕1ZUIPOܥʹରԠ͍ͯ͠ͳ͍ w HZQͬͯͳΜͧʁ w

    OPEFͷόʔδϣϯ͕YYͩͱΤϥʔ w OPEF⒏͕ରԠ͍ͯ͠ͳ͍ w /PEFKTͷੈք͔ΒμΠφϛοΫϥΠϒϥϦͷؔ਺ΛݺͿਆΞυΦϯ w YY΁μ΢ϯάϨʔυ
  3. ιʔεΛॻ͘ import * as tf from '@tensorflow/tfjs'; // Define a

    model for linear regression. const model = tf.sequential(); model.add(tf.layers.dense({units: 1, inputShape: [1]})); <script src="example.js"></script> FYBNQMFKT JOEFYIUNM
  4. ίϯύΠϧ $ npm install -g parcel-bundler $ parcel build src/index.html

    --public-url ./ $ open dist/index.html w Α͘Θ͔ΒΜ͕ɺQBSDFM͕ଟ͍ʢυΩϡϝϯτ΋QBSDFMʣ w 1BSDFMͰ࢝ΊΔ5FOTPS'MPXKT ϒϥ΢β/PEFKT
  5. KTͰΑΉΑ͏ʹม׵ $ pip install tensorflowjs $ tensorflowjs_converter --input_format keras model.hdf5

    ./ $ ls group1-shard1of1 group3-shard1of1 model.json group2-shard1of1 group4-shard1of1 w UFOTPSqPXKTΛQJQͰΠϯετʔϧʢಾʣ w OVNQZ΍ΒɺLFSBT΍ΒόʔδϣϯͷґଘͰೖΕସ͑ΒΕΔͷͰɺ QZFOWͱ͔Ͱࢼ͢؀ڥΛม͑ͨ΄͏͕͍͍ w ࢀߟIUUQTKTUFOTPSqPXPSHUVUPSJBMTJNQPSULFSBTIUNM
  6. KTଆͰΑΉ async function loadModel() { tf.loadModel('https://localhost:8000/mobilenet/model.json') .then(model => { const

    m = tf.model({inputs: model.inputs, outputs: model.outputs}); const img = webcam.capture(); const img2 = _reshape(img); // warmup const predicts = m.predict(img2); console.log(predicts.dataSync()); console.log(predicts.argMax().dataSync()[0]); mobilenet = m; return m; }); } w UFOTPSqPXͱ͍͏ΑΓɺLFSBTͬΆ͍ w XBSNVQڬ·ͳ͍ͱ࠷ॳͷQSFEJDU͕ॏ͘ʁࣦഊ͢Δ w 44-͕ඞཁʢࣗݾূ໌ॻΛ࡞ͬͯɺ1ZUIPOͰ'MBTLΛཱͯͨʣ
  7. KTଆͰΑΉQSFEJDU async function predict() { if (isPredicting) { isPredicting =

    false; const predictedClass = tf.tidy(() => { var imgElement = document.getElementById('get-image'); var _img = preprocessing(imgElement); // javascript data -> Tensor var img = tf.fromPixels(_img, 1); const img2 = _reshape(img); const predictions = mobilenet.predict(img2); return predictions.argMax(); }); const classId = (await predictedClass.data()); return classId; } } w ΰϛΈ͍ͨͳม਺໊࢖͍ͬͯΔ͕ڐͯ͠΄͍͠ w 5FOTPS͔Β+4ͷσʔλʹ໭͍ͨ͠৔߹͸ɺEBUB ͱ͔EBUB4ZOD Λ࢖ ͑͹Α͍