TensorflowJs shape increase while training

51 Views Asked by At

I'm trying to teach my model on tensorflow to classify images but cannot reach any suitable effect.

For base im generating main model.json on https://teachablemachine.withgoogle.com/train/image. Then i go and write code

const tf = require('@tensorflow/tfjs')
const  tfnode = require('@tensorflow/tfjs-node')
const fs = require('fs-extra');
const feature_file = "image3.jpg"//human
const feature_file2 = "imgs/3.jpg"//not human

const sharp = require('sharp');
const x = 224
const y = 224
const height = x
const width = y

f()
async function f(){
    const imageBuffer = await fs.readFile(feature_file);
const tensorFeature = tfnode.node.decodeImage( await sharp(imageBuffer).resize(x, y).toBuffer()) // create a tensor for the image
const imageBuffer2 = await fs.readFile(feature_file2);
const tensorFeature2 = tfnode.node.decodeImage( await sharp(imageBuffer2).resize(x, y).toBuffer()) // create a tensor for the image

labelArray = ['Class 1', 'Class 2'] // maybe 0 for dog, 1 for cat and 2 for birds
tensorFeatures = tf.stack([tensorFeature, tensorFeature2])
tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'),2);
    // console.log(tensorFeatures)
    // console.log(tensorLabels)
    
    const model = await tf.loadLayersModel('file://model4//model.json')    
    model.compile({loss: 'meanSquaredError', optimizer: tf.train.adam(1e-3), metrics: ['accuracy']});
    model.summary()
    model.fit(tensorFeatures, tensorLabels, {
        epochs: 12,
        batchSize:1
    }).then((res)=>{
        console.log(res)
      })
    model.save(`file://model3`)

So problem is if i generated in teachable machine 2 classes and trying to add 3th one, it asks that input shape must be [, 2]. So i add

model.add(tf.layers.dense({units: 3, activation: 'softmax'}));

And change tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'),2); to tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'),3);

But after all of this operations my model classifies images fully wrongly. Is any way available to do some images training in Node.js tensorflow? I'm trying to do it second week and have no idea.

0

There are 0 best solutions below