First let's install needed packages
!pip install roboflow -q
!pip install ultralytics -q
Grab the dataset link from roboflow
from roboflow import Roboflow
rf = Roboflow(api_key="your roboflow api key here")
project = rf.workspace("workspace").project("project name")
version = project.version(4)
dataset = version.download("yolov9")
in order to change the yaml file configuration to match your data train test valid folders you will execute the following code
import yaml
def update_yaml_content(file_path, new_content):
try:
# Write the new content to the YAML file
with open(file_path, 'w') as file:
yaml.dump(new_content, file)
print("File updated successfully.")
except Exception as e:
print(f"An error occurred: {e}")
# Define the yaml file path
file_path = '/kaggle/working/dataset/data.yaml'
# Define the new content
new_content = {
'names': [
'Early Blight',
'Healthy',
'Late Blight',
'Leaf Miner',
'Leaf Mold',
'Mosaic Virus',
'Septoria',
'Spider Mites',
'Yellow Leaf Curl Virus'
],
'nc': 9,
'roboflow': {
'license': 'CC BY 4.0',
'project': 'proj name',
'url': 'url',
'version': 4,
'workspace': 'workspace'
},
'test': '/kaggle/working/dataset/test',
'train': '/kaggle/working/dataset/train',
'val': '/kaggle/working/dataset/valid'
}
# Call the function to update the YAML file
update_yaml_content(file_path, new_content)
File updated successfully.
check if yaml file is updated correctly or not
import yaml
def view_yaml_file(file_path):
with open(file_path, 'r') as file:
yaml_content = yaml.safe_load(file)
return yaml_content
file_path = "/kaggle/working/dataset/data.yaml"
yaml_content = view_yaml_file(file_path)
print(yaml_content)
from ultralytics import YOLO
# Build a YOLOv9c model from scratch
model = YOLO('yolov9e.yaml')
# Build a YOLOv9c model from pretrained weight
model = YOLO('yolov9e.pt')
# Display model information (optional)
model.info()
# Train the model
results = model.train(data='/kaggle/working/dataset/data.yaml', epochs=300,
batch=32,patience=10,cache=True,save_period=30,imgsz=300)