-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_regression_example.py
More file actions
41 lines (34 loc) · 1.53 KB
/
Copy pathlinear_regression_example.py
File metadata and controls
41 lines (34 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Import necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Create a sample pandas DataFrame
# This DataFrame contains two features ('feature1', 'feature2') and a 'target' variable.
data = {'feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'feature2': [2, 4, 5, 4, 2, 4, 6, 8, 8, 9],
'target': [3, 6, 8, 7, 5, 7, 9, 12, 11, 13]}
df = pd.DataFrame(data)
# Separate features (X) and target variable (y)
# X contains the independent variables (features).
# y contains the dependent variable (target).
X = df[['feature1', 'feature2']]
y = df['target']
# Split data into training and testing sets
# The data is split into 80% training and 20% testing.
# random_state is set for reproducibility.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize and train the LinearRegression model
# A LinearRegression model is initialized.
model = LinearRegression()
# The model is trained using the training data (X_train, y_train).
model.fit(X_train, y_train)
# Make predictions on the testing data
# The trained model is used to make predictions on the test features (X_test).
y_pred = model.predict(X_test)
# Calculate Mean Squared Error
# MSE is calculated to evaluate the model's performance on the test data.
mse = mean_squared_error(y_test, y_pred)
# Print the MSE
# The calculated Mean Squared Error is printed to the console.
print(f"Mean Squared Error: {mse}")