|
| 1 | +"""quadratic_cost_demo.py |
| 2 | +~~~~~~~~~~~~~~~~~~~~~~~~ |
| 3 | +
|
| 4 | +Demonstration of quadratic cost function during gradient descent training. |
| 5 | +
|
| 6 | +""" |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import matplotlib.pyplot as plt |
| 10 | + |
| 11 | + |
| 12 | +def sigmoid(z): |
| 13 | + """The sigmoid function.""" |
| 14 | + return 1.0/(1.0+np.exp(-z)) |
| 15 | + |
| 16 | + |
| 17 | +def sigmoid_prime(z): |
| 18 | + """Derivative of the sigmoid function.""" |
| 19 | + return sigmoid(z)*(1-sigmoid(z)) |
| 20 | + |
| 21 | + |
| 22 | +def quadraticCostDemo(epochs): |
| 23 | + """Demonstrate quadratic cost function over epochs.""" |
| 24 | + w = 0.6 |
| 25 | + b = 0.9 |
| 26 | + x = 1 |
| 27 | + y = 0 # desired output |
| 28 | + cost_history = {} # dictionary to store cost values |
| 29 | + |
| 30 | + # Enable interactive mode for real-time plotting |
| 31 | + plt.ion() |
| 32 | + fig, ax = plt.subplots(figsize=(10, 6)) |
| 33 | + |
| 34 | + for i in range(1, epochs): |
| 35 | + z = w * x + b |
| 36 | + a = sigmoid(z) |
| 37 | + cost = 0.5 * (a - y) ** 2 |
| 38 | + cost_history[i] = cost |
| 39 | + |
| 40 | + # Calculate gradients |
| 41 | + nabla_cW = (a - y) * sigmoid_prime(z) * x |
| 42 | + nabla_cB = (a - y) * sigmoid_prime(z) |
| 43 | + |
| 44 | + # Update weights and bias |
| 45 | + w = w - nabla_cW |
| 46 | + b = b - nabla_cB |
| 47 | + |
| 48 | + # Update plot in real-time |
| 49 | + if i % 5 == 0 or i == 1: # Update every 5 epochs for better visualization |
| 50 | + ax.clear() |
| 51 | + epoch_list = sorted(cost_history.keys()) |
| 52 | + cost_list = [cost_history[e] for e in epoch_list] |
| 53 | + |
| 54 | + ax.plot(epoch_list, cost_list, 'b-', linewidth=2) |
| 55 | + ax.set_xlabel('Epoch', fontsize=12) |
| 56 | + ax.set_ylabel('Quadratic Cost', fontsize=12) |
| 57 | + ax.set_title('Quadratic Cost Function Over Training Epochs', fontsize=14) |
| 58 | + ax.grid(True, alpha=0.3) |
| 59 | + plt.tight_layout() |
| 60 | + plt.pause(0.01) # Small pause to see the update |
| 61 | + |
| 62 | + # Turn off interactive mode |
| 63 | + plt.ioff() |
| 64 | + |
| 65 | + return cost_history |
| 66 | + |
| 67 | + |
| 68 | +def plot_cost_history(cost_history): |
| 69 | + """Plot the cost function over epochs.""" |
| 70 | + epochs = sorted(cost_history.keys()) |
| 71 | + costs = [cost_history[epoch] for epoch in epochs] |
| 72 | + |
| 73 | + plt.figure(figsize=(10, 6)) |
| 74 | + plt.plot(epochs, costs, 'b-', linewidth=2) |
| 75 | + plt.xlabel('Epoch', fontsize=12) |
| 76 | + plt.ylabel('Quadratic Cost', fontsize=12) |
| 77 | + plt.title('Quadratic Cost Function Over Training Epochs', fontsize=14) |
| 78 | + plt.grid(True, alpha=0.3) |
| 79 | + plt.tight_layout() |
| 80 | + plt.savefig('quadratic_cost_plot.png', dpi=150, bbox_inches='tight') |
| 81 | + print("Plot saved to quadratic_cost_plot.png") |
| 82 | + plt.show() |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + # Run the demo with 100 epochs |
| 87 | + epochs = 300 |
| 88 | + cost_history = quadraticCostDemo(epochs) |
| 89 | + |
| 90 | + # Save final plot |
| 91 | + plt.figure(figsize=(10, 6)) |
| 92 | + epoch_list = sorted(cost_history.keys()) |
| 93 | + cost_list = [cost_history[e] for e in epoch_list] |
| 94 | + plt.plot(epoch_list, cost_list, 'b-', linewidth=2) |
| 95 | + plt.xlabel('Epoch', fontsize=12) |
| 96 | + plt.ylabel('Quadratic Cost', fontsize=12) |
| 97 | + plt.title('Quadratic Cost Function Over Training Epochs', fontsize=14) |
| 98 | + plt.grid(True, alpha=0.3) |
| 99 | + plt.tight_layout() |
| 100 | + plt.savefig('quadratic_cost_plot.png', dpi=150, bbox_inches='tight') |
| 101 | + print("Plot saved to quadratic_cost_plot.png") |
| 102 | + plt.show() |
0 commit comments