Learn practical skills, build real-world projects, and advance your career
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
import pandas as pd
X=pd.read_csv("datasets/cars.csv")
x1 = X['dist'].values
x2 = X['speed'].values
X = np.array(list(zip(x1, x2))).reshape(len(x1), 2)
plt.plot()
plt.xlim([0, 100])
plt.ylim([0, 50])
plt.title('Dataset')
plt.scatter(x1, x2)
plt.show()
#code for EM
gmm = GaussianMixture(n_components=3)
gmm.fit(X)
em_predictions = gmm.predict(X)
print("\nEM predictions")
print(em_predictions)
print("mean:\n",gmm.means_)
print('\n')
print("Covariances\n",gmm.covariances_)
print(X)
plt.title('Exceptation Maximum')
plt.scatter(X[:,0], X[:,1],c=em_predictions,s=50)
plt.show()
#code for Kmeans
import matplotlib.pyplot as plt1
kmeans = KMeans(n_clusters=3) 
kmeans.fit(X)
print(kmeans.cluster_centers_)
print(kmeans.labels_)
plt.title('KMEANS')
plt1.scatter(X[:,0], X[:,1], c=kmeans.labels_, cmap='rainbow')
plt1.scatter(kmeans.cluster_centers_[:,0] ,kmeans.cluster_centers_[:,1], color='black')
Notebook Image
EM predictions [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 2 1 1 0 1 1 1 1 0 1 0 2 2 1 0 0 1 0 0 0 0 0 0 0 2 2 2 2] mean: [[53.23068163 18.4405432 ] [25.06480597 12.31793428] [84.8576843 20.42693312]] Covariances [[[125.60339622 20.50678536] [ 20.50678536 10.49291194]] [[125.97999865 37.74072941] [ 37.74072941 17.46824676]] [[288.74759551 41.85197749] [ 41.85197749 16.62841499]]] [[ 2 4] [ 10 4] [ 4 7] [ 22 7] [ 16 8] [ 10 9] [ 18 10] [ 26 10] [ 34 10] [ 17 11] [ 28 11] [ 14 12] [ 20 12] [ 24 12] [ 28 12] [ 26 13] [ 34 13] [ 34 13] [ 46 13] [ 26 14] [ 36 14] [ 60 14] [ 80 14] [ 20 15] [ 26 15] [ 54 15] [ 32 16] [ 40 16] [ 32 17] [ 40 17] [ 50 17] [ 42 18] [ 56 18] [ 76 18] [ 84 18] [ 36 19] [ 46 19] [ 68 19] [ 32 20] [ 48 20] [ 52 20] [ 56 20] [ 64 20] [ 66 22] [ 54 23] [ 70 24] [ 92 24] [ 93 24] [120 24] [ 85 25]]
Notebook Image
[[90. 21. ] [23.34615385 11.84615385] [53.64705882 18.52941176]] [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 2 0 1 1 2 1 2 1 2 2 2 2 0 0 1 2 2 1 2 2 2 2 2 2 2 0 0 0 0]
<matplotlib.collections.PathCollection at 0x3a8ff30>
Notebook Image