Implementierung des Gradientenabstiegs für die logistische Regression in Python | von Nazlican Caglar | Juli 2023

0
24


In diesem Artikel werden die grundlegenden Optimierungstechniken für Klassifizierungsprobleme mit logistischer Regression vorgestellt. Der Code führt einen Gradientenabstieg durch, um die Parameter (w) zu optimieren und den Fehler zu minimieren. Verwendete unterschiedliche Lernraten und zeigte deren Auswirkungen auf das Ergebnis. Es ist ein perfektes Beispiel für Anfänger.

Zuerst bitte herunterladen die CSV-Datei. Wenn Sie die Datendatei überprüfen, werden die erste, zweite und dritte Spalte als Eingabedatensatz bezeichnet (und enthalten die Eingabemerkmale). Die vierte Spalte wird als Ausgabedatensatz bezeichnet und enthält die Klassennummer für jedes Eingabebeispiel. Anschließend für 500 Iterationen werden die vorhergesagten Ausgaben mithilfe der folgenden Formel für jede Iteration berechnet.

Jetzt fangen wir an.

#Import Required Libraries
import pandas as pd
import numpy as np
import scipy.particular as sps
import matplotlib.pyplot as plt

#Seeing the dataset solely 10 gadgets
knowledge = pd.read_csv('/content material/knowledge.csv')

#Changing dataframe to a numpy array
knowledge = np.array(knowledge)

#Studying enter and output array from knowledge
X = knowledge[:,:3] # ":3" outline first 3 column should taken (0,1,2), don't take column 3
Y = knowledge [:,3] # "3" outline that the 3th column will execute.

#Initializing parameters
w = np.random.rand(3,)

#most variety of iterations
max_iter = 500

#outline an error vector to save lots of all error values over all iterations.
error_all = []

#studying fee for gradient descent
eta = 0.5

# Outline the sigmoid operate with the given components
def sigmoid(z):
return 1/(1+np.exp(-z))

# Increase the load parameter 'w' to the facility of 'max_iter' and multiply by the enter matrix 'X'
z = w**max_iter * X

# Loop over the required most variety of iterations
for iter in vary(max_iter):
# Compute the expected chances of the optimistic class utilizing the sigmoid (expit) operate
Y_hat = sps.expit(np.dot(X, w))

# Compute the logistic loss/value/error utilizing binary cross-entropy components
e = (-1 / len(Y)) * np.sum(Y * np.log(Y_hat) + (1 - Y) * np.log(1 - Y_hat))
error_all.append(e)

# # Gradient of the error
grad_e = np.imply(np.multiply((Y_hat - Y), X.T), axis=1)

# Carry out one step of gradient descent utilizing the educational fee eta to replace the load parameter w
# Retailer the present weight as w_old and the up to date weight as w for the following iteration
w_old = w
w = w - eta * grad_e

# Print the present iteration quantity, logistic loss/value, and up to date weight
print('epoch {0:d}, damaging log-likelihood {1:.4f}, w={2}'.format(iter, e, w.T))

Nach dem Drucken der obigen Struktur finden Sie 500 Iterationen.

Wie diese Iterationen aussehen, werden wir anhand der Handlung herausfinden.

# Plot the evolution of the error over all iterations
plt.xlabel('Iteration')
plt.ylabel('Error')
plt.title('Error Values 0.5')
plt.plot(error_all)
plt.present()

Die Iterationen finden Sie unten.

Die oszillierende Handlung ändert sich basierend auf dem „eta“-Wert, der unsere Lernrate bedeutet. Wenn unsere Lernrate zu groß ist, kann das Gewicht erheblich schwanken und das Ergebnis wird schwankender aussehen.

Wenn wir die Lernrate ändern möchten, sieht es wie folgt aus:

# Set the educational fee to 0.3
eta = 0.3

# Outline the sigmoid operate with the given components
def sigmoid(z):
return 1/(1+np.exp(-z))

# Multiply the load parameter 'w' to the facility of 'max_iter' and multiply by the enter matrix 'X'
# Cross the end result by means of the sigmoid operate to compute the expected output chances
z = w**max_iter * X
Y_hat = sigmoid(z)

# Loop over the required most variety of iterations to coach the mannequin
for iter in vary(max_iter):
# Compute the expected chances of the optimistic class utilizing the sigmoid (expit) operate
Y_hat = sps.expit(np.dot(X, w))

# Compute the logistic loss/value/error utilizing binary cross-entropy components
e = (-1 / len(Y)) * np.sum(Y * np.log(Y_hat) + (1 - Y) * np.log(1 - Y_hat))
error_all.append(e)

# Compute the gradient of the error utilizing the spinoff of the logistic loss/value operate
# Gradient computation makes use of elementwise multiplication and averaging, and is carried out utilizing the transpose of X
grad_e = np.imply(np.multiply((Y_hat - Y), X.T), axis=1)

# Carry out one step of gradient descent utilizing the educational fee eta to replace the load parameter w
# Retailer the present weight as w_old and the up to date weight as w for the following iteration
w_old = w
w = w - eta * grad_e

# Print the present iteration quantity, logistic loss/value, and up to date weight
print('epoch {0:d}, damaging log-likelihood {1:.4f}, w={2}'.format(iter, e, w.T))

# Plot the evolution of the error over all iterations
plt.xlabel('Iteration')
plt.ylabel('Error')
plt.title('Error Values for studying fee set to 0.3')
plt.plot(error_all)
plt.present()

Wir werden einige Experimente durchführen. Bitte wenden Sie diese Lernraten unabhängig an (η = 0,1, 0,05, 0,01). (Sie können den obigen Codeblock verwenden. Ändern Sie nur den „eta“-Wert.)

Nachdem wir drei verschiedene Lernraten verwendet haben, vergleichen wir fünf Lernraten und sehen, wie sie aussehen.
Alle berechneten Lernraten sind η = 0,5, 0,3, 0,1, 0,05, 0,01

# Initialize the load vector 'w' with 3 random values between 0 and 1
w = np.random.rand(3)

# Set the utmost variety of iterations for coaching the mannequin
max_iter = 500

# Initialize an empty checklist to retailer the error values for every studying fee examined
error_all = []

# Outline an inventory of studying charges to be examined
eta_values = [0.5, 0.3, 0.1, 0.05, 0.01]

# For every studying fee, practice the mannequin for the required variety of iterations and retailer the error values
for eta in eta_values:
# Initialize the load vector 'w' with a brand new set of random values for every studying fee
w = np.random.rand(3)

# Initialize an empty checklist to retailer the error values for every iteration of coaching
error_iter = []

# Practice the mannequin for the required variety of iterations and retailer the error values for every iteration
for i in vary(max_iter):
Y_hat = sigmoid(np.dot(X, w))
e = (-1 / len(Y)) * np.sum(Y * np.log(Y_hat) + (1 - Y) * np.log(1 - Y_hat))
error_iter.append(e)

grad_e = np.imply(np.multiply((Y_hat - Y), X.T), axis=1)
w -= eta * grad_e

# Retailer the error values for the present studying fee within the checklist of error values for all studying charges
error_all.append(error_iter)

# Plot the error values for every studying fee examined on the identical graph with a corresponding label
for i, eta in enumerate(eta_values):
plt.plot(error_all[i], label='eta = {}'.format(eta))

# Add axis labels, a title, and a legend to the graph
plt.xlabel('Iteration')
plt.ylabel('Error')
plt.title('Error Values with Totally different Studying Charges')
plt.legend()
plt.present()

Die Handlung ist:

Fazit: Bei hoher Lernrate werden die Parameter des Modells durch größere Iterationen aktualisiert. Dies kann durch ein Überschwingen der optimalen Werte verursacht werden.

Vielen Dank fürs Lesen.



Source link

HINTERLASSEN SIE EINE ANTWORT

Please enter your comment!
Please enter your name here