forked from datitran/spark-tdd-example
/
test_clustering.py
76 lines (62 loc) · 2.86 KB
/
test_clustering.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
62
63
64
65
66
67
68
69
70
71
72
73
74
import os
import sys
import unittest
try:
# Append PySpark to PYTHONPATH / Spark 1.6.1
sys.path.append(os.path.join(os.environ['SPARK_HOME'], "python"))
sys.path.append(os.path.join(os.environ['SPARK_HOME'], "python", "lib", "py4j-0.9-src.zip"))
except KeyError as e:
print("SPARK_HOME is not set", e)
sys.exit(1)
try:
# Import PySpark modules here
from pyspark import SparkContext, SparkConf
from pyspark.mllib.linalg import DenseVector, SparseVector
from pyspark.sql import SQLContext, Row
except ImportError as e:
print("Can not import Spark modules", e)
sys.exit(1)
# Import script modules here
import clustering
class ClusteringTest(unittest.TestCase):
def setUp(self):
"""Create a single node Spark application."""
conf = SparkConf()
conf.set("spark.executor.memory", "1g")
conf.set("spark.cores.max", "1")
conf.set("spark.app.name", "nosetest")
self.sc = SparkContext(conf=conf)
self.mock_df = self.mock_data()
def tearDown(self):
"""Stop the SparkContext."""
self.sc.stop()
def mock_data(self):
"""Mock data to imitate read from database."""
sqlContext = SQLContext(self.sc)
mock_data_rdd = self.sc.parallelize([("A", 1, 1), ("B", 1, 0), ("C", 0, 2), ("D", 2, 4), ("E", 3, 5) ])
schema = ["id", "x", "y"]
mock_data_df = sqlContext.createDataFrame(mock_data_rdd, schema)
return mock_data_df
def test_count(self):
"""Check if mock data has five rows."""
self.assertEqual(len(self.mock_df.collect()), 5)
def test_convert_df(self):
"""Check if dataframe has the form (id, DenseVector)."""
input_df = clustering.convert_df(self.sc, self.mock_df)
self.assertEqual(input_df.dtypes, [('id', 'string'), ('features', 'vector')])
def test_rescale_df_first_entry(self):
"""Check if rescaling works for the first entry of the first row."""
input_df = clustering.convert_df(self.sc, self.mock_df)
scaled_df = clustering.rescale_df(input_df)
self.assertAlmostEqual(scaled_df.map(lambda x: x.features_scaled).take(1)[0].toArray()[0], 0.8770580193070292)
def test_rescale_df_second_entry(self):
"""Check if rescaling works for the second entry of the first row."""
input_df = clustering.convert_df(self.sc, self.mock_df)
scaled_df = clustering.rescale_df(input_df)
self.assertAlmostEqual(scaled_df.map(lambda x: x.features_scaled).take(1)[0].toArray()[1], 0.48224282217041214)
def test_assign_cluster(self):
"""Check if rows are labeled are as expected."""
input_df = clustering.convert_df(self.sc, self.mock_df)
scaled_df = clustering.rescale_df(input_df)
label_df = clustering.assign_cluster(scaled_df)
self.assertEqual(label_df.map(lambda x: x.label).collect(), [0, 0, 0, 1, 1])