# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series
import seaborn as sns
#
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

# # Create a data set in 2 dimensions using make_blobs
#
# The function make_blobs stores the data in x and the cluster each point belongs to in y
#
(x,y)= make_blobs (
n_samples =200, n_features=2,centers=5,cluster_std=0.5,
shuffle=True,random_state=0
)
plt.scatter(
x[:,0],x[:,1],
c='white', edgecolor='black',marker='o', s=50)
plt.show()

# Calculate centroids of blobs; remember that the array y contains cluster number
n = len(y)
n_blobs=5
n_points_blob = 40.
blob_mean = np.zeros( ( n_blobs,2) )
#
# Loop to sum up x and y coordinates of each point in blob
for i in range (0,n):
blob=y[i] # given blob index (0,1,2,3,4)
blob_mean [blob,0] = blob_mean [blob,0] + x[i,0]
blob_mean [blob,1] = blob_mean [blob,1] + x[i,1]
# Loop to divide by number of points in blob and print out
for k in range (0,n_blobs) :
blob_mean [k,:] = blob_mean [k,:] / n_points_blob
print (f"Blob {k+1} has centroid: ( { blob_mean [k,0] }, { blob_mean [k,1] } ) " )

```
Blob 1 has centroid: ( 0.9148227503116141, 4.280336857833884 )
Blob 2 has centroid: ( 2.054873265582555, 1.1110568334393494 )
Blob 3 has centroid: ( -1.543516197703645, 2.8134551104965806 )
Blob 4 has centroid: ( -1.3675452152752192, 7.891534958387625 )
Blob 5 has centroid: ( 9.210599887923255, -2.473923314565855 )
```

# Create KMeans model and fit data in array x which is in the correct shape: 200 by 2
km = KMeans( n_clusters = 5, init = 'random', random_state = 0)
km.fit(x)
print ("Final centroids are", km.cluster_centers_)

```
Final centroids are [[ 2.05487327 1.11105683]
[-1.5435162 2.81345511]
[-1.36754522 7.89153496]
[ 0.91482275 4.28033686]
[ 9.21059989 -2.47392331]]
```

# Plot clusters using colors and compare visually with blob plot above
plt.scatter(
x[:,0],x[:,1],c=km.labels_,cmap='rainbow'
)
plt.scatter(
km.cluster_centers_[:,0],km.cluster_centers_[:,1],
marker='*',c='black',label='centroids'
)
plt.legend(scatterpoints=1)
plt.grid()
plt.show()
plt.scatter(
x[:,0],x[:,1],
c='white', edgecolor='black',marker='o', s=50)
plt.show()

# Print out final clusters centroids and print out actual centroids to compare
#
print (" KMeans Centroids ", " Original Centroids ")
print( )
# Note that Kmeans cluster 3 corresponds to our cluster 5 and vice versa

```
KMeans Centroids Original Centroids
```

# 1 iteration
centroids = np.array( [ [-3,-2], [-2,12], [3,8], [12,0], [2,12] ])
print ()
print ("******************************************")
print ("Results for 1st iteration of KMeans")

```
******************************************
Results for 1st iteration of KMeans
```

# 2 iterations
centroids = np.array( [ [-3,-2], [-2,12], [3,8], [12,0], [2,12] ])
print ()
print ("******************************************")
print ("Results for 2nd iteration of KMeans")

```
******************************************
Results for 2nd iteration of KMeans
```

# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame, Series
import seaborn as sns
# Import models
from sklearn.cluster import KMeans

# Create dataframe from file insurance.csv
df = pd.read_csv('insurance.csv')
df.head()

ageint64

sexobject

0

19

female

1

18

male

2

28

male

3

33

male

4

32

male

#Create a new dataframe which only has the two features (age and bmi)and the charges
#
df_mod = DataFrame(df, columns = ['age','bmi','charges'])
df_mod.head()

ageint64

bmifloat64

0

19

27.9

1

18

33.77

2

28

33

3

33

22.705

4

32

28.88

# Determine how many data instances there are
# so 1338 data instances
my_array = df_mod.values
print(type(my_array))
print(my_array)
print(f"{len(my_array)} data instances")

```
<class 'numpy.ndarray'>
[[1.90000000e+01 2.79000000e+01 1.68849240e+04]
[1.80000000e+01 3.37700000e+01 1.72555230e+03]
[2.80000000e+01 3.30000000e+01 4.44946200e+03]
...
[1.80000000e+01 3.68500000e+01 1.62983350e+03]
[2.10000000e+01 2.58000000e+01 2.00794500e+03]
[6.10000000e+01 2.90700000e+01 2.91413603e+04]]
1338 data instances
```

# Find the maximum & minimum value of the charges

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Print out the data instance where the max occurs

# Print out all data instances where charges are >60,000

# Print out all data instances where bmi > 35 and charges > 50,000

# Delete all data instances where the charges are more than $60,000
# Print out all data instances where charges are >60000 to check

# Scale costs between $0 and $100; round costs to 2 decimal places (for cents)
# print out the first few entries to check

# Add column to dataframe with scaled charges and remove column with full charges

# Create 2D array and use KMeans with 4 clusters

# Print out the labels
#
# add column to dataframe giving cluster labels

# Set white background grid for Seaborn plots
sns.set_style ( "whitegrid")

# Create scatterplot of charges vs bmi with cluster indiciated by hue using Seaborn's relplot

# Create scatterplot of charges vs age with cluster indiciated by hue using Seaborn's relplot