Step 1: Import Libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Step 2: Load Dataset
df = pd.read_csv(r"E:\Kiran\DSI\ML and NN\Lab\Program 2\car1.csv")
# Display First Five Records
print("First 5 Records")
print(df.head())
# Step 3: Data Preprocessing
# Replace '?' with NaN
df.replace('?', np.nan, inplace=True)
# Convert horsepower to numeric
df['horsepower'] = pd.to_numeric(df['horsepower'], errors='coerce')
# Fill missing values in horsepower with mean
df['horsepower'] = df['horsepower'].fillna(df['horsepower'].mean())
# Check missing values before dropping car name
print("\nMissing Values")
print(df.isnull().sum())
# Drop car name column
df.drop('car name', axis=1, inplace=True)
# Step 4: Define Features and Target
X = df.drop('mpg', axis=1)
y = df['mpg']
# Step 5: Split 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
)
# Step 6: Train the Linear Regression Model
model = LinearRegression()
model.fit(X_train, y_train)
# Step 7: Predict MPG for Test Data
y_pred = model.predict(X_test)
# Step 8: Display Actual vs Predicted Values
results = pd.DataFrame({
'Actual MPG': y_test.values,
'Predicted MPG': np.round(y_pred, 2)
})
print("\nActual vs Predicted MPG (First 5 Samples)")
print(results.head(5))
# Step 9: Evaluate the Model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("\nModel Evaluation")
print("Mean Squared Error (MSE):", round(mse, 2))
print("R² Score:", round(r2, 4))⚠️Content was pasted as plain text and auto-formatted as a code block. Use the Code Block button in the editor for proper formatting.