Voici un exemple simplifié d'une application de recommandation de films utilisant le Q-learning.
Le
projet se compose de deux parties : le backend en Python avec Flask et l'algorithme Q-learning, et le
frontend en HTML/CSS.
Backend (Flask + Q-learning)Installation des dépendances :pip install flask numpy pandasCode source
du backend :# [Link]
from flask import Flask, request, jsonify
import numpy as np
import pandas as pd
import random
app = Flask(__name__)
# Données fictives des films
movies = [
{'id': 1, 'title': 'Movie A', 'genre': 'Action'},
{'id': 2, 'title': 'Movie B', 'genre': 'Comedy'},
{'id': 3, 'title': 'Movie C', 'genre': 'Drama'},
# Ajoutez plus de films ici
# Initialisation de la table Q
q_table = [Link](
[Link]((len(movies), len(movies))),
columns=[movie['id'] for movie in movies],
index=[movie['id'] for movie in movies]
# Paramètres de l'algorithme Q-learning
alpha = 0.1 # Taux d'apprentissage
gamma = 0.9 # Facteur de discount
epsilon = 0.1 # Taux d'exploration
def choose_action(state):
if [Link]() < epsilon:
return [Link](movies)['id'] # Exploration
else:
return q_table.loc[state].idxmax() # Exploitation
def update_q_table(state, action, reward, next_state):
best_next_action = q_table.loc[next_state].idxmax()
q_table.loc[state, action] = q_table.loc[state, action] + alpha * (
reward + gamma * q_table.loc[next_state, best_next_action] - q_table.loc[state, action]
@[Link]('/recommend', methods=['POST'])
def recommend():
data = [Link]
user_id = data['user_id']
current_movie_id = data['current_movie_id']
reward = data['reward']
action = choose_action(current_movie_id)
update_q_table(current_movie_id, action, reward, action) # Mise à jour de la table Q
recommended_movie = next(movie for movie in movies if movie['id'] == action)
return jsonify(recommended_movie)
if __name__ == '__main__':
[Link](debug=True)
Frontend (HTML/CSS)Code source du frontend :<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Movie Recommender</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
.movie {
margin-bottom: 20px;
</style>
</head>
<body>
<h1>Movie Recommender</h1>
<div id="movie-container"></div>
<button onclick="getRecommendation()">Get Recommendation</button>
<script>
const userId = 1; // Utilisateur fictif
function getRecommendation() {
fetch('/recommend', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link]({
user_id: userId,
current_movie_id: currentMovieId,
reward: [Link]([Link]() * 3) // Récompense aléatoire pour simplification
})
})
.then(response => [Link]())
.then(data => {
currentMovieId = [Link];
[Link]('movie-container').innerHTML = `
<div class="movie">
<h2>${[Link]}</h2>
<p>Genre: ${[Link]}</p>
</div>
`;
});
let currentMovieId = 1; // Film initial
getRecommendation();
</script>
</body>
</html>
Exécution du projetLancer le backend :python [Link]
Ouvrir le fichier HTML dans un navigateur : Ouvrez le fichier [Link] dans votre navigateur
préféré.