-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrefinedzone_refinedzone_H-Student-6nov.py
399 lines (164 loc) · 7.7 KB
/
refinedzone_refinedzone_H-Student-6nov.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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import pyspark
from pyspark.sql import SparkSession
from operator import add
sc = pyspark.SparkContext()
spark = SparkSession(sc)
# coding: utf-8
# In[1]:
from pyspark.sql import functions as sparkf
# In[2]:
#import time as t
#start_time = t.time()
# ### 1. Business Understanding
# Problem Statement: Prediction of Arrival Delay
# Project Objective: (1) Regression Model (2) Model Deployment
# ### 2. Data Understanding
# #### Spark อ่านไฟล์ 2008.csv จาก HDFS มาเป็น DataFrame
# In[3]:
airline_df = spark.read.parquet('/rawzone/*')
# #### Spark นับจำนวน tuple ใน DataFrame
# In[4]:
#airline_df.count()
# #### Spark: Assign ค่าของตัวแปรเก่า ให้กับตัวแปรใหม่
# In[5]:
airline_row_df = airline_df.filter(sparkf.col('Cancelled') != 1)
# In[6]:
#airline_row_df.count()
# #### Spark แสดง Schema ของข้อมูลใน DataFrame
# In[7]:
#airline_row_df.printSchema()
# In[8]:
#airline_row_df.describe().toPandas().transpose()
# ### 3. Data Preparation
# #### Spark เรียกใช้ Data Types และ Functions ต่างๆ สำหรับจัดการข้อมูลใน DataFrame
# In[9]:
from pyspark.sql.types import *
from pyspark.sql.functions import col, udf
# In[10]:
crunched_df = airline_row_df.withColumn('DepTime',airline_row_df['DepTime']. cast(DoubleType())).withColumn('TaxiOut',airline_row_df['TaxiOut']. cast(DoubleType())).withColumn('TaxiIn',airline_row_df['TaxiIn']. cast(DoubleType())).withColumn('DepDelay',airline_row_df['DepDelay']. cast(DoubleType())).withColumn('DayOfWeek',airline_row_df['DayOfWeek']. cast(DoubleType())).withColumn('Distance',airline_row_df['Distance']. cast(DoubleType())).withColumn('ArrDelay',airline_row_df['ArrDelay']. cast(DoubleType()))
# #### Spark แสดง Schema ของข้อมูลใน DataFrame หลังจาก cast type แล้ว
# In[11]:
#crunched_df.printSchema()
# #### Python ติดตั้ง Module "pandas"
# In[12]:
#get_ipython().system(' pip install pandas')
# #### Spark ทำ Data Exploratory โดยใช้สถิติเบื้องต้นกับข้อมูลใน DataFrame
# #### Spark ทำ Data Transformation โดยใช้ Data Discretization กับ "DepTime" ใน DataFrame
# In[14]:
def t_timeperiod(origin):
if origin is None:
period = None
elif origin > 0 and origin < 600:
period = '00.01-05.59'
elif origin >= 600 and origin <=1200:
period = '06.00-11.59'
elif origin >= 1200 and origin <= 1800:
period = '12.00-17.59'
elif origin >= 1800 and origin <= 2400:
period = '18.00-24.00'
else:
period = 'NA'
return period
# In[15]:
timeperiod = udf(lambda x: t_timeperiod(x),StringType())
# In[16]:
discretized_df = crunched_df.withColumn('DepTime',timeperiod(crunched_df['DepTime']))
# #### Spark ทำ Data Transformation โดยใช้ Data Normalization กับ "Distance" และ "ArrDelay" ใน DataFrame
# In[17]:
from pyspark.sql.functions import *
max_distance = discretized_df.select(max('Distance')).collect()[0][0]
min_distance = discretized_df.select(min('Distance')).collect()[0][0]
# In[18]:
max_ArrDelay = discretized_df.select(max('ArrDelay')).collect()[0][0]
min_ArrDelay = discretized_df.select(min('ArrDelay')).collect()[0][0]
# In[19]:
def t_normalized_distance(origin):
if origin is None:
return None
else:
return ((origin-min_distance)/(max_distance-min_distance))
# In[20]:
def t_normalized_ArrDelay(origin):
if origin is None:
return None
else:
return ((origin-min_ArrDelay)/(max_ArrDelay-min_ArrDelay))
# In[21]:
normalized_distance = udf(lambda x: t_normalized_distance(x),DoubleType())
# In[22]:
normalized_ArrDelay = udf(lambda x: t_normalized_ArrDelay(x),DoubleType())
# In[23]:
normalized_df = discretized_df
normalized_df = discretized_df.\
withColumn('Distance', normalized_distance(discretized_df['Distance'])).\
withColumn('ArrDelay', normalized_ArrDelay(discretized_df['ArrDelay']))
# #### Spark ทำ Feature Selection ด้วยการเลือกเฉพาะบาง Attributes มาเป็น Features
# In[24]:
features_df = normalized_df.select(['UniqueCarrier','Origin','Dest', 'DepTime','TaxiOut','TaxiIn','DepDelay', 'DayOfWeek','Distance','ArrDelay'])
# #### Spark กำจัดค่า Null ด้วยการลบทั้ง Tuple (Record) เมื่อพบว่ามี Attribute ใดมีค่า Null
# In[25]:
final_df = features_df.dropna()
# #### Spark นับจำนวน tuple ใน DataFrame
# In[26]:
#final_df.count()
# In[27]:
#final_df.show()
# ### 4. Modeling (and making some data transformation )
# #### Spark แบ่งข้อมูลเป็น training set และ test set
# In[28]:
training_df,test_df = final_df.randomSplit([0.80,0.20], seed = 12)
# #### Spark นับจำนวน tuple ใน DataFrame
# In[29]:
#training_df.count()
# #### Spark แสดง Schema ของ training set
# In[30]:
#training_df.printSchema()
# #### Transformation categorical variable to numerical one.
# In[31]:
from pyspark.ml.feature import StringIndexer,OneHotEncoder
# In[32]:
DepTimeIndexer = StringIndexer(inputCol='DepTime',outputCol='DepTimeIndexed',handleInvalid='keep')
# In[33]:
UniqueCarrierIndexer = StringIndexer(inputCol='UniqueCarrier', outputCol='UniqueCarrierIndexed',handleInvalid='keep')
# In[34]:
UniqueCarrierOneHotEncoder = OneHotEncoder(dropLast=False,inputCol='UniqueCarrierIndexed', outputCol='UniqueCarrierVec')
# In[35]:
OriginIndexer = StringIndexer(inputCol='Origin', outputCol='OriginIndexed',handleInvalid='keep')
# In[36]:
OriginOneHotEncoder = OneHotEncoder(dropLast=False,inputCol='OriginIndexed', outputCol='OriginVec')
# In[37]:
DestIndexer = StringIndexer(inputCol='Dest', outputCol='DestIndexed',handleInvalid='keep')
# In[38]:
DestOneHotEncoder = OneHotEncoder(dropLast=False,inputCol='DestIndexed', outputCol='DestVec')
# In[39]:
#labelIndexer = StringIndexer(inputCol='ArrDelay',outputCol='labelIndexed')
# #### Combines a selected columns into a single vector column.
# In[40]:
from pyspark.mllib.linalg import Vectors
# In[41]:
from pyspark.ml.feature import VectorAssembler
# In[42]:
from pyspark.ml import Pipeline
# In[43]:
featureAssembler = VectorAssembler(inputCols=['UniqueCarrierIndexed', 'OriginVec', 'DepTimeIndexed', 'TaxiOut','TaxiIn', 'DepDelay', 'DayOfWeek', 'Distance'
], outputCol='allFeatures')
# #### Define an algorithm.
# In[44]:
from pyspark.ml.regression import DecisionTreeRegressor, LinearRegression
# In[45]:
dt = LinearRegression(maxIter=100, regParam=0, loss='squaredError',\
labelCol='ArrDelay',featuresCol='allFeatures')
# #### Pipeline.
# In[46]:
pipeline_dt = Pipeline().setStages([UniqueCarrierIndexer, UniqueCarrierOneHotEncoder, DepTimeIndexer, OriginIndexer , OriginOneHotEncoder, DestIndexer, DestOneHotEncoder, featureAssembler,dt])
# In[47]:
#training_df.count()
# #### Launch the pipeline and get a model.
# In[48]:
dtModel = pipeline_dt.fit(training_df)
# #### print out model structure
# In[49]:
#tree = dtModel.stages[8]
# In[50]:
#tree.toDebugString
dtModel.write().overwrite().save('gs://6nov/refinedzone/ArrDelay_regressionModel')