# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + id="OJDDh0qwBWNo" colab_type="code" colab={}
import numpy as np

from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler, MinMaxScaler

import pandas as pd

# + id="sl81oeJTBkPh" colab_type="code" colab={}
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]

X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,
                            random_state=0)

X = StandardScaler().fit_transform(X)

# + id="vUCToVO-FWnA" colab_type="code" outputId="79c95ac6-1aad-44ee-c71e-0a685859b82d" colab={"resources": {"http://localhost:8080/nbextensions/google.colab/files.js": {"data": "<KEY> "ok": true, "headers": [["content-type", "application/javascript"]], "status": 200, "status_text": "OK"}}, "base_uri": "https://localhost:8080/", "height": 100}
from google.colab import files

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

# + id="YZGCjGoaEBeH" colab_type="code" colab={}
data = pd.read_csv('./IND115datalabels.csv')

# + [markdown] id="c0kboZWWt4td" colab_type="text"
#

# + id="TiCNy4j6EInJ" colab_type="code" outputId="b9c2d091-7a52-4443-bf96-76b332081a68" colab={"base_uri": "https://localhost:8080/", "height": 208}
#xm=data.values[:,0]
#ym=data.values[:,1]
#timesteps=10

X=data.values[:,[0,1]]

labeltrue=1-data.values[:,2]

m=X.shape[0]

#m,n=xm.shape

xm=MinMaxScaler(feature_range=(-1,1)).fit_transform(X)
#ym=preprocessing.MinMaxScaler(feature_range=(-1,1)).fit_transform(ym.reshape(-1,1))

print(xm.shape)
print(xm[0:10])

# + id="4Fd5lA8fBpqX" colab_type="code" outputId="bfc2ab88-2e5b-41b6-fea4-9033e0813934" colab={"base_uri": "https://localhost:8080/", "height": 298}
# Compute DBSCAN
db = DBSCAN(eps=0.1, min_samples=15).fit(xm)
print(len(db.labels_))
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_

nlabel=len(labels)
for i in range(0,nlabel):
  if(labels[i]==-1):
    labels[i]=1


# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) #- (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)



print('Estimated number of clusters: %d' % n_clusters_)
print('Estimated number of noise points: %d' % n_noise_)
print("Homogeneity: %0.3f" % metrics.homogeneity_score(labeltrue, labels))
print("Completeness: %0.3f" % metrics.completeness_score(labeltrue, labels))
print("V-measure: %0.3f" % metrics.v_measure_score(labeltrue, labels))
print("Adjusted Rand Index: %0.3f"
     % metrics.adjusted_rand_score(labeltrue, labels))
print("Adjusted Mutual Information: %0.3f"
      % metrics.adjusted_mutual_info_score(labeltrue, labels))
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(X, labels))
print("Accuracy score ",metrics.accuracy_score(labeltrue, labels, normalize=True))
print("Precision score ",metrics.precision_score(labeltrue,labels,average=None))
print("Recall score ",metrics.recall_score(labeltrue, labels, average=None))
print("f1 score ",metrics.f1_score(labeltrue, labels, average=None))

# + id="A_drKcIYtctp" colab_type="code" colab={}


# + id="12b_z9UGBqwM" colab_type="code" outputId="e867ebcc-e9d0-4fdf-e056-717394d7cfef" colab={"base_uri": "https://localhost:8080/", "height": 281}
# Plot result
import matplotlib.pyplot as plt

# Black removed and is used for noise instead.
unique_labels = set(labels)
colors = [plt.cm.Spectral(each)
          for each in np.linspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
    if k == -1:
        # Black used for noise.
        col = [0, 0, 0, 1]

    class_member_mask = (labels == k)

    xy = X[class_member_mask & core_samples_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=14)

    xy = X[class_member_mask & ~core_samples_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=6)

plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()

StarcoderdataJupyterScriptsDedupFiltered