# Pokemon Attack vs Speed
# Least Squares + Correlation + R^2 + MSE/RMSE
# Mean / Variance / Standard Deviation
# Normal Equations / Projection / Orthogonality
# Gradient (Derivative of SSE)
# Distance to Line
# Classification (Logistic & SVM) + Decision Boundaries
# --------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
# ==============================
# 1. Dummy data (Base Stats)
# ==============================
# Pikachu, Mewtwo, Dragonite
attack = np.array([55, 110, 134])
speed = np.array([90, 130, 80])
names = ["Pikachu", "Mewtwo", "Dragonite"]
X_feat = np.column_stack([attack, speed])
# ==============================
# 2. Mean / Variance / Std
# ==============================
attack_mean = np.mean(attack)
attack_var = np.var(attack, ddof=0)
attack_std = np.std(attack, ddof=0)
speed_mean = np.mean(speed)
speed_var = np.var(speed, ddof=0)
speed_std = np.std(speed, ddof=0)
# ==============================
# 3. Correlation coefficient
# ==============================
r = np.corrcoef(attack, speed)[0, 1]
# ==============================
# 4. Least Squares (Normal Equations)
# ==============================
# speed = a * attack + b
X = np.column_stack([attack, np.ones(len(attack))])
y = speed.reshape(-1, 1)
# (X^T X) beta = X^T y
XT_X = X.T @ X
XT_y = X.T @ y
beta = np.linalg.solve(XT_X, XT_y)
a, b = beta.flatten()
y_hat = X @ beta
residuals = (y - y_hat).flatten()
# ==============================
# 5. R^2, MSE, RMSE
# ==============================
SS_res = np.sum((y - y_hat) ** 2)
SS_tot = np.sum((y - np.mean(y)) ** 2)
R2 = 1 - SS_res / SS_tot
MSE = np.mean(residuals**2)
RMSE = np.sqrt(MSE)
# ==============================
# 6. Distance from point to line
# ==============================
# Line: a*x - y + b = 0
distances = np.abs(a * attack - speed + b) / np.sqrt(a**2 + 1)
# ==============================
# 7. Projection (Hat Matrix)
# ==============================
H = X @ np.linalg.inv(X.T @ X) @ X.T
y_hat_proj = H @ y
# Orthogonality: X^T (y - Xβ) = 0
orthogonality = X.T @ residuals.reshape(-1, 1)
# ==============================
# 8. Gradient (Derivative of SSE)
# ==============================
# SSE = ||y - Xβ||^2
# ∂SSE/∂β = -2 X^T (y - Xβ)
gradient_SSE = -2 * X.T @ (y - y_hat)
# ==============================
# 9. Classification labels (dummy)
# ==============================
# 0: low-speed, 1: high-speed
labels = np.array([1, 1, 0])
# ==============================
# 10. Logistic Regression
# ==============================
logreg = LogisticRegression()
logreg.fit(X_feat, labels)
# ==============================
# 11. SVM (linear)
# ==============================
svm = SVC(kernel="linear")
svm.fit(X_feat, labels)
# ==============================
# 12. Decision boundary grid
# ==============================
x_min, x_max = attack.min() - 10, attack.max() + 10
y_min, y_max = speed.min() - 10, speed.max() + 10
xx, yy = np.meshgrid(
np.linspace(x_min, x_max, 200),
np.linspace(y_min, y_max, 200)
)
grid = np.c_[xx.ravel(), yy.ravel()]
Z_log = logreg.predict(grid).reshape(xx.shape)
Z_svm = svm.predict(grid).reshape(xx.shape)
# ==============================
# 13. Plot
# ==============================
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
# --- Regression plot ---
axes[0].scatter(attack, speed)
for x, y_obs, y_pred, name in zip(attack, speed, y_hat.flatten(), names):
axes[0].text(x + 1, y_obs + 1, name)
axes[0].plot([x, x], [y_obs, y_pred], linestyle="dashed")
x_line = np.linspace(x_min, x_max, 100)
y_line = a * x_line + b
axes[0].plot(x_line, y_line)
axes[0].set_title(f"Least Squares (R² = {R2:.3f})")
axes[0].set_xlabel("Attack")
axes[0].set_ylabel("Speed")
axes[0].grid(True)
# --- Logistic Regression boundary ---
axes[1].contourf(xx, yy, Z_log, alpha=0.3)
axes[1].scatter(attack, speed, c=labels)
axes[1].set_title("Logistic Regression (Decision Boundary)")
axes[1].set_xlabel("Attack")
axes[1].set_ylabel("Speed")
axes[1].grid(True)
# --- SVM boundary ---
axes[2].contourf(xx, yy, Z_svm, alpha=0.3)
axes[2].scatter(attack, speed, c=labels)
axes[2].set_title("SVM (Linear) Decision Boundary")
axes[2].set_xlabel("Attack")
axes[2].set_ylabel("Speed")
axes[2].grid(True)
plt.tight_layout()
plt.show()
# ==============================
# 14. Print numerical results
# ==============================
print("=== Basic Statistics ===")
print("Attack: mean =", attack_mean, ", var =", attack_var, ", std =", attack_std)
print("Speed : mean =", speed_mean, ", var =", speed_var, ", std =", speed_std)
print("\n=== Correlation ===")
print("Correlation coefficient r =", r)
print("r^2 =", r**2)
print("\n=== Normal Equations ===")
print("X^T X =\n", XT_X)
print("X^T y =\n", XT_y)
print("\n=== Least Squares Solution ===")
print("Speed = {:.3f} * Attack + {:.3f}".format(a, b))
print("\n=== Fit Quality ===")
print("R^2 =", R2)
print("MSE =", MSE)
print("RMSE =", RMSE)
print("\n=== Residual Analysis ===")
print("Residuals =", residuals)
print("Distance to regression line =", distances)
print("\n=== Linear Algebra Checks ===")
print("Projection check (y_hat == H y):", np.allclose(y_hat, y_hat_proj))
print("Orthogonality (X^T residuals) =\n", orthogonality)
print("\n=== Gradient of SSE ===")
print("∂SSE/∂β =\n", gradient_SSE)
print("\n=== Logistic Regression Parameters ===")
print("w =", logreg.coef_)
print("b =", logreg.intercept_)
print("\n=== SVM Parameters ===")
print("w =", svm.coef_)
print("b =", svm.intercept_)
print("SVM margin width =", 2 / np.linalg.norm(svm.coef_))
# Dragon-type Pokémon
# Attack vs Speed (Inverse Proportionality)
# Absolute Deviation Fit (L1 / LAD)
# -----------------------------------------
# Model:
# Speed ≈ k / Attack + b
# Linearized:
# Speed = k * (1/Attack) + b
# Objective:
# minimize sum |y_i - (k * x_i + b)|
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linprog
# ==============================
# 1. Concrete Pokémon data
# ==============================
names = [
"Garchomp",
"Dragonite",
"Salamence",
"Hydreigon",
"Haxorus",
"Kommo-o"
]
attack = np.array([130, 134, 135, 105, 147, 110])
speed = np.array([102, 80, 100, 98, 97, 85])
x = 1 / attack
y = speed
n = len(y)
# ==============================
# 2. L1 regression via LP
# ==============================
# Variables:
# [k, b, e1+, e1-, e2+, e2-, ..., en+, en-]
# minimize sum(ei+ + ei-)
# subject to:
# y_i - (k*x_i + b) = ei+ - ei-
num_vars = 2 + 2*n
c = np.zeros(num_vars)
c[2:] = 1 # objective: sum of absolute errors
A_eq = np.zeros((n, num_vars))
b_eq = y.copy()
for i in range(n):
A_eq[i, 0] = x[i] # k
A_eq[i, 1] = 1 # b
A_eq[i, 2 + 2*i] = 1 # e+
A_eq[i, 2 + 2*i + 1] = -1 # e-
bounds = [(None, None), (None, None)] + [(0, None)] * (2*n)
res = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, method="highs")
k_abs, b_abs = res.x[0], res.x[1]
# ==============================
# 3. Prediction
# ==============================
attack_line = np.linspace(min(attack) - 5, max(attack) + 5, 300)
speed_line = k_abs / attack_line + b_abs
y_hat = k_abs * x + b_abs
abs_errors = np.abs(y - y_hat)
MAE = np.mean(abs_errors)
# ==============================
# 4. Plot
# ==============================
plt.figure(figsize=(7, 6))
plt.scatter(attack, speed, s=80)
for a, s, n in zip(attack, speed, names):
plt.text(a + 0.8, s + 0.8, n)
plt.plot(attack_line, speed_line, color="red", linewidth=2,
label="L1 (Absolute Deviation) Fit")
plt.xlabel("Attack")
plt.ylabel("Speed")
plt.title("Dragon-type Pokémon\nAttack vs Speed (Absolute Value Fit)")
plt.legend()
plt.grid(True)
plt.show()
# ==============================
# 5. Results
# ==============================
print("Absolute deviation model:")
print("Speed ≈ k / Attack + b")
print("k =", k_abs)
print("b =", b_abs)
print("\nMean Absolute Error (MAE) =", MAE)
print("\nAbsolute errors:")
for n, e in zip(names, abs_errors):
print(f"{n}: {e:.2f}")
# Pokemon MooMoo Milk Sales vs Temperature
# Quadratic Least Squares (Parabola)
# + Maximum / Minimum via Differentiation
# ---------------------------------
# Model:
# y = a*T^2 + b*T + c
# dy/dT = 2aT + b
# Extreme point at T* = -b / (2a)
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Dummy data
# ==============================
temp = np.array([5, 10, 15, 20, 25, 30]) # Temperature (°C)
sales = np.array([40, 65, 85, 90, 70, 45]) # Sales (bottles/day)
# ==============================
# 2. Design matrix (quadratic)
# ==============================
X = np.column_stack([temp**2, temp, np.ones(len(temp))])
y = sales.reshape(-1, 1)
# ==============================
# 3. Least Squares (Normal Equations)
# ==============================
beta = np.linalg.solve(X.T @ X, X.T @ y)
a, b, c = beta.flatten()
y_hat = X @ beta
residuals = (y - y_hat).flatten()
# ==============================
# 4. Fit quality
# ==============================
SS_res = np.sum((y - y_hat) ** 2)
SS_tot = np.sum((y - np.mean(y)) ** 2)
R2 = 1 - SS_res / SS_tot
MSE = np.mean(residuals**2)
RMSE = np.sqrt(MSE)
# ==============================
# 5. Maximum / Minimum (Derivative)
# ==============================
# dy/dT = 2aT + b = 0
T_extreme = -b / (2 * a)
sales_extreme = a * T_extreme**2 + b * T_extreme + c
if a < 0:
extreme_type = "Maximum"
else:
extreme_type = "Minimum"
# ==============================
# 6. Smooth curve for plotting
# ==============================
t_line = np.linspace(temp.min() - 2, temp.max() + 2, 200)
y_line = a * t_line**2 + b * t_line + c
# ==============================
# 7. Plot
# ==============================
plt.figure(figsize=(6, 5))
plt.scatter(temp, sales, label="Data (MooMoo Milk Sales)")
plt.plot(t_line, y_line, label="Quadratic Least Squares")
# Residuals
for T, y_obs, y_p in zip(temp, sales, y_hat.flatten()):
plt.plot([T, T], [y_obs, y_p], linestyle="dashed", alpha=0.6)
# Extreme point
plt.scatter(T_extreme, sales_extreme, color="red", zorder=5)
plt.axvline(T_extreme, linestyle="dotted", color="red", alpha=0.7)
plt.text(
T_extreme + 0.5,
sales_extreme,
f"{extreme_type}\nT = {T_extreme:.2f}°C\nSales = {sales_extreme:.1f}",
)
plt.xlabel("Temperature (°C)")
plt.ylabel("Sales (bottles/day)")
plt.title("MooMoo Milk Sales vs Temperature (Parabolic Fit)")
plt.legend()
plt.grid(True)
plt.show()
# ==============================
# 8. Print results
# ==============================
print("Quadratic model:")
print("Sales = {:.4f} * T^2 + {:.4f} * T + {:.4f}".format(a, b, c))
print("\nFit quality:")
print("R^2 =", R2)
print("MSE =", MSE)
print("RMSE =", RMSE)
print("\nExtreme point (via differentiation):")
print(extreme_type)
print("Temperature =", T_extreme)
print("Sales =", sales_extreme)
print("\nResiduals:")
print(residuals)
# Pokemon Encounter Waiting Time
# Exponential Distribution (Waiting Time Model)
# ---------------------------------------------
# Purpose:
# Model waiting time until a Pokemon encounter
# using an exponential distribution
#
# Model:
# f(t) = lambda * exp(-lambda * t)
# E[T] = 1 / lambda
#
# Units:
# Time: minutes
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Parameters
# ==============================
# Encounter rate (per minute)
# e.g., average encounter every 5 minutes
lam = 1 / 5.0 # lambda
# ==============================
# 2. Dummy waiting time data
# ==============================
np.random.seed(0)
waiting_time = np.random.exponential(scale=1/lam, size=200)
# ==============================
# 3. Exponential PDF
# ==============================
t = np.linspace(0, 25, 300)
pdf = lam * np.exp(-lam * t)
# ==============================
# 4. Statistics
# ==============================
mean_wait = np.mean(waiting_time)
var_wait = np.var(waiting_time)
std_wait = np.std(waiting_time)
# ==============================
# 5. Plot
# ==============================
plt.figure(figsize=(6, 5))
# Histogram (normalized)
plt.hist(waiting_time, bins=20, density=True, alpha=0.6, label="Observed waiting time")
# Theoretical PDF
plt.plot(t, pdf, linewidth=2, label="Exponential PDF")
plt.xlabel("Waiting Time (minutes)")
plt.ylabel("Probability Density")
plt.title("Pokemon Encounter Waiting Time\n(Exponential Distribution)")
plt.legend()
plt.grid(True)
plt.show()
# ==============================
# 6. Print results
# ==============================
print("Exponential distribution model")
print("lambda =", lam)
print("Theoretical mean =", 1 / lam)
print("\nSample statistics:")
print("Mean =", mean_wait)
print("Variance =", var_wait)
print("Standard deviation =", std_wait)
# Pokemon Level vs Experience
# Logarithmic Plot (Semi-log)
# ---------------------------
# Purpose:
# Demonstrate logarithmic graphs using dummy Pokemon data
#
# Example:
# Pokemon level vs required experience points (EXP)
#
# Axes:
# x-axis: Level (linear)
# y-axis: EXP (log scale)
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Dummy data
# ==============================
# Pokemon levels
level = np.arange(1, 101)
# Dummy EXP growth (roughly exponential growth)
# This mimics typical RPG leveling curves
exp = 50 * level**3
# ==============================
# 2. Basic statistics
# ==============================
mean_exp = np.mean(exp)
var_exp = np.var(exp)
std_exp = np.std(exp)
# ==============================
# 3. Plot (logarithmic y-axis)
# ==============================
plt.figure(figsize=(6, 5))
plt.plot(level, exp, marker="o", markersize=3, linestyle="-")
plt.yscale("log") # logarithmic scale
plt.xlabel("Pokemon Level")
plt.ylabel("Required EXP (log scale)")
plt.title("Pokemon Level vs EXP (Logarithmic Graph)")
plt.grid(True, which="both")
plt.show()
# ==============================
# 4. Print results
# ==============================
print("EXP statistics (dummy data)")
print("Mean =", mean_exp)
print("Variance =", var_exp)
print("Standard deviation =", std_exp)
print("Min EXP =", np.min(exp))
print("Max EXP =", np.max(exp))
# Pokemon-style demo:
# Why computing probabilities in log-space is easier and safer
# ------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Tiny probabilities (capture rate)
# ==============================
p = 0.01
n_trials = 100
# Direct probability (underflow-prone)
P_direct = p ** n_trials
# Log-probability (stable)
logP = n_trials * np.log(p)
P_from_log = np.exp(logP)
print("Direct probability:", P_direct)
print("Log probability:", logP)
print("Recovered from log:", P_from_log)
# ==============================
# 2. Product -> Sum (many encounters)
# ==============================
probs = np.random.uniform(0.005, 0.02, size=50) # varying capture rates
prod_direct = np.prod(probs)
sum_log = np.sum(np.log(probs))
prod_from_log = np.exp(sum_log)
print("\nProduct (direct):", prod_direct)
print("Sum of logs:", sum_log)
print("Product from log:", prod_from_log)
# ==============================
# 3. Exponential distribution (waiting time)
# ==============================
# Time until a rare Pokemon appears
lam = 0.3 # rate
t = np.linspace(0, 15, 300)
pdf = lam * np.exp(-lam * t)
log_pdf = np.log(lam) - lam * t
# Derivative of log-pdf (easy!)
d_log_pdf_dt = -lam * np.ones_like(t)
# ==============================
# 4. Visualization
# ==============================
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(t, pdf, label="pdf")
plt.plot(t, np.exp(log_pdf), "--", label="exp(log pdf)")
plt.title("Exponential Waiting Time")
plt.xlabel("Time")
plt.ylabel("Probability Density")
plt.legend()
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(t, log_pdf, label="log pdf")
plt.title("Log Probability (Linear & Stable)")
plt.xlabel("Time")
plt.ylabel("log Probability")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# ==============================
# 5. Log-sum-exp trick (model comparison)
# ==============================
# Competing encounter models
log_likes = np.array([-120.5, -121.2, -119.8])
# Naive sum in prob-space (bad)
naive = np.sum(np.exp(log_likes))
# Stable log-sum-exp
m = np.max(log_likes)
logsumexp = m + np.log(np.sum(np.exp(log_likes - m)))
print("\nNaive sum:", naive)
print("LogSumExp:", logsumexp)
print("Recovered sum:", np.exp(logsumexp))
# Pikachu's "10,000,000 Volt Thunderbolt"
# Sine Wave Signal + FFT Analysis
# ---------------------------------------
# Purpose:
# Model Pikachu's electric attack as a sine wave
# and analyze its frequency components using FFT
#
# Signal meaning:
# Voltage waveform of electric shock
#
# Units:
# Time: seconds
# Amplitude: arbitrary voltage units
# Frequency: Hz
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Time axis
# ==============================
fs = 1000 # Sampling frequency [Hz]
T = 1.0 # Duration [s]
t = np.linspace(0, T, int(fs*T), endpoint=False)
# ==============================
# 2. Pikachu Thunderbolt signal
# ==============================
# Base electric oscillation
f1 = 50 # Main frequency [Hz]
f2 = 120 # Harmonic [Hz]
signal = (
1.0 * np.sin(2 * np.pi * f1 * t) +
0.5 * np.sin(2 * np.pi * f2 * t)
)
# ==============================
# 3. FFT
# ==============================
fft_vals = np.fft.fft(signal)
freqs = np.fft.fftfreq(len(fft_vals), d=1/fs)
# Magnitude spectrum
magnitude = np.abs(fft_vals) / len(fft_vals)
# Use only positive frequencies
pos_mask = freqs >= 0
freqs_pos = freqs[pos_mask]
mag_pos = magnitude[pos_mask]
# ==============================
# 4. Plot
# ==============================
plt.figure(figsize=(10, 5))
# --- Time domain ---
plt.subplot(1, 2, 1)
plt.plot(t[:200], signal[:200])
plt.title("Pikachu Thunderbolt (Time Domain)")
plt.xlabel("Time [s]")
plt.ylabel("Voltage (arb.)")
plt.grid(True)
# --- Frequency domain ---
plt.subplot(1, 2, 2)
plt.stem(freqs_pos, mag_pos, basefmt=" ")
plt.xlim(0, 200)
plt.title("FFT Spectrum (Frequency Domain)")
plt.xlabel("Frequency [Hz]")
plt.ylabel("Magnitude")
plt.grid(True)
plt.tight_layout()
plt.show()
# ==============================
# 5. Print dominant frequencies
# ==============================
peak_indices = np.argsort(mag_pos)[-5:][::-1]
print("Dominant frequency components:")
for i in peak_indices:
print(f"Frequency = {freqs_pos[i]:.1f} Hz, Magnitude = {mag_pos[i]:.3f}")
# Pokemon Speed Distribution
# Normal Distribution + Derivative + Integral (CDF)
# + Moments (Mean, Variance, Skewness, Kurtosis)
# -------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm, skew, kurtosis
# ==============================
# 1. Dummy Pokémon speed data
# ==============================
speed_data = np.array([
35, 45, 60, 70, 80, 90, 95, 100,
110, 120, 130, 140
])
# ==============================
# 2. Moments (from data)
# ==============================
mu = np.mean(speed_data) # 1st moment (mean)
var = np.var(speed_data, ddof=0) # 2nd central moment (variance)
sigma = np.sqrt(var) # standard deviation
sk = skew(speed_data, bias=True) # 3rd standardized moment
kt = kurtosis(speed_data, bias=True) # 4th standardized moment (excess)
# ==============================
# 3. Continuous axis
# ==============================
x = np.linspace(mu - 4*sigma, mu + 4*sigma, 500)
# ==============================
# 4. Normal distribution
# ==============================
pdf = norm.pdf(x, mu, sigma)
cdf = norm.cdf(x, mu, sigma)
# ==============================
# 5. Derivative of PDF
# ==============================
pdf_derivative = - (x - mu) / (sigma**2) * pdf
# ==============================
# 6. Numerical integral (CDF check)
# ==============================
dx = x[1] - x[0]
cdf_numerical = np.cumsum(pdf) * dx
# ==============================
# 7. Plot
# ==============================
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
axes[0].plot(x, pdf)
axes[0].set_title("Pokémon Speed PDF")
axes[0].set_xlabel("Speed")
axes[0].set_ylabel("Density")
axes[0].grid(True)
axes[1].plot(x, pdf_derivative)
axes[1].axhline(0, linestyle="dashed")
axes[1].set_title("Derivative of PDF")
axes[1].set_xlabel("Speed")
axes[1].set_ylabel("d/dx PDF")
axes[1].grid(True)
axes[2].plot(x, cdf, label="Analytical CDF")
axes[2].plot(x, cdf_numerical, linestyle="dashed", label="Numerical Integral")
axes[2].set_title("CDF")
axes[2].set_xlabel("Speed")
axes[2].set_ylabel("Probability")
axes[2].legend()
axes[2].grid(True)
plt.tight_layout()
plt.show()
# ==============================
# 8. Print moments
# ==============================
print("Pokémon Speed Moments")
print("Mean (1st moment) =", mu)
print("Variance (2nd central moment) =", var)
print("Standard deviation =", sigma)
print("Skewness (3rd standardized moment) =", sk)
print("Kurtosis (4th standardized moment, excess) =", kt)
print("\nChecks")
print("Integral of PDF ≈", cdf_numerical[-1])
print("PDF derivative at mean =",
- (mu - mu) / (sigma**2) * norm.pdf(mu, mu, sigma))
# Garchomp vs Dragonite
# Attack & Speed mapped to Euler's Formula
# z = Attack + i * Speed
# exp(iθ) = cosθ + i sinθ
# (Radians + Degrees)
# ----------------------------------------
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Pokémon base stats (dummy)
# ==============================
# Garchomp, Dragonite
names = ["Garchomp", "Dragonite"]
attack = np.array([130, 134])
speed = np.array([102, 80])
# Complex representation
# z = Attack + i * Speed
z = attack + 1j * speed
# ==============================
# 2. Polar form
# ==============================
r = np.abs(z) # magnitude
theta_rad = np.angle(z) # angle (radians)
theta_deg = np.degrees(theta_rad) # angle (degrees)
# Euler representation
z_euler = r * np.exp(1j * theta_rad)
# ==============================
# 3. Euler formula components
# ==============================
cos_theta = np.cos(theta_rad)
sin_theta = np.sin(theta_rad)
# ==============================
# 4. Plot on complex plane
# ==============================
plt.figure(figsize=(6, 6))
plt.axhline(0, linestyle="dashed", alpha=0.5)
plt.axvline(0, linestyle="dashed", alpha=0.5)
for i, name in enumerate(names):
plt.scatter(attack[i], speed[i])
plt.text(
attack[i] + 1,
speed[i] + 1,
f"{name}\nθ={theta_deg[i]:.1f}°"
)
plt.plot([0, attack[i]], [0, speed[i]])
plt.xlabel("Real axis (Attack)")
plt.ylabel("Imaginary axis (Speed)")
plt.title("Pokémon Stats on Complex Plane (Euler Representation)")
plt.grid(True)
plt.axis("equal")
plt.show()
# ==============================
# 5. Print results
# ==============================
for i, name in enumerate(names):
print(name)
print("z =", z[i])
print("|z| =", r[i])
print("θ (rad) =", theta_rad[i])
print("θ (deg) =", theta_deg[i])
print("cosθ =", cos_theta[i])
print("sinθ =", sin_theta[i])
print("Euler form |z|·e^{iθ} =", z_euler[i])
print("-" * 40)
# Pokemon-like Sequences (Numerical Series)
# ----------------------------------------
# Purpose:
# Demonstrate typical mathematical sequences
# using Pokémon-themed interpretations
#
# Included:
# 1. Arithmetic sequence (Level-up stat growth)
# 2. Geometric sequence (Experience required per level)
# 3. Fibonacci-like series (Evolution rarity / population growth)
# 4. Difference & ratio check
#
# No external data, dummy but "Pokémon-like"
import numpy as np
import matplotlib.pyplot as plt
# ==============================
# 1. Arithmetic sequence
# ==============================
# Example: Attack increases by +5 every level
level = np.arange(1, 11)
attack = 50 + 5 * (level - 1)
# ==============================
# 2. Geometric sequence
# ==============================
# Example: Experience required grows by ×1.2 each level
exp = 100 * (1.2 ** (level - 1))
# ==============================
# 3. Fibonacci-like sequence
# ==============================
# Example: Rare Pokémon population growth
fib = [1, 1]
for _ in range(8):
fib.append(fib[-1] + fib[-2])
fib = np.array(fib)
# ==============================
# 4. Difference & ratio
# ==============================
attack_diff = np.diff(attack)
exp_ratio = exp[1:] / exp[:-1]
# ==============================
# 5. Plot
# ==============================
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
# Arithmetic
axes[0].plot(level, attack, marker="o")
axes[0].set_title("Arithmetic Sequence (Attack Growth)")
axes[0].set_xlabel("Level")
axes[0].set_ylabel("Attack")
axes[0].grid(True)
# Geometric
axes[1].plot(level, exp, marker="o")
axes[1].set_title("Geometric Sequence (EXP Requirement)")
axes[1].set_xlabel("Level")
axes[1].set_ylabel("EXP")
axes[1].set_yscale("log")
axes[1].grid(True)
# Fibonacci
axes[2].plot(level, fib, marker="o")
axes[2].set_title("Fibonacci-like Sequence (Population)")
axes[2].set_xlabel("Generation")
axes[2].set_ylabel("Count")
axes[2].grid(True)
plt.tight_layout()
plt.show()
# ==============================
# 6. Print results
# ==============================
print("Arithmetic sequence (Attack):")
print(attack)
print("Common difference:", attack_diff)
print("\nGeometric sequence (EXP):")
print(np.round(exp, 2))
print("Common ratio:", np.round(exp_ratio, 3))
print("\nFibonacci-like sequence:")
print(fib)
# ==============================
# PCA: Pokémon Stats Dimensionality Reduction
# HP / Atk / Def / SpAtk / SpDef / Speed
# --------------------------------------
# Interpretation:
# PC1 ≈ overall strength
# PC2 ≈ physical vs special tendency
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
# ==============================
# 1. Pokémon stats (concrete data)
# ==============================
names = ["Garchomp", "Dragonite", "Salamence", "Pikachu", "Mewtwo"]
stats = np.array([
[108, 130, 95, 80, 85, 102], # Garchomp
[91, 134, 95, 100, 110, 80], # Dragonite
[95, 135, 80, 110, 80, 100], # Salamence
[35, 55, 40, 50, 50, 90], # Pikachu
[106, 110, 90, 154, 90, 130], # Mewtwo
])
features = ["HP", "Atk", "Def", "SpAtk", "SpDef", "Speed"]
# ==============================
# 2. Standardization
# ==============================
scaler = StandardScaler()
stats_scaled = scaler.fit_transform(stats)
# ==============================
# 3. PCA
# ==============================
pca = PCA(n_components=2)
coords = pca.fit_transform(stats_scaled)
# ==============================
# 4. Explained variance
# ==============================
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Cumulative variance:", np.sum(pca.explained_variance_ratio_))
# ==============================
# 5. Component loadings
# ==============================
print("\nPCA loadings:")
for i, comp in enumerate(pca.components_):
print(f"PC{i+1}")
for f, v in zip(features, comp):
print(f" {f:6s}: {v:.3f}")
# ==============================
# 6. Plot (PCA space)
# ==============================
plt.figure(figsize=(6, 6))
plt.axhline(0, linestyle="dashed", alpha=0.5)
plt.axvline(0, linestyle="dashed", alpha=0.5)
plt.scatter(coords[:, 0], coords[:, 1], s=80)
for i, name in enumerate(names):
plt.text(coords[i, 0] + 0.05, coords[i, 1] + 0.05, name)
plt.xlabel("PC1 (Overall Strength)")
plt.ylabel("PC2 (Physical ↔ Special)")
plt.title("PCA of Pokémon Base Stats")
plt.grid(True)
plt.axis("equal")
plt.show()