import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score


# ]ʂ̕\
def eval_and_print(name, y_true, y_pred):
    print(f"\n[{name}]")
    mse = mean_squared_error(y_true, y_pred)
    r2 = r2_score(y_true, y_pred)
    print("MSE:", round(mse,2))
    print("R^2:", round(r2,3))

    # Uz}i\ vs j
    plt.figure()
    plt.title(f"Diabetes: {name}")
    plt.scatter(y_true, y_pred, alpha=0.7)
    plt.xlabel("Actual Progression")
    plt.ylabel("Predicted Progression")
    min_val = min(y_true.min(), y_pred.min())
    max_val = max(y_true.max(), y_pred.max())
    plt.plot([min_val, max_val], [min_val, max_val], "r--")
    plt.show()


# 1) f[^ǂݍ݂ƕ
diabetes = load_diabetes()
X, y = diabetes.data, diabetes.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)


# x[XCiϗ\j
y_pred_base = np.full_like(y_test, y_train.mean(), dtype=float)
mse_base = mean_squared_error(y_test, y_pred_base)
print("[Baseline] MSE:", mse_base)


# 2) pCvCiW  `Aj
pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("lr", LinearRegression())
])


# 3) `Aŗ\ƕ]
# 4) Uz}ŉ
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
eval_and_print("Liner Regression", y_test, y_pred)


# 5) ʏdvx
importances = pipe.named_steps["lr"].coef_
df_importances = pd.DataFrame({
    "feature": diabetes.feature_names,
    "importance": importances
}).sort_values("importance", ascending=False)
print(df_importances,"\n")