DEV Community

SyedKashifNaqvi
SyedKashifNaqvi

Posted on

Machine learning with Django and React.js

This is for begineers guide

First, let's create a Django project and app and install the necessary dependencies. Open your terminal and run the following commands:

# Create a new virtual environment (optional)
python -m venv env
source env/bin/activate

# Install Django and other dependencies
pip install django djangorestframework pandas scikit-learn joblib
Enter fullscreen mode Exit fullscreen mode

Next, let's create a new Django project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp


Enter fullscreen mode Exit fullscreen mode

Now, let's create a machine learning model that we want to expose through the API. For this example, we'll create a simple logistic regression model that predicts whether a person is male or female based on their height and weight. Create a new file called model.py in the myapp directory with the following code:

import pandas as pd
from sklearn.linear_model import LogisticRegression
import joblib

# Load the training data
data = pd.read_csv('https://people.sc.fsu.edu/~jburkardt/data/csv/hw_200.csv')

# Train a logistic regression model
X = data[['Height', 'Weight']]
y = data['Gender']
model = LogisticRegression()
model.fit(X, y)

# Save the model to disk
joblib.dump(model, 'model.pkl')
Enter fullscreen mode Exit fullscreen mode

This code loads a dataset of height and weight measurements and gender labels, trains a logistic regression model using scikit-learn, and saves the trained model to disk using the joblib library.

Now, let's create a Django view that uses the trained model to make predictions. Create a new file called views.py in the myapp directory with the following code:


from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import joblib
import numpy as np

# Load the saved model from disk
model = joblib.load('model.pkl')

# Define a view that takes input data and returns a prediction
@csrf_exempt
def predict(request):
    if request.method == 'POST':
        # Get the input data from the request
        data = request.POST.dict()

        # Convert the input data to a numpy array
        X = np.array([[float(data['height']), float(data['weight'])]])

        # Use the model to make a prediction
        y_pred = model.predict(X)

        # Return the prediction as a JSON response
        return JsonResponse({'prediction': str(y_pred[0])})
    else:
        return JsonResponse({'error': 'Invalid request method'})


Enter fullscreen mode Exit fullscreen mode

This code defines a view called predict that takes input data (height and weight) from a POST request, converts the input data to a numpy array, uses the trained model to make a prediction, and returns the prediction as a JSON response.

Now, let's create a URL pattern that maps the predict view to a URL. Create a new file called urls.py in the myapp directory with the following code:

from django.urls import path
from .views import predict

urlpatterns = [
    path('predict/', predict, name='predict'),
]

Enter fullscreen mode Exit fullscreen mode

This code defines a URL pattern that maps the /predict/ URL to the predict view.

Finally, let's start the Django development server to test our API. Run the following command:

python manage.py runserver


Enter fullscreen mode Exit fullscreen mode

Django development server, which will listen for requests on http://127.0.0.1:8000/.

Now that we have a functioning backend API, let's move on to the React frontend.

React Frontend

First, let's create a new React app using create-react-app. Open your terminal and run the following command:

npx create-react-app myapp
cd myapp


Enter fullscreen mode Exit fullscreen mode

Now, let's install the necessary dependencies:

npm install axios
Enter fullscreen mode Exit fullscreen mode

This installs the axios library, which we'll use to make requests to the Django backend API.

Next, let's create a form component that allows the user to input their height and weight and make a prediction using the backend API. Create a new file called PredictionForm.js in the src directory with the following code:

import React, { useState } from 'react';
import axios from 'axios';

function PredictionForm() {
  const [height, setHeight] = useState('');
  const [weight, setWeight] = useState('');
  const [prediction, setPrediction] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await axios.post('/api/predict/', {
        height: height,
        weight: weight,
      });

      setPrediction(response.data.prediction);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Height (cm):
        <input
          type="number"
          value={height}
          onChange={(event) => setHeight(event.target.value)}
        />
      </label>
      <br />
      <label>
        Weight (kg):
        <input
          type="number"
          value={weight}
          onChange={(event) => setWeight(event.target.value)}
        />
      </label>
      <br />
      <button type="submit">Predict</button>
      {prediction && <p>Prediction: {prediction}</p>}
    </form>
  );
}

export default PredictionForm;




Enter fullscreen mode Exit fullscreen mode

This code defines a form component that allows the user to input their height and weight and make a prediction using the backend API. The handleSubmit function makes a POST request to the /api/predict/ URL using the axios library, passing the height and weight data as JSON. If the request is successful, the prediction state is updated with the predicted gender.

Now, let's create a main component that renders the PredictionForm component. In App.js in the src directory with the following code:

import React from 'react';
import PredictionForm from './PredictionForm';

function App() {
  return (
    <div>
      <h1>Gender Predictor</h1>
      <PredictionForm />
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

This code defines a main component that renders the PredictionForm component and a header.

Finally, let's start the React development server to test our app. Run the following command:

`npm start`

Enter fullscreen mode Exit fullscreen mode

This should start the React development server, which will listen for requests on http://localhost:3000/.

If you navigate to http://localhost:3000/ in your web browser, you should see a form that allows you to input your height and weight and make a prediction using the backend API.

That's it! You now have a basic Django backend that exposes a machine learning model through a RESTful API, and a React frontend that communicates with the backend to make predictions using the model.

Top comments (0)