-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
61 lines (49 loc) · 1.94 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#
# Utility functions for Spark Cluster Analysis Hands-On
#
#
from itertools import cycle, islice
from math import sqrt
from numpy import array
from pandas.tools.plotting import parallel_coordinates
from pyspark.ml.clustering import KMeans as KM
from pyspark.mllib.linalg import DenseVector
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def computeCost(featuresAndPrediction, model):
allClusterCenters = [DenseVector(c) for c in model.clusterCenters()]
arrayCollection = featuresAndPrediction.rdd.map(array)
def error(point, predictedCluster):
center = allClusterCenters[predictedCluster]
z = point - center
return sqrt((z*z).sum())
return arrayCollection.map(lambda row: error(row[0], row[1])).reduce(lambda x, y: x + y)
def elbow(elbowset, clusters):
wsseList = []
for k in clusters:
print("Training for cluster size {} ".format(k))
kmeans = KM(k = k, seed = 1)
model = kmeans.fit(elbowset)
transformed = model.transform(elbowset)
featuresAndPrediction = transformed.select("features", "prediction")
W = computeCost(featuresAndPrediction, model)
print("......................WSSE = {} ".format(W))
wsseList.append(W)
return wsseList
def elbow_plot(wsseList, clusters):
wsseDF = pd.DataFrame({'WSSE' : wsseList, 'k' : clusters })
wsseDF.plot(y='WSSE', x='k', figsize=(15,10), grid=True, marker='o')
def pd_centers(featuresUsed, centers):
colNames = list(featuresUsed)
colNames.append('prediction')
# Zip with a column called 'prediction' (index)
Z = [np.append(A, index) for index, A in enumerate(centers)]
# Convert to pandas for plotting
P = pd.DataFrame(Z, columns=colNames)
P['prediction'] = P['prediction'].astype(int)
return P
def parallel_plot(data, P):
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(P)))
plt.figure(figsize=(15,8)).gca().axes.set_ylim([-3,+3])
parallel_coordinates(data, 'prediction', color = my_colors, marker='o')