In [1]:
!pip install matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
Requirement already satisfied: matplotlib in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (3.10.5)
Requirement already satisfied: contourpy>=1.0.1 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (1.3.3)
Requirement already satisfied: cycler>=0.10 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (4.59.1)
Requirement already satisfied: kiwisolver>=1.3.1 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (1.4.9)
Requirement already satisfied: numpy>=1.23 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (2.3.2)
Requirement already satisfied: packaging>=20.0 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (25.0)
Requirement already satisfied: pillow>=8 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (11.3.0)
Requirement already satisfied: pyparsing>=2.3.1 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (3.2.3)
Requirement already satisfied: python-dateutil>=2.7 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from matplotlib) (2.9.0.post0)
Requirement already satisfied: six>=1.5 in /opt/anaconda3/envs/NNM24AM045/lib/python3.13/site-packages (from python-dateutil>=2.7->matplotlib) (1.17.0)
In [2]:
# 1. Load dataset
df = pd.read_csv("car_dataset.csv")
print("Original DataFrame with Missing Values:\n", df.head())
Original DataFrame with Missing Values:
     Brand    Model  Year   Mileage    Price
0    Ford  Corolla  2015   35000.0  3506420
1     NaN   Seltos  2021   20000.0  3665884
2  Nissan     City  2012   30000.0  3669720
3     Kia   Fiesta  2008   65000.0   816771
4   Honda      NaN  2010  100000.0  3228009
In [3]:
# 2. Select relevant columns (you may adjust these)
df = df[['Brand', 'Model', 'Year', 'Mileage', 'Price']]
In [4]:
#3. Handle missing values
cat_imputer = SimpleImputer(strategy='most_frequent')
df[['Brand', 'Model']] = cat_imputer.fit_transform(df[['Brand', 'Model']])

num_imputer = SimpleImputer(strategy='mean')
df[['Mileage']] = num_imputer.fit_transform(df[['Mileage']])
print("after filling most frequent values:\n", df)
after filling most frequent values:
        Brand    Model  Year   Mileage    Price
0       Ford  Corolla  2015   35000.0  3506420
1    Hyundai   Seltos  2021   20000.0  3665884
2     Nissan     City  2012   30000.0  3669720
3        Kia   Fiesta  2008   65000.0   816771
4      Honda    Yaris  2010  100000.0  3228009
..       ...      ...   ...       ...      ...
95  Mercedes     City  2005   20000.0  3009532
96  Mercedes       A4  2012   90000.0  3965060
97      Ford     Polo  2016   65000.0  3762565
98    Toyota     Polo  2016   55000.0  1637682
99     Honda   Altima  2009   20000.0  1376871

[100 rows x 5 columns]
In [5]:
df.isnull().sum()
Out[5]:
Brand      0
Model      0
Year       0
Mileage    0
Price      0
dtype: int64
In [6]:
# 4. Encode categorical variables using Label Encoding
label_enc = LabelEncoder()
df['Brand'] = label_enc.fit_transform(df['Brand'])
df['Model'] = label_enc.fit_transform(df['Model'])

print("\nDataFrame after Label Encoding:\n", df.head())
DataFrame after Label Encoding:
    Brand  Model  Year   Mileage    Price
0      2      5  2015   35000.0  3506420
1      4      9  2021   20000.0  3665884
2      7      3  2012   30000.0  3669720
3      5      7  2008   65000.0   816771
4      3     11  2010  100000.0  3228009
In [7]:
# 5. Split into features (X) and target (y)
X = df.drop('Price', axis = 1)
y = df['Price']
In [8]:
# 6. Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=42)
In [9]:
X_train
Out[9]:
Brand Model Year Mileage
11 4 10 2022 90000.000000
47 6 7 2007 55549.450549
85 4 9 2016 95000.000000
28 5 5 2016 35000.000000
93 5 9 2015 45000.000000
... ... ... ... ...
60 2 3 2018 80000.000000
71 1 5 2020 55000.000000
14 1 9 2020 85000.000000
92 7 11 2019 95000.000000
51 7 11 2018 20000.000000

70 rows × 4 columns

In [10]:
X_test
Out[10]:
Brand Model Year Mileage
83 8 8 2020 70000.000000
53 9 7 2005 100000.000000
70 7 0 2015 95000.000000
45 0 5 2018 35000.000000
44 1 11 2016 80000.000000
39 2 11 2020 70000.000000
22 4 3 2012 10000.000000
80 9 3 2005 60000.000000
10 8 11 2018 65000.000000
0 2 5 2015 35000.000000
18 2 8 2008 60000.000000
30 5 6 2010 15000.000000
73 9 11 2014 60000.000000
33 4 3 2012 95000.000000
90 3 4 2014 50000.000000
4 3 11 2010 100000.000000
76 7 0 2017 55549.450549
77 8 6 2011 40000.000000
12 9 11 2006 50000.000000
31 3 10 2010 60000.000000
55 4 11 2007 95000.000000
88 9 2 2006 85000.000000
26 1 1 2005 55549.450549
42 8 7 2021 60000.000000
69 4 2 2013 55549.450549
15 1 8 2013 95000.000000
40 3 11 2008 100000.000000
96 6 0 2012 90000.000000
9 0 4 2022 80000.000000
72 8 7 2011 25000.000000
In [11]:
y_train
Out[11]:
11    1169474
47    2068831
85     825830
28     934736
93     817313
       ...   
60     497775
71    3338370
14     370640
92    1105497
51     305486
Name: Price, Length: 70, dtype: int64
In [12]:
y_test
Out[12]:
83    2605276
53    1173332
70     833636
45    3921581
44    3504891
39    2592156
22     975510
80     513945
10    1462928
0     3506420
18    1774271
30    2307635
73     374460
33    3564908
90    2752401
4     3228009
76    3976817
77    2076203
12    2483151
31    1526607
55    2617336
88    2436233
26    3631869
42    2303019
69    1189465
15     496582
40     766152
96    3965060
9     3432130
72     338102
Name: Price, dtype: int64
In [13]:
# 7. Choose a simple regression algorithm
model = LinearRegression()
In [14]:
# 8. Train the model
model.fit(X_train, y_train)
Out[14]:
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
fit_intercept  True
copy_X  True
tol  1e-06
n_jobs  None
positive  False
In [15]:
#9. Predict on test data
y_pred = model.predict(X_test)
In [16]:
#10. Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print("\nMean Squared Error:", mse)
print("R² Score:", r2)
print("Predicted Prices:", y_pred)
Mean Squared Error: 1310429300560.4426
R² Score: 0.0485831396066152
Predicted Prices: [1936342.85082553 1416911.35569305 2064340.04235218 2443835.60194065
 1814914.21489114 1946350.18013101 2446714.35823572 1848731.25078733
 1778565.1243111  2322047.77896295 1861693.35393571 2202746.80191359
 1688560.68237921 1927458.62827893 2228317.56476024 1499362.59092441
 2353063.13461213 1998583.76125237 1558753.63931746 1790584.29291802
 1433220.14305107 1766737.03569607 2170458.66394874 2068159.81865765
 2239185.79084721 1792293.06170612 1451638.60280731 2048399.43528088
 2311249.55021169 2043351.0609955 ]
In [17]:
#11. Visualization: Actual vs Predicted
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, color='blue', alpha=0.7)
plt.plot([y.min(), y.max()], [y.min(), y.max()], 'r--', label='Ideal')
plt.xlabel("Actual Price")
plt.ylabel("Predicted Price")
plt.title("Actual vs Predicted Car Prices")
plt.legend()
plt.show()
No description has been provided for this image