Tensorflow ML model classes Issue

Viewed 54

I created a tflite model and try to deploy in my android app. I successfully deployed but the result that i got from it was wrong. like when i initalize the classes of citrus disease btw my Ml model is about citrus disease detection. when i initalize the classes in my app code. Then result from it that i got was the same result on different images of the fruits but on jupiter notebook where i created my model showing accruate result. here is my android app code where i deploy my model. Code:

public void classifyImage(Bitmap image){
    mDetect = findViewById(R.id.D_btn);

    mDetect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {

                Modelf model = Modelf.newInstance(getApplicationContext());

                // Creates inputs for reference.
                TensorBuffer inputFeature0 = TensorBuffer.createFixedSize(new int[]{1, 256, 256, 3}, DataType.FLOAT32);
                ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * imagesize * imagesize * 3);
                byteBuffer.order(ByteOrder.nativeOrder());

                int[] intValues = new int[imagesize * imagesize];
                image.getPixels(intValues, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
                int pixel = 0;
                for(int i = 0; i < imagesize; i++){
                    for(int j = 0; j < imagesize; j++){
                        int val = intValues[pixel++];
                        byteBuffer.putFloat(((val >> 16) & 0xFF) * (1.f / 1));
                        byteBuffer.putFloat(((val >> 8) & 0xFF) * (1.f / 1));
                        byteBuffer.putFloat((val  & 0xFF) * (1.f / 1));
                    }
                }

                inputFeature0.loadBuffer(byteBuffer);

                // Runs model inference and gets result.
                Modelf.Outputs outputs = model.process(inputFeature0);
                TensorBuffer outputFeature0 = outputs.getOutputFeature0AsTensorBuffer();

                float[] confidence = outputFeature0.getFloatArray();
                int maxPos = 0;
                float maxConfidence = 0;
                for(int i = 0; i < confidence.length; i++){
                    if(confidence[i] > maxConfidence){
                        maxConfidence = confidence[i];
                        maxPos = i;
                    }
                }
                String[] classes = {"black-spot","citrus-canker"};
                String result= classes[maxPos];

                Intent Intent = new Intent(fdetection.this,fresult.class);

                Intent.putExtra("Disease",result);
                startActivity(Intent);

                // Releases model resources if no longer used.
                model.close();
            } catch (IOException e) {
                // TODO Handle the exception
            }
        }
    });

}

like in above code where i initialize classes. i got only "citrus-canker" in the result of the image i replace the names of the classes and then i got only "black spot".

here is my python model code:

def get_dataset_partitions_tf(data, train_split=0.8, val_split=0.1, test_split=0.1, shuffle=True, shuffle_size=10000):
assert (train_split + test_split + val_split) == 1

data_size = len(data)

if shuffle:
    data = data.shuffle(shuffle_size, seed=12)

train_size = int(train_split * data_size)
val_size = int(val_split * data_size)

train_ds = data.take(train_size)    
val_ds = data.skip(train_size).take(val_size)
test_ds = data.skip(train_size).skip(val_size)

return train_ds, val_ds, test_ds
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)
val_ds = val_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)
test_ds = test_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)

resize_and_rescale = tf.keras.Sequential([


 layers.experimental.preprocessing.Resizing(IMAGE_SIZE, IMAGE_SIZE),
  layers.experimental.preprocessing.Rescaling(1./255),])

data_augmentation = tf.keras.Sequential([


layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
  layers.experimental.preprocessing.RandomRotation(0.2),])

input_shape = (BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, CHANNELS)
n_classes = 2

model = models.Sequential([
resize_and_rescale,
layers.Conv2D(32, kernel_size = (3,3), activation='relu', input_shape=input_shape),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64,  kernel_size = (3,3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(n_classes, activation='softmax'),])
model.build(input_shape=input_shape)

model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['accuracy'])

history = model.fit(
train_ds,
batch_size=BATCH_SIZE,
validation_data=val_ds,
verbose=1,
epochs=50,)

can you guys please help me where is the problem i get.

1 Answers

This issue is because of my Model not by java code that I use in my app. I resolve this issue by changing my dataset images and using a high-resolution dataset.

Related