!
cat ../../run.sh
PYSPARK_DRIVER_PYTHON=jupyter PYSPARK_DRIVER_PYTHON_OPTS="notebook" $SPARK_HOME/bin/pyspark --master local[2]
PYSPARK_DRIVER_PYTHON=jupyter
This sets the driver as this Jupyter Notebook
PYSPARK_DRIVER_PYTHON_OPTS="notebook"
This is used to pass options when starting the Python driver
$SPARK_HOME/bin/pyspark --master local[2]
This runs a pyspark shell in local mode with 2 executors.
import
pyspark.sql.functions
as
func
import
matplotlib.pyplot
as
plt
import
seaborn
as
sns
from
pyspark.mllib.stat
import
Statistics
from
pyspark.mllib.linalg
import
Vectors
import
pandas
as
pd
from
time
import
time
import
operator
%
matplotlib
inline
from
__future__
import
print_function
if
(
'sc'
in
locals
()
or
'sc'
in
globals
()):
print
(
"SparkContext is defined."
)
else
:
print
(
"SparkContext does not exist."
)
SparkContext is defined.
if
(
'sqlContext'
in
locals
()
or
'sqlContext'
in
globals
()):
print
(
"SQLContext is defined."
)
else
:
print
(
"SQLContext does not exist."
)
SQLContext is defined.
start_time
=
time
()
print
(
"data_source ="
,
data_source
)
print
(
"data_type ="
,
data_type
)
if
(
use_local_datapath
):
user_data_path
=
local_user_data_path
else
:
user_data_path
=
dbfs_user_data_path
print
(
"user_data_path ="
,
user_data_path
)
user_df
=
sqlContext
.
read
.
load
(
user_data_path
)
.
cache
()
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
data_source = StackOverflowdata_type = Useruser_data_path = ../../data/StackOverflow/UserTime taken = 15.0903670788 seconds.
print
(
"Schema for user dataframe"
)
user_df
.
printSchema
()
Schema for user dataframeroot |-- Id: long (nullable = true) |-- Reputation: long (nullable = true) |-- CreationDate: string (nullable = true) |-- DisplayName: string (nullable = true) |-- EmailHash: string (nullable = true) |-- lastAccessDate: string (nullable = true) |-- WebsiteUrl: string (nullable = true) |-- Location: string (nullable = true) |-- Age: long (nullable = true) |-- AboutMe: string (nullable = true) |-- Views: long (nullable = true) |-- UpVotes: long (nullable = true) |-- DownVotes: long (nullable = true) |-- AccountId: long (nullable = true)
number_of_rows
=
user_df
.
count
()
print
(
"Total number of rows in the data = "
+
str
(
number_of_rows
))
Total number of rows in the data =
number_of_unique_ids
=
user_df
.
select
(
'Id'
)
.
distinct
()
.
count
()
print
(
"Total number of unique Id in the data = "
+
str
(
number_of_unique_ids
))
Total number of unique Id in the data =
max_reputation
=
user_df
.
agg
({
"Reputation"
:
"max"
})
.
collect
()[
0
][
0
]
print
(
"Maximum reputation for a user = "
+
str
(
max_reputation
))
Maximum reputation for a user = 872346
max_upvotes
=
user_df
.
agg
({
"UpVotes"
:
"max"
})
.
collect
()[
0
][
0
]
print
(
"Maximum UpVotes for a user = "
+
str
(
max_upvotes
))
Maximum UpVotes for a user = 155541
user_df
.
describe
()
.
toPandas
()
| summary | Id | Reputation | Age | Views | UpVotes | DownVotes | AccountId | |
|---|---|---|---|---|---|---|---|---|
| 0 | count | |||||||
| 1 | mean | 3458959.329377492 | 122.36497495798147 | 2.1128550085270037 | 14.985955015607887 | 13.056719106300964 | 1.5714251492533895 | 4239436.648318959 |
| 2 | stddev | 1775717.819577991 | 2178.7325223376183 | 9.808645948617777 | 621.4858576805434 | 157.4016433378767 | 296.28945574718387 | 2463450.0689051063 |
| 3 | min | -1 | 1 | -972 | 0 | 0 | 0 | -2 |
| 4 | max | 872346 | 96 | 155541 | 683400 |
user_max_reputation
=
user_df
.
filter
(
"Reputation = "
+
str
(
max_reputation
))
.
select
(
'Id'
)
.
collect
()[
0
][
0
]
user_df
.
filter
(
"Reputation = "
+
str
(
max_reputation
))
.
toPandas
()
| Id | Reputation | CreationDate | DisplayName | EmailHash | lastAccessDate | WebsiteUrl | Location | Age | AboutMe | Views | UpVotes | DownVotes | AccountId | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 22656 | 872346 | 2008-09-26T12:05:05.150 | Jon Skeet | 2016-06-11T17:54:35.587 | http://csharpindepth.com | Reading, United Kingdom | 40 | <p>\nAuthor of <a href="http://www.manning.com... | 15469 | 5013 | 11683 |
Spark Dataframes and RDDs are lazy. They do nothing unless an action is called. We can keep adding as many transformations as we want but nothing actually happens till we call an action. By deferring evaluations, Spark can optimise the overall workflow as it evaluates only that which is needed.
start_time
=
time
()
user_max_reputation
=
user_df
.
orderBy
(
"Reputation"
,
desc
=
True
)
print
(
user_max_reputation
)
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
start_time
=
time
()
# list_user_max_reputation = user_df.orderBy("Reputation", desc=True).collect()
print
(
"This command crashes."
)
# print ("Time taken =", time() - start_time, "seconds.")
This command crashes.
start_time
=
time
()
list_user_max_reputation
=
user_df
.
orderBy
(
"Reputation"
,
desc
=
True
)
.
take
(
1
)
print
(
"Size of list ="
,
len
(
list_user_max_reputation
))
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
Size of list = 1Time taken = 29.9515519142 seconds.
start_time
=
time
()
column_list
=
[
"Reputation"
,
"UpVotes"
,
"DownVotes"
,
"Views"
,
"Age"
]
for
col
in
column_list
:
max_value_col
=
user_df
.
orderBy
(
col
,
ascending
=
False
)
.
select
(
"Id"
,
col
)
.
take
(
1
)[
0
]
userId
=
str
(
max_value_col
[
0
])
print
(
"max"
,
col
,
"value ="
,
str
(
max_value_col
[
1
]),
"for userId ="
,
userId
,
""
,
base_url
+
userId
,
"
\n
"
)
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
filter_expression
=
"AccountId > -1 and DownVotes > -1 and UpVotes > -1 and
\
Views > -1 and Reputation > -9223372036854775808 and Age > 0"
vectorData
=
user_df
.
filter
(
filter_expression
)
\
.
select
(
column_list
)
\
.
map
(
lambda
data
:
Vectors
.
dense
([
c
for
c
in
data
]))
print
(
vectorData
)
vectorData
.
take
(
5
)
PythonRDD[118] at RDD at PythonRDD.scala:43
[DenseVector([11.0, 0.0, 0.0, 5.0, 29.0]), DenseVector([21.0, 1.0, 0.0, 9.0, 34.0]), DenseVector([1.0, 0.0, 0.0, 0.0, 27.0]), DenseVector([336.0, 7.0, 1.0, 67.0, 20.0]), DenseVector([119.0, 17.0, 0.0, 23.0, 25.0])]
print
(
"Columns in vectorData are"
,
column_list
)
stats
=
Statistics
.
colStats
(
vectorData
)
for
col
,
val
in
zip
(
column_list
,
stats
.
mean
()):
print
(
"Average "
,
col
,
" = "
,
val
)
Columns in vectorData are ['Reputation', 'UpVotes', 'DownVotes', 'Views', 'Age']Average Reputation = 657.790010956Average UpVotes = 71.3291876684Average DownVotes = 8.45428023762Average Views = 79.1855292626Average Age = 30.6904020327
Other supported statistics include:
* count()* max()* mean()* min()* normL1()* normL2()* numNonzeros()* variance()
For the sake of completeness, we will try all these methods. We would visualise this data as Pandas dataframe to make it look clean
pd_data
=
map
(
list
,
[[
stats
.
count
()]
*
5
,
stats
.
max
(),
stats
.
mean
(),
stats
.
min
(),
stats
.
normL1
(),
stats
.
normL2
(),
\
stats
.
numNonzeros
()
,
stats
.
variance
()])
pd_index
=
[
'Count'
,
'Max'
,
'Mean'
,
'Min'
,
'NormL1'
,
'NormL2'
,
'NumNonzeros'
,
'Variance'
]
pd
.
DataFrame
(
pd_data
,
index
=
pd_index
,
columns
=
column_list
)
| Reputation | UpVotes | DownVotes | Views | Age | |
|---|---|---|---|---|---|
| Count | 5.576910e+05 | ||||
| Max | 8.723460e+05 | .000000 | 96.000000 | ||
| Mean | 6.577900e+02 | 71.329188 | 8.454280 | 79.185529 | 30.690402 |
| Min | 1.000000e+00 | 0.000000 | 0.000000 | 0.000000 | 6.000000 |
| NormL1 | 3.668436e+08 | ||||
| NormL2 | 4.349657e+06 | ||||
| NumNonzeros | 5.576910e+05 | ||||
| Variance | 3.349210e+07 | 72.076761 |
start_time
=
time
()
Statistics
.
colStats
(
vectorData
)
pd_data
=
Statistics
.
corr
(
vectorData
,
method
=
"pearson"
)
pd
.
DataFrame
(
pd_data
,
index
=
column_list
,
columns
=
column_list
)
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
pd
.
DataFrame
(
pd_data
,
index
=
column_list
,
columns
=
column_list
)
Time taken = 12.8704071045 seconds.
| Reputation | UpVotes | DownVotes | Views | Age | |
|---|---|---|---|---|---|
| Reputation | 1.000000 | 0.568410 | 0.338779 | 0.558201 | 0.060482 |
| UpVotes | 0.568410 | 1.000000 | 0.328948 | 0.269376 | 0.061463 |
| DownVotes | 0.338779 | 0.328948 | 1.000000 | 0.222938 | 0.021307 |
| Views | 0.558201 | 0.269376 | 0.222938 | 1.000000 | 0.021190 |
| Age | 0.060482 | 0.061463 | 0.021307 | 0.021190 | 1.000000 |
High positive correlation between Reputation and Upvotes (0.57).High positive correlation between Reputation and Views (0.56).
The last observation can be explained by the hypothesis that more reputation you have, more likely it is that people would land up on your profile page. Lets drill down further on the first observation.
We filter the data to contain only Reputation and UpVotes and filter for rows with defualt values
columns_to_select
=
[
"Reputation"
,
"UpVotes"
]
data
=
user_df
.
filter
(
filter_expression
)
.
select
(
columns_to_select
)
.
cache
()
data
.
sample
(
False
,
0.0001
,
42
)
.
toPandas
()
| Reputation | UpVotes | |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 665 | 61 |
| 2 | 1 | 0 |
| 3 | 11 | 0 |
| 4 | 1 | 0 |
| 5 | 1 | 0 |
| 6 | 1 | 0 |
| 7 | 1 | 0 |
| 8 | 1 | 0 |
| 9 | 55 | 5 |
| 10 | 287 | 30 |
| 11 | 1 | 0 |
| 12 | 1 | 0 |
| 13 | 1 | 0 |
| 14 | 1 | 0 |
| 15 | 373 | 9 |
| 16 | 11 | 0 |
| 17 | 429 | 32 |
| 18 | 5870 | 413 |
| 19 | 980 | 4 |
| 20 | 1 | 0 |
| 21 | 108 | 9 |
| 22 | 8669 | 2324 |
| 23 | 866 | 38 |
| 24 | 45 | 0 |
| 25 | 1 | 0 |
| 26 | 46 | 49 |
| 27 | 6 | 0 |
| 28 | 1 | 0 |
| 29 | 116 | 602 |
| ... | ... | ... |
| 31 | 283 | 9 |
| 32 | 94 | 1 |
| 33 | 2234 | 667 |
| 34 | 19 | 0 |
| 35 | 21 | 2 |
| 36 | 1662 | 69 |
| 37 | 151 | 0 |
| 38 | 1 | 0 |
| 39 | 189 | 2 |
| 40 | 23 | 6 |
| 41 | 1 | 0 |
| 42 | 1563 | 512 |
| 43 | 25 | 3 |
| 44 | 1 | 0 |
| 45 | 1 | 0 |
| 46 | 1161 | 38 |
| 47 | 1 | 0 |
| 48 | 1 | 0 |
| 49 | 1 | 0 |
| 50 | 1 | 0 |
| 51 | 1 | 0 |
| 52 | 1 | 0 |
| 53 | 47 | 17 |
| 54 | 178 | 62 |
| 55 | 20 | 54 |
| 56 | 22 | 5 |
| 57 | 6 | 0 |
| 58 | 1 | 0 |
| 59 | 1 | 0 |
| 60 | 1 | 0 |
61 rows × 2 columns
Notice that this is the second dataframe that we have cached so far.
We can check the memory profile for the app at http://localhost:4040/storage .
We no longer need the user_df dataframe so we will unpersist it and recover some memory.
user_df
.
unpersist
()
DataFrame[Id: bigint, Reputation: bigint, CreationDate: string, DisplayName: string, EmailHash: string, lastAccessDate: string, WebsiteUrl: string, Location: string, Age: bigint, AboutMe: string, Views: bigint, UpVotes: bigint, DownVotes: bigint, AccountId: bigint]
Check that now only one dataframe is cached for the application. http://localhost:4040/storage .
Spark is good at number chrunching and performing compuations but not so good at visualisations. So we will load a sample of the dataset into Pandas dataframe using the toPandas method and visualise it using sns.
start_time
=
time
()
pandas_df
=
data
.
sample
(
False
,
.
1
,
42
)
.
toPandas
()
%
matplotlib
inline
sns
.
jointplot
(
'Reputation'
,
'UpVotes'
,
data
=
pandas_df
)
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
start_time
=
time
()
pandas_df
=
data
.
sample
(
False
,
0.9
,
42
)
.
toPandas
()
%
matplotlib
inline
sns
.
jointplot
(
'Reputation'
,
'UpVotes'
,
data
=
pandas_df
)
print
(
"Time taken ="
,
time
()
-
start_time
,
"seconds."
)
Time taken = 3.80150699615 seconds.
This visualistion is unintutive as most of the data is distributed in a narrow zone and the scale is skewed due to outliers. We will try plotting the values on the log scale.
log_pandas_df
=
data
.
select
(
func
.
log10
(
data
[
"Reputation"
]),
func
.
log10
(
data
[
"UpVotes"
]))
.
sample
(
False
,
.
1
)
.
toPandas
()
%
matplotlib
inline
sns
.
jointplot
(
'LOG10(Reputation)'
,
'LOG10(UpVotes)'
,
data
=
log_pandas_df
)
<seaborn.axisgrid.JointGrid at 0x7f2973bdf150>
Before we wrap up, let us play with the CreationDate column and see if we can mine some interesting observations on that front. The idea is to show how we can play with more complex data types (like datetime)and use some Spark operators as well.
We will start with the user_df dataframe. Remember that we had uncached it which means it is no longer available in memory but we can still run operations on it. In this case, the dataframe would be loaded once again but will not be persisted, unless we explicitly ask Spark to do so.
creation_date_df
=
user_df
.
select
(
"CreationDate"
)
creation_date_df
.
printSchema
()
creation_date_df
.
show
(
10
)
root |-- CreationDate: string (nullable = true)+--------------------+| CreationDate|+--------------------+|2014-12-19T22:29:...||2014-12-19T22:30:...||2014-12-19T22:30:...||2014-12-19T22:30:...||2014-12-19T22:31:...||2014-12-19T22:31:...||2014-12-19T22:31:...||2014-12-19T22:32:...||2014-12-19T09:20:...||2014-12-19T22:32:...|+--------------------+only showing top 10 rows
Note that CreationDate column was parsed as string . Let us fix that by selecting CreationDate as date type.
date_df
=
creation_date_df
.
select
(
func
.
to_date
(
creation_date_df
[
"CreationDate"
])
.
alias
(
"CreationDate"
))
date_df
.
printSchema
()
date_df
.
show
(
10
)
root |-- CreationDate: date (nullable = true)+------------+|CreationDate|+------------+| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|| 2014-12-19|+------------+only showing top 10 rows
We want to count the number of new accounts each day. We would try doing this using both RDDs and DataFrames and compare their performance.
Convert dataframe to rdd.
Map each row with numerical value 1 (number of accounts each row contributes).
Then we reduce our data using date as the key and add the values corresponding to same date.
start_time
=
time
()
date_rdd
=
date_df
.
rdd
aggregated_df
=
date_rdd
.
map
(
lambda
a
:
(
a
,
1
))
.
groupByKey
()
.
map
(
lambda
a
:
(
a
[
0
],
sum
(
a
[
1
])))
print
(
"aggregated_df maps each date to number of accounts that were created."
)
print
(
"Number of rows = "
,
aggregated_df
.
count
())
time_taken_rdd
=
time
()
-
start_time
print
(
"Time taken ="
,
time_taken_rdd
,
"seconds."
)
aggregated_df maps each date to number of accounts that were created.Number of rows = 2874Time taken = 21.812182188 seconds.
start_time
=
time
()
aggregated_df
=
date_df
.
groupBy
(
'CreationDate'
)
.
count
()
print
(
"aggregated_df maps each date to number of accounts that were created."
)
print
(
"Number of rows = "
,
aggregated_df
.
count
())
time_taken_df
=
time
()
-
start_time
print
(
"Time taken ="
,
time_taken_df
,
"seconds."
)
aggregated_df maps each date to number of accounts that were created.Number of rows = 2874Time taken = 4.52407288551 seconds.
print
(
"time_taken_rdd ="
,
time_taken_rdd
)
print
(
"time_taken_df ="
,
time_taken_df
)
print
(
"Speed up ="
,
time_taken_rdd
/
time_taken_df
)
time_taken_rdd = 21.812182188time_taken_df = 4.52407288551Speed up = 4.82135958903
aggregated_df
.
printSchema
()
root |-- CreationDate: date (nullable = true) |-- count: long (nullable = false)
pandas_df
=
aggregated_df
.
select
(
"CreationDate"
,
aggregated_df
[
"count"
]
.
alias
(
"NewAccounts"
))
\
.
orderBy
(
func
.
asc
(
"CreationDate"
))
.
toPandas
()
pandas_df
| CreationDate | NewAccounts | |
|---|---|---|
| 0 | 2008-07-31 | 9 |
| 1 | 2008-08-01 | 80 |
| 2 | 2008-08-02 | 54 |
| 3 | 2008-08-03 | 54 |
| 4 | 2008-08-04 | 83 |
| 5 | 2008-08-05 | 86 |
| 6 | 2008-08-06 | 89 |
| 7 | 2008-08-07 | 81 |
| 8 | 2008-08-08 | 66 |
| 9 | 2008-08-09 | 64 |
| 10 | 2008-08-10 | 67 |
| 11 | 2008-08-11 | 85 |
| 12 | 2008-08-12 | 70 |
| 13 | 2008-08-13 | 74 |
| 14 | 2008-08-14 | 92 |
| 15 | 2008-08-15 | 88 |
| 16 | 2008-08-16 | 62 |
| 17 | 2008-08-17 | 72 |
| 18 | 2008-08-18 | 134 |
| 19 | 2008-08-19 | 139 |
| 20 | 2008-08-20 | 118 |
| 21 | 2008-08-21 | 107 |
| 22 | 2008-08-22 | 112 |
| 23 | 2008-08-23 | 63 |
| 24 | 2008-08-24 | 93 |
| 25 | 2008-08-25 | 100 |
| 26 | 2008-08-26 | 158 |
| 27 | 2008-08-27 | 124 |
| 28 | 2008-08-28 | 141 |
| 29 | 2008-08-29 | 106 |
| ... | ... | ... |
| 2844 | 2016-05-14 | 2855 |
| 2845 | 2016-05-15 | 2819 |
| 2846 | 2016-05-16 | 4512 |
| 2847 | 2016-05-17 | 4975 |
| 2848 | 2016-05-18 | 5276 |
| 2849 | 2016-05-19 | 4976 |
| 2850 | 2016-05-20 | 4577 |
| 2851 | 2016-05-21 | 2761 |
| 2852 | 2016-05-22 | 2757 |
| 2853 | 2016-05-23 | 4605 |
| 2854 | 2016-05-24 | 4997 |
| 2855 | 2016-05-25 | 4880 |
| 2856 | 2016-05-26 | 4845 |
| 2857 | 2016-05-27 | 4465 |
| 2858 | 2016-05-28 | 2545 |
| 2859 | 2016-05-29 | 2515 |
| 2860 | 2016-05-30 | 3973 |
| 2861 | 2016-05-31 | 4671 |
| 2862 | 2016-06-01 | 5025 |
| 2863 | 2016-06-02 | 5012 |
| 2864 | 2016-06-03 | 4336 |
| 2865 | 2016-06-04 | 2716 |
| 2866 | 2016-06-05 | 2704 |
| 2867 | 2016-06-06 | 4526 |
| 2868 | 2016-06-07 | 4903 |
| 2869 | 2016-06-08 | 5116 |
| 2870 | 2016-06-09 | 4863 |
| 2871 | 2016-06-10 | 4299 |
| 2872 | 2016-06-11 | 2580 |
| 2873 | 2016-06-12 | 320 |
2874 rows × 2 columns
Let us plot this data and see if there is any interesting observation.
%
matplotlib
inline
plt
.
plot
(
pandas_df
.
CreationDate
,
pandas_df
.
NewAccounts
)
[<matplotlib.lines.Line2D at 0x7f2973efdc50>]
Interesting! We can see a spike in the initial data. If we zoom in, we see the date of the spike as 15th September,2008 when over 2000 new users joined StackOverflow. Flipping the pages of history, this was the day when StackOverflow was opened for public.