Building MLP Block
Creating a MLP Block
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
# Generate data points for the GeLU function
x = np.linspace(5, 1000, 1000000) # Range of x values to avoid sqrt(0)
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))
y = gelu(x)
# Fit a polynomial to approximate the GeLU function
degree = 6
coeffs = np.polyfit(x, y, degree)
poly_approx = np.poly1d(coeffs)
# Calculate error metrics
abs_mean_error = np.abs(y - poly_approx(x)).mean()
max_error = np.abs(y - poly_approx(x)).max()
median_error = np.median(np.abs(y - poly_approx(x)))
print(f"Mean absolute error: {abs_mean_error}")
print(f"Max error: {max_error}")
print(f"Median error: {median_error}")
# Plot the true function and polynomial approximation
plt.plot(x, y, label="GeLU(x)", color="blue")
plt.plot(x, poly_approx(x), label=f"Polynomial approx (degree {degree})", color="red", linestyle="--")
# Labels and legend
plt.xlabel("x")
plt.ylabel("y")
plt.title("GeLU Function and Polynomial Approximation")
plt.legend()
plt.grid(True)
plt.show()
# Print polynomial coefficients for reference
print(f"Coefficients of the polynomial: {coeffs}")Last updated