image_output_1.png
from sklearn.model_selection import train_test_split

from tensorflow import keras

import cv2

import matplotlib.pyplot as plt

import numpy as np

import os

import pandas as pd

import seaborn as sns

import tensorflow as tf

train = '/kaggle/input/rice-image-dataset/Rice_Image_Dataset'
file_names = os.listdir(train)
pd.DataFrame(file_names, columns=['Names'])

files = []
for file in file_names:
    if file == 'Rice_Citation_Request.txt':
        continue
    files.append(file)
files

size_number = []
size = []
for file in files:
    path = os.path.join(train, file)
    size_number.append(len(os.listdir(path)))
    for img in os.listdir(path):
        image = cv2.imread(os.path.join(path, img))
        size.append(image.shape)
pd.DataFrame(size_number, columns=['size'], index=files)

pd.DataFrame(pd.Series(size).value_counts(), columns=['Number'])

train_image = []
label = []
for file in files:
    path = os.path.join(train, file)
    for img in os.listdir(path):
        image = cv2.imread(os.path.join(path, img))
        image = cv2.resize(image, (100, 100))
        train_image.append(image)
        label.append(file)
pd.DataFrame(label, columns=['label'])

for n, i in enumerate(np.random.randint(0, len(train_image), 100)):
    plt.axis('off')

code = {}
label_uniqe = list(pd.unique(label))
for i in range(5):
    code[label_uniqe[i]] = i
code

def get_Name(N):
    for x, y in code.items():
        if y == N:
            return x
label2 = []
for i in label:
    label2.append(code[i])
label2 = np.array(label2)
pd.DataFrame(label2)

train_image = np.array(train_image)

X_train, X_test, y_train, y_test = train_test_split(train_image, label2, test_size=0.1, random_state=44, shuffle=True)

shape = (100, 100, 3)
num_class = 5
model = keras.models.Sequential()
model.add(keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=tf.nn.relu, input_shape=shape))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.MaxPool2D((3, 3)))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=tf.nn.relu))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.MaxPool2D((3, 3)))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Conv2D(filters=128, kernel_size=(3, 3), activation=tf.nn.relu))
model.add(keras.layers.BatchNormalization())
model.add(keras.layers.MaxPool2D((3, 3)))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(512, activation=tf.nn.relu))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(128, activation=tf.nn.relu))
model.add(keras.layers.Dropout(0.3))
model.add(keras.layers.Dense(num_class, activation=tf.nn.softmax))

model.summary()

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
hist = model.fit(X_train, y_train, epochs=5)

hist_ = pd.DataFrame(hist.history)
hist_

score, acc = model.evaluate(X_test, y_test)

y_pred = model.predict(X_test)
y_pred

pred_Name = []
pred_number = []
for row in y_pred:
    N = np.argmax(row)
    pred_Name.append(get_Name(N))
    pred_number.append(N)
pd.DataFrame(pred_Name, columns=['pred Names'])