-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_reg.py
More file actions
47 lines (36 loc) · 1.58 KB
/
linear_reg.py
File metadata and controls
47 lines (36 loc) · 1.58 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
42
43
44
45
46
47
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features: Sepal length, Sepal width, Petal length, Petal width
y = iris.target # Target: Species
# Convert the target to a regression-friendly format (use one feature for demonstration)
# Here, we predict the Petal length based on other features
X = X[:, :3] # Using Sepal length, Sepal width, Petal length as features
y = X[:, 2] # Target is Petal length
#X = iris.data[:, [0]] # Only Sepal length as feature
#y = iris.data[:, 2] # Petal length as target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a Linear Regression model
model = LinearRegression()
# Train the model on the training data
model.fit(X_train, y_train)
# Make predictions on the test data
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# Print the results
print("Model Coefficients:", model.coef_)
print("Model Intercept:", model.intercept_)
print("Mean Squared Error (MSE):", mse)
print("R-squared Score:", r2)
# Example prediction ,sample_data = [[5.1]]
sample_data = [[5.1, 3.5, 1.4]] # Example input: Sepal length, Sepal width, Petal length
predicted_petal_length = model.predict(sample_data)
print("Predicted Petal Length:", predicted_petal_length[0])