KMeans Clustering of CSV Data Set

Viewed 101

I am trying to create a KMeans clustering model based on a csv data set that I have compiled. The data set is organized as such:

              population    longitude   latitude

 Atlanta, GA            
 Austin, TX     
 ...

I tried just plotting the data, which isn't working, if produces a scatter plot where you can't see the axis or the data points, and I can't really tell of the Kmeans algorithim is working.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
import pandas as pd
import csv


data = pd.read_csv("data.csv")

print (data.head())

plt.scatter(x=data['Population'].astype(bytes), y=data['Longitude'].astype(bytes), z=data["Latitude"].astype(bytes))

plt.xlim(0,1000000)

plt.ylim(0,5000)

plt.zlim(0,5000)

plt.xlabel('Population')

plt.ylabel('Longitude')

plt.zlabel('Latitude')

plt.title('KMeans Clustering for Population vs. Latitude and Longitude', fontsize = 10)

plt.show()

x = data.iloc[:,1:3] #selecting features

#Clustering

kmeans = KMeans(3)

kmeans.fit(x)

#Clustering Results

indentified_clusters = kmeans.fit_predict(x)

indentified_clusters

array([1,1,0.0,2])

data_with_clusters = data.copy()

data_with_clusters['Clusters'] = identified_clusters

plt.scatter(data_with_clusters['Population'],data_with_clusters['Longitude'],data_with_clusters['Latitude']c=data_with_clusters['Clusters'],cmap='rainbow')
1 Answers

Try the following :

import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.cluster import KMeans

#2 Importing the mall dataset
data= pd.read_csv("xxx")


print(data.head())

plt.scatter(data['Longitude'],data['Latitude'])
plt.xlim(-180,180)
plt.ylim(-90,90)
plt.show()


x = data.iloc[:,1:3] # 1t for rows and second for columns
x


kmeans = KMeans(3)
kmeans.fit(x)


data_with_clusters = data.copy()
data_with_clusters['Clusters'] = indentified_clusters 

plt.scatter(data_with_clusters['Longitude'],data_with_clusters['Latitude'],c=data_with_clusters['Clusters'],cmap='rainbow')
plt.show()

enter image description here

Related