Back to AI

人工智慧新手村

Coming soon

Python Demo, 20261014 GradientDescent

GradientDescent20261014a.py 

import numpy as np
import matplotlib.pyplot as plt

# Loss function: L(w) = (2w - 6)^2
def loss(w):
    return (2 * w - 6) ** 2

# Gradient: dL/dw = 8w - 24
def gradient(w):
    return 8 * w - 24

# Training settings
w = 0.0
learning_rate = 0.1
epochs = 20

history = []

for epoch in range(epochs):
    current_loss = loss(w)
    grad = gradient(w)

    history.append((epoch, w, current_loss, grad))

    # Gradient Descent update
    w = w - learning_rate * grad

print(f"Final w: {w:.6f}")
print(f"Final loss: {loss(w):.8f}")

# Plot the loss curve
ws = np.linspace(-1, 7, 200)
plt.plot(ws, loss(ws), label="Loss function")
plt.scatter(
    [item[1] for item in history],
    [item[2] for item in history],
    label="Optimization steps"
)
plt.xlabel("w")
plt.ylabel("Loss")
plt.title("Gradient Descent")
plt.legend()
plt.grid(True)
plt.show()

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *