top of page

How to Train Your First ML Model in Python?

  • Writer: Ramesh Choudhary
    Ramesh Choudhary
  • Feb 12
  • 2 min read
How to Train Your First ML Model in Python?

Machine learning (ML) is revolutionizing industries by enabling computers to learn from data and make predictions. If you’re new to ML and want to train your first model using Python, this guide will walk you through the process step by step. We’ll use Scikit-learn, one of the most beginner-friendly ML libraries in Python.


Step 1: Install Required Libraries


Before we begin, install the necessary libraries using pip:

pip install numpy pandas scikit-learn matplotlib seaborn

These libraries help with data handling, model training, and visualization.


Step 2: Load and Explore the Data


To train an ML model, we need data. Let’s use the classic Iris dataset, which contains features of different iris flowers.


from sklearn.datasets import load_iris
import pandas as pd

# Load dataset
iris = load_iris()

# Create a DataFrame
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target  # Add target labels

# Display first few rows
print(df.head())

Tip: Always explore your dataset before training a model. Check for missing values, data distributions, and anomalies.


Step 3: Split the Data into Training and Testing Sets


To evaluate model performance, we split our data into training (80%) and testing (20%) sets.


from sklearn.model_selection import train_test_split

X = df.drop(columns=['target'])  # Features
y = df['target']  # Target labels

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Step 4: Choose an ML Model and Train It


For this example, we’ll use a Support Vector Machine (SVM) classifier, a popular ML algorithm for classification tasks.


from sklearn.svm import SVC

# Initialize model
model = SVC(kernel='linear')

# Train model
model.fit(X_train, y_train)

Step 5: Make Predictions


Once the model is trained, we can use it to make predictions on new data.

y_pred = model.predict(X_test)

Step 6: Evaluate Model Performance


To measure accuracy, we compare predicted labels with actual labels.


from sklearn.metrics import accuracy_score, classification_report

accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy * 100:.2f}%')

print('Classification Report:')
print(classification_report(y_test, y_pred))

Tip: If accuracy is low, consider trying different models (e.g., Decision Trees, Random Forests) or tuning hyperparameters.


Step 7: Save and Load the Model for Future Use


Once you have a working model, save it for reuse.


import joblib

joblib.dump(model, 'iris_model.pkl')

# Load model
loaded_model = joblib.load('iris_model.pkl')

Conclusion


Congratulations! You’ve trained your first ML model in Python.


Here’s a quick recap:


✅ Loaded and explored the dataset

✅ Split data into training and testing sets

✅ Chose and trained an ML model

✅ Made predictions and evaluated performance

✅ Saved the model for future use


This is just the beginning. Experiment with different algorithms, feature engineering techniques, and hyperparameters to improve your model. Happy ML coding! 🚀

Comments


Subscribe to our newsletter • Don’t miss out!

bottom of page