<jupyter_start><jupyter_text>**1. K-Means**<jupyter_code>#Import Libraries
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
np.random.seed()
X, y = make_blobs(n_samples = 5000, centers = [[4,4], [-2,1], [2,-3], [1,1]], cluster_std = 0.9)
plt.scatter(X[:,0], X[:,1], marker = '.')
!wget -o Cust_Segmentation https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/Cust_Segmentation.csv
import pandas as pd
df = pd.read_csv("Cust_Segmentation.csv")
df.head()
df_frop = df.drop('Address', axis = 1)
df_frop.head()
#Normalisasi data

from sklearn.preprocessing import StandardScaler
X = df_frop.values[:,1:]
X = np.nan_to_num(X)
Clust_dataSet = StandardScaler().fit_transform(X)
Clust_dataSet
clusterNum = 3
k_means = KMeans (init = "k-means++", n_clusters = clusterNum, n_init = 12)
k_means.fit(X)
labels = k_means.labels_
print(labels)
df_frop["Clustering"] = labels
df_frop.head()
df_frop.groupby('Clustering').mean()<jupyter_output><empty_output><jupyter_text>lihat distribusi berdasarkan umum dan pendapatan<jupyter_code>area = np.pi * (X[:, 1])**2
plt.scatter(X[:,0], X[:,3], s=area, c=labels.astype(np.float), alpha=0.5)
plt.xlabel('Age', fontsize = 18)
plt.ylabel('Income', fontsize=18)
plt.show()<jupyter_output>/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations<jupyter_text>**2. Hierarchical Clustering**<jupyter_code>!wget -O cars_clus.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cars_clus.csv<jupyter_output>--2022-03-30 01:28:23--  https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cars_clus.csv
Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 172.16.58.3
Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)|172.16.58.3|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17774 (17K) [text/csv]
Saving to: ‘cars_clus.csv’

cars_clus.csv       100%[===================>]  17.36K  --.-KB/s    in 0s      

2022-03-30 01:28:24 (158 MB/s) - ‘cars_clus.csv’ saved [17774/17774]<jupyter_text><jupyter_code>namafile = 'cars_clus.csv'

#baca dataframe
dataHC = pd.read_csv(namafile)
print("Bantak baris dan kolom: ", dataHC.shape)
dataHC.head()
print("Banyaknya data sebelum dibersihkan: ", dataHC.size)
dataHC[['sales','resale','type','price','engine_s','horsepow','wheelbas','width','length','curb_wgt','fuel_cap','mpg','lnsales']] = dataHC[['sales','resale','type','price','engine_s','horsepow','wheelbas','width','length','curb_wgt','fuel_cap','mpg','lnsales']].apply(pd.to_numeric, errors='coerce')
dataHC = dataHC.dropna()
dataHC = dataHC.reset_index(drop=True)
print("Banyaknya data setelah dibersihkan: ", dataHC.size)

fitur = dataHC[['engine_s', 'width', 'length', 'fuel_cap', 'mpg']]
from sklearn.preprocessing import MinMaxScaler
x = fitur.values
min_max_scaler = MinMaxScaler()
fitur_minmax = min_max_scaler.fit_transform(x)
fitur_minmax[0:5]
import scipy
leng = fitur_minmax.shape[0]
D = scipy.zeros([leng,leng])
for i in range(leng):
  for j in range(leng):
    D[i,j] = scipy.spatial.distance.euclidean(fitur_minmax[i], fitur_minmax[j])
import pylab
import scipy.cluster.hierarchy as sch

Z = sch.linkage(D, 'complete')
from scipy.cluster.hierarchy import fcluster
max_d = 3
clusters = fcluster(Z, max_d, criterion = 'distance')
clusters
from scipy.cluster.hierarchy import fcluster
k = 3
clusters = fcluster(Z, k, criterion = 'maxclust')
clusters
gambar = pylab.figure(figsize=(15, 30))
def llf(id):
  return '[%s %s %s]' % (dataHC['manufact'][id], dataHC['model'][id], int(float(dataHC['type'][id])))

gambar_dendro = sch.dendrogram(Z, leaf_label_func=llf, leaf_rotation=0, leaf_font_size=10, orientation = 'right')<jupyter_output><empty_output><jupyter_text>**3. DBSCAN**<jupyter_code>#belom gez<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16719817767653758, 'fraction_numerical': 0.03599088838268793, 'mean_word_length': 6.392255892255892, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 20, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '611595', 'license': 'MIT', 'n_tokens_mistral': 1855, 'n_tokens_neox': 1722, 'n_words': 310, 'path': 'pertemuan11_metdat/Clustering_metdat.ipynb', 'repo_name': 'gilangAS20/metdat-science', 'size': '4396'}