forked from runawayhorse001/learning-apache-spark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fnn.Rmd
368 lines (323 loc) · 13.9 KB
/
fnn.Rmd
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
---
title: "Feedforward Neural Network"
author: "Wenqiang Feng"
date: "2/23/2017"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### Remark:
- You can download the complete [ipython notebook](./ipynb/Feedforward neural network.ipynb) for this tutorial session.
### 1. Set up spark context and SparkSession
```{python eval=FALSE}
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark Feedforward neural network example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
```
### 2. Load dataset
```{python eval=FALSE}
from pyspark.ml.classification import MultilayerPerceptronClassifier
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
# Load training data
df = spark.read.format('com.databricks.spark.csv').\
options(header='true', \
inferschema='true').load("./data/WineData.csv",header=True);
```
- preview dataset
```{python eval=FALSE}
df.show(5)
```
```{python eval=FALSE}
# output
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
|fixed acidity|volatile acidity|citric acid|residual sugar|chlorides|free sulfur dioxide|total sulfur dioxide|density| pH|sulphates|alcohol|quality|
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
| 7.4| 0.7| 0.0| 1.9| 0.076| 11.0| 34.0| 0.9978|3.51| 0.56| 9.4| 5|
| 7.8| 0.88| 0.0| 2.6| 0.098| 25.0| 67.0| 0.9968| 3.2| 0.68| 9.8| 5|
| 7.8| 0.76| 0.04| 2.3| 0.092| 15.0| 54.0| 0.997|3.26| 0.65| 9.8| 5|
| 11.2| 0.28| 0.56| 1.9| 0.075| 17.0| 60.0| 0.998|3.16| 0.58| 9.8| 6|
| 7.4| 0.7| 0.0| 1.9| 0.076| 11.0| 34.0| 0.9978|3.51| 0.56| 9.4| 5|
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
only showing top 5 rows
```
- check schema
```{python eval=FALSE}
df.printSchema()
```
```{python eval=FALSE}
#output
root
|-- fixed acidity: double (nullable = true)
|-- volatile acidity: double (nullable = true)
|-- citric acid: double (nullable = true)
|-- residual sugar: double (nullable = true)
|-- chlorides: double (nullable = true)
|-- free sulfur dioxide: double (nullable = true)
|-- total sulfur dioxide: double (nullable = true)
|-- density: double (nullable = true)
|-- pH: double (nullable = true)
|-- sulphates: double (nullable = true)
|-- alcohol: double (nullable = true)
|-- quality: integer (nullable = true)
```
### 3. change categorical variable size
- define function
```{python eval=FALSE}
# Convert to float format
def string_to_float(x):
return float(x)
#
def condition(r):
if (0<= r <= 4):
label = "low"
elif(4< r <= 6):
label = "medium"
else:
label = "high"
return label
```
```{python eval=FALSE}
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType, DoubleType
string_to_float_udf = udf(string_to_float, DoubleType())
quality_udf = udf(lambda x: condition(x), StringType())
```
- change categorical variable size
```{python eval=FALSE}
#df= df.withColumn("quality", string_to_float_udf("quality")).withColumn("Cquality", quality_udf("quality"))
df= df.withColumn("quality", quality_udf("quality"))
```
- check schema
```{python eval=FALSE}
df.printSchema()
```
```{python eval=FALSE}
#ouput
root
|-- fixed acidity: double (nullable = true)
|-- volatile acidity: double (nullable = true)
|-- citric acid: double (nullable = true)
|-- residual sugar: double (nullable = true)
|-- chlorides: double (nullable = true)
|-- free sulfur dioxide: double (nullable = true)
|-- total sulfur dioxide: double (nullable = true)
|-- density: double (nullable = true)
|-- pH: double (nullable = true)
|-- sulphates: double (nullable = true)
|-- alcohol: double (nullable = true)
|-- quality: string (nullable = true)
```
- preview dataset
```{python eval=FALSE}
df.show()
```
```{python eval=FALSE}
#ouput
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
|fixed acidity|volatile acidity|citric acid|residual sugar|chlorides|free sulfur dioxide|total sulfur dioxide|density| pH|sulphates|alcohol|quality|
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
| 7.4| 0.7| 0.0| 1.9| 0.076| 11.0| 34.0| 0.9978|3.51| 0.56| 9.4| medium|
| 7.8| 0.88| 0.0| 2.6| 0.098| 25.0| 67.0| 0.9968| 3.2| 0.68| 9.8| medium|
| 7.8| 0.76| 0.04| 2.3| 0.092| 15.0| 54.0| 0.997|3.26| 0.65| 9.8| medium|
| 11.2| 0.28| 0.56| 1.9| 0.075| 17.0| 60.0| 0.998|3.16| 0.58| 9.8| medium|
| 7.4| 0.7| 0.0| 1.9| 0.076| 11.0| 34.0| 0.9978|3.51| 0.56| 9.4| medium|
| 7.4| 0.66| 0.0| 1.8| 0.075| 13.0| 40.0| 0.9978|3.51| 0.56| 9.4| medium|
| 7.9| 0.6| 0.06| 1.6| 0.069| 15.0| 59.0| 0.9964| 3.3| 0.46| 9.4| medium|
| 7.3| 0.65| 0.0| 1.2| 0.065| 15.0| 21.0| 0.9946|3.39| 0.47| 10.0| high|
| 7.8| 0.58| 0.02| 2.0| 0.073| 9.0| 18.0| 0.9968|3.36| 0.57| 9.5| high|
| 7.5| 0.5| 0.36| 6.1| 0.071| 17.0| 102.0| 0.9978|3.35| 0.8| 10.5| medium|
| 6.7| 0.58| 0.08| 1.8| 0.097| 15.0| 65.0| 0.9959|3.28| 0.54| 9.2| medium|
| 7.5| 0.5| 0.36| 6.1| 0.071| 17.0| 102.0| 0.9978|3.35| 0.8| 10.5| medium|
| 5.6| 0.615| 0.0| 1.6| 0.089| 16.0| 59.0| 0.9943|3.58| 0.52| 9.9| medium|
| 7.8| 0.61| 0.29| 1.6| 0.114| 9.0| 29.0| 0.9974|3.26| 1.56| 9.1| medium|
| 8.9| 0.62| 0.18| 3.8| 0.176| 52.0| 145.0| 0.9986|3.16| 0.88| 9.2| medium|
| 8.9| 0.62| 0.19| 3.9| 0.17| 51.0| 148.0| 0.9986|3.17| 0.93| 9.2| medium|
| 8.5| 0.28| 0.56| 1.8| 0.092| 35.0| 103.0| 0.9969| 3.3| 0.75| 10.5| high|
| 8.1| 0.56| 0.28| 1.7| 0.368| 16.0| 56.0| 0.9968|3.11| 1.28| 9.3| medium|
| 7.4| 0.59| 0.08| 4.4| 0.086| 6.0| 29.0| 0.9974|3.38| 0.5| 9.0| low|
| 7.9| 0.32| 0.51| 1.8| 0.341| 17.0| 56.0| 0.9969|3.04| 1.08| 9.2| medium|
+-------------+----------------+-----------+--------------+---------+-------------------+--------------------+-------+----+---------+-------+-------+
only showing top 20 rows
```
### 4. Convert the data to dense vector
```{python eval=FALSE}
# convert the data to dense vector
def transData(data):
return data.rdd.map(lambda r: [r[-1], Vectors.dense(r[:-1])]).toDF(['label','features'])
```
```{python eval=FALSE}
from pyspark.sql import Row
from pyspark.ml.linalg import Vectors
data= transData(df)
data.show()
```
```{python eval=FALSE}
#output
+------+--------------------+
| label| features|
+------+--------------------+
|medium|[7.4,0.7,0.0,1.9,...|
|medium|[7.8,0.88,0.0,2.6...|
|medium|[7.8,0.76,0.04,2....|
|medium|[11.2,0.28,0.56,1...|
|medium|[7.4,0.7,0.0,1.9,...|
|medium|[7.4,0.66,0.0,1.8...|
|medium|[7.9,0.6,0.06,1.6...|
| high|[7.3,0.65,0.0,1.2...|
| high|[7.8,0.58,0.02,2....|
|medium|[7.5,0.5,0.36,6.1...|
|medium|[6.7,0.58,0.08,1....|
|medium|[7.5,0.5,0.36,6.1...|
|medium|[5.6,0.615,0.0,1....|
|medium|[7.8,0.61,0.29,1....|
|medium|[8.9,0.62,0.18,3....|
|medium|[8.9,0.62,0.19,3....|
| high|[8.5,0.28,0.56,1....|
|medium|[8.1,0.56,0.28,1....|
| low|[7.4,0.59,0.08,4....|
|medium|[7.9,0.32,0.51,1....|
+------+--------------------+
only showing top 20 rows
```
```{python eval=FALSE}
from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer
# Index labels, adding metadata to the label column.
# Fit on whole dataset to include all labels in index.
labelIndexer = StringIndexer(inputCol="label", outputCol="indexedLabel").fit(data)
labelIndexer.transform(data).show(6)
```
```{python eval=FALSE}
#output
+------+--------------------+------------+
| label| features|indexedLabel|
+------+--------------------+------------+
|medium|[7.4,0.7,0.0,1.9,...| 0.0|
|medium|[7.8,0.88,0.0,2.6...| 0.0|
|medium|[7.8,0.76,0.04,2....| 0.0|
|medium|[11.2,0.28,0.56,1...| 0.0|
|medium|[7.4,0.7,0.0,1.9,...| 0.0|
|medium|[7.4,0.66,0.0,1.8...| 0.0|
+------+--------------------+------------+
only showing top 6 rows
```
```{python eval=FALSE}
# Automatically identify categorical features, and index them.
# Set maxCategories so features with > 4 distinct values are treated as continuous.
featureIndexer =VectorIndexer(inputCol="features", \
outputCol="indexedFeatures", \
maxCategories=4).fit(data)
featureIndexer.transform(data).show(6)
```
```{python eval=FALSE}
#output
+------+--------------------+--------------------+
| label| features| indexedFeatures|
+------+--------------------+--------------------+
|medium|[7.4,0.7,0.0,1.9,...|[7.4,0.7,0.0,1.9,...|
|medium|[7.8,0.88,0.0,2.6...|[7.8,0.88,0.0,2.6...|
|medium|[7.8,0.76,0.04,2....|[7.8,0.76,0.04,2....|
|medium|[11.2,0.28,0.56,1...|[11.2,0.28,0.56,1...|
|medium|[7.4,0.7,0.0,1.9,...|[7.4,0.7,0.0,1.9,...|
|medium|[7.4,0.66,0.0,1.8...|[7.4,0.66,0.0,1.8...|
+------+--------------------+--------------------+
only showing top 6 rows
```
### 5. Split the data into training and test sets (40% held out for testing)
```{python eval=FALSE}
# Split the data into train and test
(trainingData, testData) = data.randomSplit([0.6, 0.4])
```
```{python eval=FALSE}
data.show()
```
```{python eval=FALSE}
#output
+------+--------------------+
| label| features|
+------+--------------------+
|medium|[7.4,0.7,0.0,1.9,...|
|medium|[7.8,0.88,0.0,2.6...|
|medium|[7.8,0.76,0.04,2....|
|medium|[11.2,0.28,0.56,1...|
|medium|[7.4,0.7,0.0,1.9,...|
|medium|[7.4,0.66,0.0,1.8...|
|medium|[7.9,0.6,0.06,1.6...|
| high|[7.3,0.65,0.0,1.2...|
| high|[7.8,0.58,0.02,2....|
|medium|[7.5,0.5,0.36,6.1...|
|medium|[6.7,0.58,0.08,1....|
|medium|[7.5,0.5,0.36,6.1...|
|medium|[5.6,0.615,0.0,1....|
|medium|[7.8,0.61,0.29,1....|
|medium|[8.9,0.62,0.18,3....|
|medium|[8.9,0.62,0.19,3....|
| high|[8.5,0.28,0.56,1....|
|medium|[8.1,0.56,0.28,1....|
| low|[7.4,0.59,0.08,4....|
|medium|[7.9,0.32,0.51,1....|
+------+--------------------+
only showing top 20 rows
```
### 6. Train neural network
```{python eval=FALSE}
# specify layers for the neural network:
# input layer of size 11 (features), two intermediate of size 5 and 4
# and output of size 7 (classes)
layers = [11, 5, 4, 4, 3 , 7]
# create the trainer and set its parameters
FNN = MultilayerPerceptronClassifier(labelCol="indexedLabel", featuresCol="indexedFeatures",\
maxIter=100, layers=layers, blockSize=128, seed=1234)
```
```{python eval=FALSE}
# Convert indexed labels back to original labels.
labelConverter = IndexToString(inputCol="prediction", outputCol="predictedLabel",
labels=labelIndexer.labels)
```
```{python eval=FALSE}
# Chain indexers and forest in a Pipeline
from pyspark.ml import Pipeline
pipeline = Pipeline(stages=[labelIndexer, featureIndexer, FNN, labelConverter])
```
```{python eval=FALSE}
# train the model
# Train model. This also runs the indexers.
model = pipeline.fit(trainingData)
```
### 7. Make predictions
```{python eval=FALSE}
# Make predictions.
predictions = model.transform(testData)
```
```{python eval=FALSE}
# Select example rows to display.
predictions.select("features","label","predictedLabel").show(5)
```
```{python eval=FALSE}
#output
+--------------------+-----+--------------+
| features|label|predictedLabel|
+--------------------+-----+--------------+
|[5.1,0.585,0.0,1....| high| medium|
|[5.2,0.48,0.04,1....| high| medium|
|[5.4,0.835,0.08,1...| high| medium|
|[5.5,0.49,0.03,1....| high| medium|
|[5.6,0.66,0.0,2.2...| high| medium|
+--------------------+-----+--------------+
only showing top 5 rows
```
### 8. Evaluation
```{python eval=FALSE}
# Select (prediction, true label) and compute test error
evaluator = MulticlassClassificationEvaluator(
labelCol="indexedLabel", predictionCol="prediction", metricName="accuracy")
accuracy = evaluator.evaluate(predictions)
print("Predictions accuracy = %g, Test Error = %g" % (accuracy,(1.0 - accuracy)))
```
```{python eval=FALSE}
#output
Predictions accuracy = 0.808642, Test Error = 0.191358
```