JavaScriptでディープラーニング

F0e950c6bf20815f3d169f063d3c5d4f?s=47 Aipa
July 08, 2018

 JavaScriptでディープラーニング

Tensorflow.jsを使ってみた

F0e950c6bf20815f3d169f063d3c5d4f?s=128

Aipa

July 08, 2018
Tweet

Transcript

  1. 10.
  2. 11.
  3. 12.
  4. 15.
  5. 19.

    TDSJQUλάͰϩʔυ <head> <!-- Load TensorFlow.js --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.8.0"> </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>
  6. 20.

    OQNͰΠϯετʔϧ $ npm install @tensorflow/tfjs w QZUIPO͕ඞཁHZQ͕1ZUIPOܥʹରԠ͍ͯ͠ͳ͍ w HZQͬͯͳΜͧʁ w

    OPEFͷόʔδϣϯ͕YYͩͱΤϥʔ w OPEF⒏͕ରԠ͍ͯ͠ͳ͍ w /PEFKTͷੈք͔ΒμΠφϛοΫϥΠϒϥϦͷؔ਺ΛݺͿਆΞυΦϯ w YY΁μ΢ϯάϨʔυ
  7. 21.

    ιʔεΛॻ͘ 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
  8. 22.

    ίϯύΠϧ $ npm install -g parcel-bundler $ parcel build src/index.html

    --public-url ./ $ open dist/index.html w Α͘Θ͔ΒΜ͕ɺQBSDFM͕ଟ͍ʢυΩϡϝϯτ΋QBSDFMʣ w 1BSDFMͰ࢝ΊΔ5FOTPS'MPXKT ϒϥ΢β/PEFKT
  9. 23.
  10. 30.

    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
  11. 31.

    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Λཱͯͨʣ
  12. 32.

    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 Λ࢖ ͑͹Α͍