Challenge

Project 2

# Import necessary libraries

import pandas as pd

from sklearn.cluster import KMeans

from sklearn.preprocessing import StandardScaler

import matplotlib.pyplot as plt

# Load the dataset

# Assuming you have a CSV file named 'car_dataset.csv' with the mentioned columns

dataset_path = 'path_to_your_dataset.csv'

df = pd.read_csv(dataset_path)

# Select relevant columns for clustering

columns_for_clustering = ['Mileage', 'Engine_Size', 'Horsepower', 'Price']

# Extract the features for clustering

X = df[columns_for_clustering]

# Standardize the features (important for K-Means)

scaler = StandardScaler()

X_scaled = scaler.fit_transform(X)

# Determine the optimal number of clusters using the Elbow Method

wcss = []

for i in range(1, 11):

kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0)

kmeans.fit(X_scaled)

wcss.append(kmeans.inertia_)

# Plot the Elbow Method to find the optimal number of clusters

plt.plot(range(1, 11), wcss)

plt.title('Elbow Method')

plt.xlabel('Number of clusters')

plt.ylabel('WCSS') # WCSS stands for "Within-Cluster Sum of Squares"

plt.show()

# Based on the elbow method, choose the optimal number of clusters

optimal_clusters = 3 # Adjust based on the visual inspection of the elbow method plot

# Apply K-Means clustering with the optimal number of clusters

kmeans = KMeans(n_clusters=optimal_clusters, init='k-means++', max_iter=300, n_init=10, random_state=0)

df['Cluster'] = kmeans.fit_predict(X_scaled)

# Display the clustered dataset

print(df[['Make', 'Model', 'Year', 'Cluster']])

# Now you can use the clustered data for prediction or further analysis

# For example, you can train a classifier on the clusters and predict the class of a new car.

# Save the clustered dataset to a new CSV file

df.to_csv('clustered_car_dataset.csv', index=False)

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.