Reactjs & Machine learning — Your First Project

Hamid Ayub
5 min readMay 15, 2024

--

Beginner Level: An Introduction to Machine Learning Concepts and Applications in Web Development on react

Introduction

Machine Learning (ML) has become an integral part of many modern applications, from recommendation systems to image recognition. As a web developer, understanding the basics of ML can open up new opportunities for creating smarter, more responsive applications. This article will introduce you to the fundamental concepts of machine learning, demonstrate how they can be applied in web development, and guide you through a simple project using a popular machine learning library.

Understanding Machine Learning

Machine Learning is a subset of artificial intelligence (AI) that focuses on building systems that can learn from data and make decisions or predictions. Instead of explicitly programming instructions, ML models are trained on data to recognize patterns and make predictions.

Key Concepts in Machine Learning

  1. Supervised Learning: Involves training a model on a labeled dataset, where the input data is paired with the correct output. Common algorithms include linear regression, logistic regression, and support vector machines.
  2. Unsupervised Learning: Deals with unlabeled data and aims to find hidden patterns or intrinsic structures. Common algorithms include k-means clustering and principal component analysis (PCA).
  3. Reinforcement Learning: Involves training a model to make sequences of decisions by rewarding desired behaviors and punishing undesired ones.
  4. Training and Testing: The process of training a model involves feeding it data and adjusting its parameters to minimize errors. The model is then tested on a separate dataset to evaluate its performance.
  5. Overfitting and Underfitting: Overfitting occurs when a model learns the training data too well, including noise and outliers, leading to poor generalization. Underfitting happens when the model is too simple to capture the underlying patterns in the data.

Applying Machine Learning in Web Development

Machine Learning can enhance web applications in various ways, including:

  • Personalization: Recommending products or content based on user preferences and behavior.
  • Search Optimization: Improving search results by understanding user intent and context.
  • Fraud Detection: Identifying fraudulent activities through anomaly detection.
  • Natural Language Processing (NLP): Enabling chatbots and sentiment analysis.

A Simple Project: Building a Recommendation System

This simple project demonstrates how to build a basic movie recommendation system using machine learning concepts. Here’s what it does in detail:

1. Data Preparation:

  • Loading Data: It loads a dataset of movie ratings from a file.
  • Merging Data: It merges movie ratings with movie details to create a comprehensive dataset.

2. Creating a User-Movie Matrix:

  • It creates a matrix where rows represent users and columns represent movies. Each cell in the matrix contains the rating a user has given to a movie. Missing values (i.e., movies not rated by a user) are filled with zeros.

3. Splitting Data:

  • It splits the data into training and testing sets to evaluate the model’s performance.

4. Building the Recommendation Model:

  • It uses a collaborative filtering approach to find similar users based on their movie ratings.
  • The cosine similarity metric is used to calculate the similarity between users.
  • It recommends movies to a user by finding other users with similar tastes and suggesting movies they have rated highly.

Note: we use collaborative filtering, a common technique in recommender systems, which falls under the category of unsupervised learning in machine learning.

Step 1: Set Up the Backend with Node.js and Integrate Machine Learning Logic

1. Download the Dataset:
— Download the MovieLens 100k dataset from here.
— Extract the files and place them in a directory named `data` inside your project folder.

2. Initialize a New Node.js Project:

mkdir movie-recommendation-backend
cd movie-recommendation-backend
npm init -y

3. Install Required Libraries:


npm install express cors csv-parser mathjs

4. Create the Backend Server with Machine Learning Logic:

Create a file named `server.js` and add the following code:


const express = require(‘express’);
const cors = require(‘cors’);
const fs = require(‘fs’);
const csv = require(‘csv-parser’);
const { mean, pow, sqrt } = require(‘mathjs’);
const app = express();
const port = 5000;

app.use(cors());
let movies = [];
let ratings = [];
// Load movies and ratings from CSV files
fs.createReadStream('data/u.item')
.pipe(csv({ separator: '|', headers: false }))
.on('data', (row) => {
movies.push({ movieId: row[0], title: row[1] });
})
.on('end', () => {
console.log('Movies data loaded');
});
fs.createReadStream('data/u.data')
.pipe(csv({ separator: '\t', headers: false }))
.on('data', (row) => {
ratings.push({ userId: row[0], movieId: row[1], rating: row[2] });
})
.on('end', () => {
console.log('Ratings data loaded');
});
// Calculate similarity between two users
const calculateSimilarity = (userRatings1, userRatings2) => {
const commonMovies = userRatings1.filter(r1 => userRatings2.some(r2 => r2.movieId === r1.movieId));
if (commonMovies.length === 0) return 0;
const ratings1 = commonMovies.map(r => parseInt(r.rating));
const ratings2 = commonMovies.map(r => parseInt(userRatings2.find(r2 => r2.movieId === r.movieId).rating));
const mean1 = mean(ratings1);
const mean2 = mean(ratings2);
const numerator = ratings1.reduce((sum, rating, index) => sum + (rating - mean1) * (ratings2[index] - mean2), 0);
const denominator = sqrt(ratings1.reduce((sum, rating) => sum + pow(rating - mean1, 2), 0)) * sqrt(ratings2.reduce((sum, rating) => sum + pow(rating - mean2, 2), 0));
return denominator === 0 ? 0 : numerator / denominator;
};
// Recommendation logic using collaborative filtering
const recommendMovies = (userId) => {
const userRatings = ratings.filter(r => r.userId === userId);
if (userRatings.length === 0) return [];
const otherUsers = ratings.filter(r => r.userId !== userId);
const userRatingsByUser = otherUsers.reduce((acc, rating) => {
acc[rating.userId] = acc[rating.userId] || [];
acc[rating.userId].push(rating);
return acc;
}, {});
const similarities = Object.entries(userRatingsByUser).map(([otherUserId, otherUserRatings]) => {
return { userId: otherUserId, similarity: calculateSimilarity(userRatings, otherUserRatings) };
});
similarities.sort((a, b) => b.similarity - a.similarity);
const topSimilarUsers = similarities.slice(0, 5);
const movieScores = {};
topSimilarUsers.forEach(({ userId, similarity }) => {
userRatingsByUser[userId].forEach(rating => {
if (!userRatings.some(r => r.movieId === rating.movieId)) {
movieScores[rating.movieId] = movieScores[rating.movieId] || 0;
movieScores[rating.movieId] += similarity * parseInt(rating.rating);
}
});
});
const recommendedMovieIds = Object.entries(movieScores).sort((a, b) => b[1] - a[1]).map(([movieId]) => movieId);
return movies.filter(movie => recommendedMovieIds.includes(movie.movieId)).map(movie => movie.title);
};
app.get('/recommend', (req, res) => {
const userId = req.query.user_id;
const recommendations = recommendMovies(userId);
res.json(recommendations);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

5. Run the Node.js Server:


node server.js

Step 2: Set Up the React Frontend

1. Create a New React App:


npx create-react-app movie-recommendation-frontend
cd movie-recommendation-frontend

2. Install Axios for HTTP Requests:


npm install axios

3. Create the React Component:

Open `src/App.js` and replace the content with the following code:


import React, { useState } from ‘react’;
import axios from ‘axios’;
function App() {
const [userId, setUserId] = useState('');
const [recommendations, setRecommendations] = useState([]);
const getRecommendations = async () => {
try {
const response = await axios.get(`http://localhost:5000/recommend?user_id=${userId}`);
setRecommendations(response.data);
} catch (error) {
console.error("There was an error fetching the recommendations!", error);
}
};
return (
<div className="App">
<h1>Movie Recommendation System</h1>
<input
type="number"
placeholder="Enter User ID"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>
<button onClick={getRecommendations}>Get Recommendations</button>
<ul>
{recommendations.map((movie, index) => (
<li key={index}>{movie}</li>
))}
</ul>
</div>
);
}
export default App;

4. Run the React App:


npm start

What You had achieved?

This project incorporates a basic collaborative filtering algorithm in the Node.js backend to provide more accurate movie recommendations. The backend processes the MovieLens dataset, calculates similarities between users based on their ratings, and recommends movies that similar users have rated highly. The frontend (React.js) allows users to input their user ID and see the recommended movies. This setup demonstrates a more realistic and practical application of machine learning in a web development project.

--

--

Hamid Ayub
Hamid Ayub

No responses yet