{"id":15066248,"url":"https://github.com/canoksuzoglu1/rice-classification-cnn","last_synced_at":"2026-02-13T22:42:25.015Z","repository":{"id":257000632,"uuid":"857106195","full_name":"canoksuzoglu1/Rice-Classification-CNN","owner":"canoksuzoglu1","description":"Rice-Classification-CNN is a TensorFlow-based project for classifying rice varieties using Convolutional Neural Networks. It utilizes a publicly available dataset to train and evaluate a CNN model for accurate classification of rice images.","archived":false,"fork":false,"pushed_at":"2024-09-14T08:29:48.000Z","size":444,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-21T23:58:54.849Z","etag":null,"topics":["cnn","convolutional-neural-networks","data-augmentation","deep-learning","image-classification","image-processing","machine-learning","python","tensorflow"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/canoksuzoglu1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-13T20:17:16.000Z","updated_at":"2024-09-14T08:29:51.000Z","dependencies_parsed_at":"2024-09-14T08:54:31.193Z","dependency_job_id":"c437bea5-3634-4e18-b65b-e7164ba2fd7e","html_url":"https://github.com/canoksuzoglu1/Rice-Classification-CNN","commit_stats":null,"previous_names":["canoksuzoglu1/rice-classification-cnn"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/canoksuzoglu1%2FRice-Classification-CNN","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/canoksuzoglu1%2FRice-Classification-CNN/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/canoksuzoglu1%2FRice-Classification-CNN/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/canoksuzoglu1%2FRice-Classification-CNN/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/canoksuzoglu1","download_url":"https://codeload.github.com/canoksuzoglu1/Rice-Classification-CNN/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225820212,"owners_count":17529139,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cnn","convolutional-neural-networks","data-augmentation","deep-learning","image-classification","image-processing","machine-learning","python","tensorflow"],"created_at":"2024-09-25T01:04:22.042Z","updated_at":"2026-02-13T22:42:24.964Z","avatar_url":"https://github.com/canoksuzoglu1.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rice-Classification-CNN\n\nThis project demonstrates how to build, train, and evaluate a Convolutional Neural Network (CNN) model using **TensorFlow** to classify images of different rice varieties. The project uses a publicly available dataset containing images of rice grains and covers key steps such as dataset loading, preprocessing, data augmentation, model building, training, and model evaluation.\n\n## Table of Contents\n- [Project Overview](#project-overview)\n- [Dataset Information](#dataset-information)\n- [Prerequisites](#prerequisites)\n- [Dataset Structure](#dataset-structure)\n- [Installation](#installation)\n- [Usage](#usage)\n   - [1. Libraries and Constants](#1-libraries-and-constants)\n   - [2. Data Loading and Sampling](#2-data-loading-and-sampling)\n   - [3. Image Preview](#3-image-preview)\n   - [4. Dataset Splitting](#4-dataset-splitting)\n   - [5. Data Preprocessing](#5-data-preprocessing)\n   - [6. Model Definition](#6-model-definition)\n   - [7. Model Compilation and Training](#7-model-compilation-and-training)\n   - [8. Model Evaluation and Prediction](#8-model-evaluation-and-prediction)\n   - [9. Model Saving and Loading](#9-model-saving-and-loading)\n   - [Key Points](#key-points)\n- [Results](#results)\n\n## Project Overview\n\nThis repository contains a TensorFlow-based image classification project where we train a CNN model to classify different varieties of rice grains. The goal is to accurately classify images into one of five rice varieties (Arborio, Basmati, Ipsala, Jasmine, and Karacadag). The project includes functionalities for data augmentation, dataset splitting, and model checkpointing to save the best performing model.\n\n## Dataset Information\n\n**Rice Image Dataset**  \nLink: [Kaggle - Rice Image Dataset](https://www.kaggle.com/datasets/muratkokludataset/rice-image-dataset)  \nOriginal Dataset Link: [Murat Koklu Dataset](https://www.muratkoklu.com/datasets/)\n\n### Citation Request\nIf you use this dataset, please cite the following articles:\n\n- Koklu, M., Cinar, I., \u0026 Taspinar, Y. S. (2021). Classification of rice varieties with deep learning methods. *Computers and Electronics in Agriculture, 187*, 106285. [DOI:10.1016/j.compag.2021.106285](https://doi.org/10.1016/j.compag.2021.106285)\n  \n- Cinar, I., \u0026 Koklu, M. (2021). Determination of Effective and Specific Physical Features of Rice Varieties by Computer Vision In Exterior Quality Inspection. *Selcuk Journal of Agriculture and Food Sciences, 35(3)*, 229-243. [DOI:10.15316/SJAFS.2021.252](https://doi.org/10.15316/SJAFS.2021.252)\n  \n- Cinar, I., \u0026 Koklu, M. (2022). Identification of Rice Varieties Using Machine Learning Algorithms. *Journal of Agricultural Sciences*. [DOI:10.15832/ankutbd.862482](https://doi.org/10.15832/ankutbd.862482)\n  \n- Cinar, I., \u0026 Koklu, M. (2019). Classification of Rice Varieties Using Artificial Intelligence Methods. *International Journal of Intelligent Systems and Applications in Engineering, 7(3)*, 188-194. [DOI:10.18201/ijisae.2019355381](https://doi.org/10.18201/ijisae.2019355381)\n\n### Highlights\n\n- The dataset contains images from five rice varieties: Arborio, Basmati, Ipsala, Jasmine, and Karacadag.\n- The dataset includes 75,000 images, with 15,000 images for each rice variety.\n- Artificial Neural Network (ANN), Deep Neural Network (DNN), and Convolutional Neural Network (CNN) models were used for classification.\n- The CNN model achieved a 100% classification accuracy for rice varieties.\n\n## Prerequisites\n\nBefore running the code, you will need to install the following dependencies:\n\n- Python 3.8+\n- TensorFlow 2.x\n- NumPy\n- Matplotlib\n\nYou can install all required libraries using `pip`:\n\n```bash\npip install tensorflow numpy matplotlib\n```\n\n## Dataset Structure\nThe project assumes that you have an image dataset organized in the following directory structure:\n\n- **Data/**  \n  - **Arborio/**  \n    - `image_1.jpg`  \n    - `image_2.jpg`  \n    - `...`  \n  - **Basmati/**  \n    - `image_1.jpg`  \n    - `image_2.jpg`  \n    - `...`  \n  - **Ipsala/**  \n    - `image_1.jpg`  \n    - `image_2.jpg`  \n    - `...`  \n  - **Jasmine/**  \n    - `image_1.jpg`  \n    - `image_2.jpg`  \n    - `...`  \n  - **Karacadag/**  \n    - `image_1.jpg`  \n    - `image_2.jpg`  \n    - `...`  \n\n\nEach subdirectory under `/Data` corresponds to one of the five rice varieties, and the images within the subdirectories belong to that variety.\n\n## Installation\n1. Clone the repository:\n```bash\ngit clone https://github.com/canoksuzoglu1/Rice-Classification-CNN.git\n```\n2. Install the required dependencies:\n```bash\npip install -r requirements.txt\n```\n3. Place your dataset in the Data/ directory as shown above.\n\n## Usage\n\n### 1. Libraries and Constants\n- Import necessary libraries like TensorFlow, Keras, and Matplotlib.\n- Set constants like `IMAGE_SIZE`, `BATCH_SIZE`, `CHANNELS`, and `EPOCHS` to configure the model's input size and training parameters.\n\n```python\nIMAGE_SIZE = 250\nBATCH_SIZE = 32\nCHANNELS = 3\nEPOCHS = 50\n```\n### 2. Data Loading and Sampling\n- Load the dataset using image_dataset_from_directory with specified image_size and batch_size.\n- Randomly sample the dataset using a custom sampling function to reduce its size for quicker iteration during development.\n\n```python\ndataset = tf.keras.preprocessing.image_dataset_from_directory(\n    \"Data\",\n    shuffle=True,\n    image_size=(IMAGE_SIZE, IMAGE_SIZE),\n    batch_size=BATCH_SIZE\n)\n\ndataset = sample_dataset(dataset, fraction=1/15)\n```\n\n### 3. Image Preview\nVisualize a few images from the dataset to ensure loading and pre-processing are correct.\n```python\nplt.figure(figsize=(10, 10))\nfor image_batch, image_label in dataset.take(1):\n    plt.imshow(image_batch[0].numpy().astype(\"uint8\"))\n```\n### 4. Dataset Splitting\nUse a custom function to split the dataset into training, validation, and test sets as TensorFlow does not have a built-in function for this.\n```python\ntrain_ds, val_ds, test_ds = get_dataset_partitions_tf(dataset)\n```\n### 5. Data Preprocessing\nCache, shuffle, and prefetch the data for better training efficiency.\nApply image resizing and scaling transformations using `layers.Rescaling` and `layers.Resizing`.\n```python\nresize_and_rescale = tf.keras.Sequential([\n    layers.Resizing(IMAGE_SIZE, IMAGE_SIZE),\n    layers.Rescaling(1.0/256)\n])\n```\n### 6. Model Definition\n- A CNN model is built with two Conv2D layers followed by pooling, and a Dense layer for classification.\n- Apply data augmentation to improve the model's robustness.\n```python\nmodel = models.Sequential([\n    resize_and_rescale,\n    data_augmentation,\n    layers.Conv2D(16, (3, 3), activation='relu'),\n    layers.MaxPool2D((2, 2)),\n    layers.Conv2D(32, (3, 3), activation='relu'),\n    layers.MaxPool2D((2, 2)),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dense(5, activation='softmax')\n])\n```\n### 7. Model Compilation and Training\n- Compile the model using Adam optimizer with a reduced learning rate (`learning_rate=1e-5`) for better convergence.\n- Use `ModelCheckpoint` to save the best version of the model based on validation loss.\n```python\nmodel.compile(\n    optimizer=Adam(learning_rate=1e-5),\n    loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n    metrics=['accuracy']\n)\nhistory = model.fit(\n    train_ds,\n    epochs=EPOCHS,\n    validation_data=val_ds,\n    callbacks=[checkpoint_callback]\n)\n```\n### 8. Model Evaluation and Prediction\n- After training, evaluate the model using the test dataset.\n- Use a prediction function to classify new images and visualize the results with confidence scores.\n```python\nscore = model.evaluate(test_ds)\n```\n### 9. Model Saving and Loading\n- Save and load the trained model for future inference.\n```python\nmodel.save(f\"./models/{model_version}.keras\")\nmodel = tf.keras.models.load_model(model_path)\n```\n### Key Points:\n- Data Preprocessing: Ensure images are correctly resized and rescaled.\n- Model Architecture: Keep the architecture simple with a small number of layers, especially for quicker prototyping.\n- Checkpointing: Always save the best model during training to avoid overfitting.\n\n## Results\nThe model can be evaluated by visualizing predictions on test images. The script includes code to display predicted labels and confidence scores along with the actual labels of test images.\n\nExample:\nPredicted: Arborio (95.12%)\nActual: Arborio\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcanoksuzoglu1%2Frice-classification-cnn","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcanoksuzoglu1%2Frice-classification-cnn","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcanoksuzoglu1%2Frice-classification-cnn/lists"}