V8055 commited on
Commit
53de850
·
verified ·
1 Parent(s): bf0f626

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.linear_model import LinearRegression
6
+ from sklearn.metrics import mean_squared_error, r2_score
7
+
8
+ # Generate sample dataset
9
+ np.random.seed(42)
10
+ X = np.random.rand(100, 1) * 10
11
+ y = 2 * X + 1 + np.random.randn(100, 1) * 2
12
+
13
+ # Create DataFrame for better data handling
14
+ df = pd.DataFrame({'X': X.flatten(), 'y': y.flatten()})
15
+
16
+ # Split the data
17
+ X_train, X_test, y_train, y_test = train_test_split(
18
+ df[['X']], df['y'], test_size=0.2, random_state=42
19
+ )
20
+
21
+ # Create and train the model
22
+ model = LinearRegression()
23
+ model.fit(X_train, y_train)
24
+
25
+ # Make predictions
26
+ y_train_pred = model.predict(X_train)
27
+ y_test_pred = model.predict(X_test)
28
+
29
+ # Calculate metrics
30
+ train_mse = mean_squared_error(y_train, y_train_pred)
31
+ test_mse = mean_squared_error(y_test, y_test_pred)
32
+ train_r2 = r2_score(y_train, y_train_pred)
33
+ test_r2 = r2_score(y_test, y_test_pred)
34
+
35
+ # Print model performance metrics
36
+ print("Model Performance Metrics:")
37
+ print("-" * 50)
38
+ print(f"Training MSE: {train_mse:.4f}")
39
+ print(f"Test MSE: {test_mse:.4f}")
40
+ print(f"Training R²: {train_r2:.4f}")
41
+ print(f"Test R²: {test_r2:.4f}")
42
+ print(f"\nModel Equation: y = {model.coef_[0]:.4f}x + {model.intercept_:.4f}")
43
+
44
+ # Create visualization
45
+ plt.figure(figsize=(10, 6))
46
+
47
+ # Plot training data
48
+ plt.scatter(X_train, y_train, color='blue', alpha=0.5, label='Training Data')
49
+ # Plot test data
50
+ plt.scatter(X_test, y_test, color='green', alpha=0.5, label='Test Data')
51
+
52
+ # Plot regression line
53
+ X_line = np.linspace(0, 10, 100).reshape(-1, 1)
54
+ y_line = model.predict(X_line)
55
+ plt.plot(X_line, y_line, color='red', label='Regression Line')
56
+
57
+ plt.xlabel('X')
58
+ plt.ylabel('y')
59
+ plt.title('Linear Regression: Training and Test Data with Regression Line')
60
+ plt.legend()
61
+ plt.grid(True, alpha=0.3)
62
+ plt.show()