import numpy as np import matplotlib.pyplot as plt import time ############################################################################### # 01-regression_lineaire.py # @title: Apprentissage par régression linéaire # @project: Mes scripts de ML # @lang: fr # @authors: Philippe Roy # @copyright: Copyright (C) 2023 Philippe Roy # @license: GNU GPL ############################################################################### ### # Commandes NumPy : # - np.array : créer un tableau à partir d'une liste de listes # - np.c_ : concatène les colonnes des tableaux # - np.ones : créer un tableau de 1 # - np.linalg.inv : inversion de matrice # - .T : transposé de matrice # - .dot : produit de matrice ### # Init du temps t_debut = time.time() # Observations d'apprentisage m = 1000 # Nombre d'observations bg = 1 # Bruit gaussien x = 2*np.random.rand(m, 1) # Liste des observations x1 y = 4 + 3*x + bg * np.random.rand(m, 1) # Liste des cibles y X = np.c_[np.ones((m, 1)), x] # Matrice des observations, avec x0=1 plt.plot(x, y, 'b.') # Phase d'apprentissage par régression linéaire avec l'équation normale # - theta : vecteur paramètres du modèle # - theta_best : vecteur paramètres pour le coût mini theta_best= np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) theta = theta_best # Nouvelles observations x_new=np.array([[0], [2]]) X_new = np.c_[np.ones((2, 1)), x_new] # Matrice des observations, avec x0=1 # Phase d'inférence y_predict=X_new.dot(theta_best) # Liste des prédictions y_predict plt.plot(x_new, y_predict, 'r-') plt.show() # Performance print ("Theta th : theta0 : "+str(4)+" ; theta1 : "+str(3)) print ("Theta : theta0 : "+str(round(float(theta[0]),3))+" ; theta1 : "+str(round(float(theta[1]),3))) print ("Erreurs : theta0 : "+str(round(float(theta[0]-4),3))+" ; theta1 : "+str(round(float(theta[1]-3),3))) print ("Temps : "+str(time.time()-t_debut))