# Import necessary libraries
import pandas as pd
import numpy as np
import re
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
# Assuming X and y are provided, or we can create them
# For the purpose of this code, let's assume we're starting with a DataFrame called df
# Let's suppose df is the dataset DataFrame
# df = pd.read_csv('dataset.csv') # This line is commented out because we don't have the actual file
# For this example, let's assume df is provided
# Let's begin preprocessing
def preprocess_data(df):
# Copy the DataFrame to avoid modifying the original data
df = df.copy()
# Handle missing values (if any)
# For simplicity, we'll fill numerical NaNs with the median and categorical NaNs with the mode
num_cols = ['model_year', 'milage']
cat_cols = ['brand', 'fuel_type', 'transmission', 'ext_col', 'int_col', 'accident']
text_cols = ['model', 'engine']
# Extract features from the 'engine' column
# Example entries: "172.0HP 1.6L 4 Cylinder Engine Gasoline Fuel", "3.0L", "420.0HP 5.0L 8 Cylinder Engine Gasoline Fuel"
# We'll extract horsepower (HP) and engine size (Litre)
def extract_hp(text):
match = re.search(r'(\d+\.?\d*)HP', text)
return float(match.group(1)) if match else np.nan
def extract_engine_size(text):
match = re.search(r'(\d+\.?\d*)L', text)
return float(match.group(1)) if match else np.nan
df['horsepower'] = df['engine'].apply(extract_hp)
df['engine_size'] = df['engine'].apply(extract_engine_size)
# Since we can't use NLTK, we'll not perform further text processing on 'model'
# Drop the original 'engine' and 'model' columns
df = df.drop(columns=['engine', 'model'])
# Now, update numerical and categorical columns
num_cols.extend(['horsepower', 'engine_size'])
# Impute missing values
num_imputer = SimpleImputer(strategy='median')
cat_imputer = SimpleImputer(strategy='most_frequent')
df[num_cols] = num_imputer.fit_transform(df[num_cols])
df[cat_cols] = cat_imputer.fit_transform(df[cat_cols])
# One-Hot Encode categorical variables
df = pd.get_dummies(df, columns=cat_cols, drop_first=True)
# Feature Scaling
scaler = StandardScaler()
df[num_cols] = scaler.fit_transform(df[num_cols])
# Separate features and target variable
X = df.drop('price', axis=1)
y = df['price']
return X, y
# Assuming df is our DataFrame
# X, y = preprocess_data(df)
# For the purpose of this example, let's generate dummy data
def generate_dummy_data():
np.random.seed(0)
num_samples = 1000
df = pd.DataFrame({
'price': np.random.uniform(10000, 50000, num_samples),
'brand': np.random.choice([f'Brand_{i}' for i in range(1, 58)], num_samples),
'model_year': np.random.randint(1980, 2023, num_samples),
'milage': np.random.randint(0, 200000, num_samples),
'fuel_type': np.random.choice(['Gasoline', 'Diesel', 'Electric', 'Hybrid'], num_samples),
'transmission': np.random.choice([f'Transmission_{i}' for i in range(1, 53)], num_samples),
'ext_col': np.random.choice([f'Color_{i}' for i in range(1, 320)], num_samples),
'int_col': np.random.choice([f'Color_{i}' for i in range(1, 157)], num_samples),
'accident': np.random.choice(['No Accident', 'Minor Accident', 'Major Accident'], num_samples),
'model': np.random.choice(['Cooper S Base', 'G90 5.0 Ultimate', 'Silverado 2500 LT', 'AMG GLC 63 Base 4MATIC'], num_samples),
'engine': np.random.choice(['172.0HP 1.6L 4 Cylinder Engine Gasoline Fuel', '3.0L', '420.0HP 5.0L 8 Cylinder Engine Gasoline Fuel'], num_samples)
})
return df
# Generate dummy data
df = generate_dummy_data()
# Preprocess the data
X, y = preprocess_data(df)
# Now, let's split the data (if not already split in test_model)
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Since we need to pass X and y to test_model, we proceed to model training
# Define the model
model = GradientBoostingRegressor(random_state=42)
# Train the model
model.fit(X, y)
# Evaluate the model
# Assuming test_model is a function that takes X and y
# The test_model function might handle the train-test split internally
# For the purpose of this example, we'll define a dummy test_model function
def test_model(X, y):
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error
# Perform cross-validation
scores = cross_val_score(model, X, y, cv=5, scoring='neg_mean_squared_error')
rmse_scores = np.sqrt(-scores)
print(f"Cross-validated RMSE: {rmse_scores.mean():.2f} (+/- {rmse_scores.std() * 2:.2f})")
# Call the test_model function
test_model(X, y)