import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
# ── Generate, split, scale, train (same pipeline) ──
outdoor_temp = 15 + 10 * np.random.randn(n_samples) * 0.5 + 5 * np.sin(np.linspace(0, 4 * np.pi, n_samples))
humidity = 60 - 0.5 * outdoor_temp + np.random.randn(n_samples) * 5
humidity = np.clip(humidity, 20, 95)
hour = np.random.randint(0, 24, n_samples).astype(float)
daily_cycle = 2 * np.sin(2 * np.pi * (hour - 6) / 24)
indoor_temp = 0.4 * outdoor_temp - 0.05 * humidity + daily_cycle + 18 + np.random.randn(n_samples) * 1.0
X = np.column_stack([outdoor_temp, humidity, hour])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
model = LinearRegression()
model.fit(X_train_scaled, y_train)
y_train_pred = model.predict(X_train_scaled)
y_test_pred = model.predict(X_test_scaled)
print("EVALUATION RESULTS")
print(f"\n{'Metric':<20} {'Train':<12} {'Test':<12}")
print(f"{'MSE':<20} {mean_squared_error(y_train, y_train_pred):<12.4f} {mean_squared_error(y_test, y_test_pred):<12.4f}")
print(f"{'MAE':<20} {mean_absolute_error(y_train, y_train_pred):<12.4f} {mean_absolute_error(y_test, y_test_pred):<12.4f}")
print(f"{'R-squared':<20} {r2_score(y_train, y_train_pred):<12.4f} {r2_score(y_test, y_test_pred):<12.4f}")
print(f"{'RMSE':<20} {np.sqrt(mean_squared_error(y_train, y_train_pred)):<12.4f} {np.sqrt(mean_squared_error(y_test, y_test_pred)):<12.4f}")
print(f"\nInterpretation:")
test_rmse = np.sqrt(mean_squared_error(y_test, y_test_pred))
test_r2 = r2_score(y_test, y_test_pred)
print(f" RMSE of {test_rmse:.2f} C means predictions are off by about {test_rmse:.1f} degrees on average.")
print(f" R-squared of {test_r2:.3f} means the model explains {test_r2 * 100:.1f}% of the variance in indoor temperature.")
# ── Plot: Predicted vs Actual ──
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].scatter(y_test, y_test_pred, alpha=0.6, s=20, color='steelblue')
min_val = min(y_test.min(), y_test_pred.min())
max_val = max(y_test.max(), y_test_pred.max())
axes[0].plot([min_val, max_val], [min_val, max_val], 'r--', linewidth=2, label='Perfect prediction')
axes[0].set_xlabel('Actual Indoor Temp (C)')
axes[0].set_ylabel('Predicted Indoor Temp (C)')
axes[0].set_title(f'Predicted vs Actual (R² = {test_r2:.3f})')
axes[0].grid(True, alpha=0.3)
errors = y_test - y_test_pred
axes[1].hist(errors, bins=20, color='steelblue', edgecolor='white', alpha=0.7)
axes[1].axvline(x=0, color='red', linestyle='--', linewidth=2)
axes[1].set_xlabel('Prediction Error (C)')
axes[1].set_ylabel('Count')
axes[1].set_title(f'Error Distribution (MAE = {mean_absolute_error(y_test, y_test_pred):.2f} C)')
axes[1].grid(True, alpha=0.3)
plt.savefig('regression_evaluation.png', dpi=100)
print("\nPlot saved as regression_evaluation.png")
Comments