-
Notifications
You must be signed in to change notification settings - Fork 5
/
youtube_adview_prediction.py
599 lines (424 loc) · 17.6 KB
/
youtube_adview_prediction.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# -*- coding: utf-8 -*-
"""youtube_adview_prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1nbhPdY2S_RHDZbEUGlfzCh4ikxt1-cel
# <center>**===========YouTube AdView Prediction============**</center>
# **1. Introduction**
### **Objective:**
To build a machine learning model which will predict youtube adview count based on other youtube metrics.
### **Data Description:**
- train.csv - the training set
- test.csv - the test set
- The file train.csv contains metrics and other details of about 15000 youtube videos. The metrics include number of views, likes, dislikes, comments and apart from that published date, duration and category are also included. The train.csv file also contains the metric number of adviews which is our target variable for prediction.
### **Table of Content:**
1. Introduction
2. Install & Import Libraries
3. Load Datasets
4. Exploratory Data Analysis
5. Feature Engineering
6. Model Development
7. Find Prediction
# **2. Install & Import Libraries**
- Run the below cell, if you've not install these libraries before.
"""
# # use to visualize missing value
# !pip install missingno
# # use for hyper parameter tuning
# !pip install optuna
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
## Display all the columns of the dataframe
pd.pandas.set_option('display.max_columns',None)
from scipy import stats
from scipy.stats import norm, skew # for some statistics
import warnings # to ignore warning
from sklearn.preprocessing import RobustScaler, PowerTransformer, LabelEncoder
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
import optuna
from sklearn.model_selection import KFold, cross_val_score
from sklearn.linear_model import Ridge, Lasso
from sklearn.ensemble import StackingRegressor, RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
import xgboost as xgb
import lightgbm as lgb
import joblib
import warnings
warnings.filterwarnings('ignore')
print("Library Imported!!")
"""# **3. Load Datasets**"""
# load train and test dataset
train_df = pd.read_csv("/content/train.csv")
test_df = pd.read_csv("/content/test.csv")
"""# **4. Exploratory Data Analysis**
### 4.1. Train Data Exploration
For both train and test dataset, We'll explore following things
- First 5 rows
- Data shape
- Data information
- Data types
- Null value
### 4.1.1. First 5 records
"""
train_df.head()
"""### 4.1.2. Data Shape - Train Data"""
train_df.shape
"""### 4.1.3. Data Information - Train Data"""
train_df.info()
"""### 4.1.4. Statistical analysis - Train Data"""
train_df.describe(include='all')
"""### 4.1.5. Data Type - Train Data"""
train_dtype = train_df.dtypes
train_dtype.value_counts()
"""### 4.1.6. Null Value - Train Data"""
train_df.isnull().sum().sort_values(ascending = False).head(10)
"""### 4.1.7. Visualize missing value using **Misingno** - Train Data"""
msno.matrix(train_df)
"""### 4.2. Test Data Exploration
### 4.2.1. First 5 rows - Test Data
"""
test_df.head()
"""### 4.2.2. Data Shape - Test Data"""
test_df.shape
"""### 4.2.3. Data Type - Test Data"""
test_dtype = test_df.dtypes
test_dtype.value_counts()
"""### 4.2.4. Data Information - Test Data"""
test_df.info()
"""### 4.2.5. Statistical analysis - Test Data"""
test_df.describe(include='all')
"""### 4.2.6. Null Data - Test Data"""
test_df.isnull().sum().sort_values(ascending = False).head(10)
"""### 4.2.7. Visualize missing value using **Misingno** - Test Data"""
msno.matrix(test_df)
"""### 4.2.8. Report - Data Exploration
- The shape of train and test datasets are (14999, 9) & (8764, 8)
- There is no null value present in both dataset.
- Some categorical columns should convert to numerical.
- e.g 'views', 'likes', 'dislikes', 'comment'.
### 4.3. Train & Test Data Comparison
Here we'll compare below things between train and test dataset.
- Data Type
- Null values
- Data Distribution
### 4.3.1. Data Type Comparison
"""
# as 'SalePrice' Column is not available in test dataset. So we'll delete it.
trn_dtype = train_dtype.drop('adview')
trn_dtype.compare(test_dtype)
"""- The data type of each columns is same in both train and test dataframe
### 4.3.2. Null Value Comparison
"""
null_train = train_df.isnull().sum()
null_test = test_df.isnull().sum()
null_train = null_train.drop('adview')
null_comp_df = null_train.compare(null_test).sort_values(['self'],ascending = [False])
null_comp_df
"""- Here we can see that there is no null value present in test and train dataset.
### 4.3.3. Distribution Comparison
Before going for distribution comparison,let's do some data preprocessing which will help in data analysis.
### 4.3.3.1 Convert Categorical column to numerical
"""
convert_col = ['views', 'likes', 'dislikes', 'comment']
# these columns contain 'F' letter. So replace it by '0'. As we are converting columns to numerical.
for col in convert_col:
train_df[col].replace({"F": 0}, inplace=True)
test_df[col].replace({"F": 0}, inplace=True)
# Convert "categorical" feature to "numerical"
for col in convert_col:
train_df[col] = train_df[col].astype('int')
test_df[col] = test_df[col].astype('int')
"""### 4.3.3.2. Temporal variable analysis"""
train_df.head()
# convert "duration" column format into "second" format
def checki(x):
y = x[2:]
h = ''
m = ''
s = ''
mm = ''
P = ['H','M','S']
for i in y:
if i not in P:
mm+=i
else:
if(i=="H"):
h = mm
mm = ''
elif(i == "M"):
m = mm
mm = ''
else:
s = mm
mm = ''
if(h==''):
h = '00'
if(m == ''):
m = '00'
if(s==''):
s='00'
bp = h+':'+m+':'+s
return bp
train_mp = train_df["duration"]
test_mp = test_df["duration"]
train_time = train_mp.apply(checki)
test_time = test_mp.apply(checki)
def func_sec(time_string):
h, m, s = time_string.split(":")
return int(h) * 3600 + int(m) * 60 + int(s)
train_time=train_time.apply(func_sec)
test_time=test_time.apply(func_sec)
train_df["duration"]=train_time
test_df["duration"]=test_time
# train_df.head()
"""### 4.3.3.3. Convert 'date' to 'year' format in 'published' column"""
train_df['published'] = pd.DatetimeIndex(train_df['published']).year
test_df['published'] = pd.DatetimeIndex(test_df['published']).year
# convert to numerical feature
train_df['published'] = train_df['published'].astype('int')
test_df['published'] = test_df['published'].astype('int')
train_df.head()
numerical_features = [col for col in train_df.columns if train_df[col].dtypes != 'O']
discrete_features = [col for col in numerical_features if len(train_df[col].unique()) < 10 and col not in ['vidid']]
continuous_features = [feature for feature in numerical_features if feature not in discrete_features+['vidid']]
categorical_features = [col for col in train_df.columns if train_df[col].dtype == 'O']
print("Total Number of Numerical Columns : ",len(numerical_features))
print("Number of discrete features : ",len(discrete_features))
print("No of continuous features are : ", len(continuous_features))
print("Number of categorical features : ",len(categorical_features))
"""### 4.3.3.4. Concat Train and Test datasets"""
# combined train and test datasets
combined_df = pd.concat([train_df,test_df],axis=0)
combined_df["Label"] = "test"
combined_df["Label"][:14999] = "train"
"""### 4.3.4. Distribution Comparison - Continuous"""
plt.figure(figsize=(20, 8))
continuous_features = ['views', 'comment', 'likes', 'dislikes','published', 'duration']
pos = 1
for i, feature in enumerate(continuous_features):
plt.subplot(2 , 3 , pos)
sns.distplot(test_df[feature], hist = False, kde = True, kde_kws = {'linewidth': 3},color='r' )
sns.distplot(train_df[feature], hist = False, kde = True, kde_kws = {'linewidth': 3} ,color='b')
pos = pos + 1
"""Above distribution shows that:
- The distribution of train and test data are similar for most continous features.
- All distributions are not **normally distributed**.
### 4.3.5. Linearity Check
Here we'll see the linearity between all features and the target variable.
"""
plt.figure(figsize=(20, 8))
pos = 1
for i, feature in enumerate(continuous_features):
plt.subplot(2 , 3 , pos)
sns.scatterplot(data=combined_df, x = feature, y= "adview")
pos = pos + 1
"""### 4.3.6. Distribution Comparison - Categorical
- There are two categorical features. These are **"category", "vidid"**.
- **"vidid"** is the id of video. So it has no impact to target variable.
- So we'll only check the distribution of **"category"** column.
"""
plt.figure(figsize=(30, 8))
sns.countplot(data = combined_df, x = 'category', hue="Label")
"""Above distribution shows that:
- The distribution of train and test data are similar for most categorical features.
### 4.3.7. Distribution - Target Variable
"""
sns.distplot(train_df["adview"], hist = False, kde = True, kde_kws = {'linewidth': 3} ,color='b')
"""### 4.3.8. Data Correlation"""
training_corr = train_df.corr(method='spearman')
plt.figure(figsize=(20,10))
sns.heatmap(training_corr,cmap="YlGnBu", linewidths=.5)
"""#**5. Feature Engineering**
### 5.1. Drop Columns
Here we'll drop unnecessary columns
"""
drop_columns = ["vidid",'Label','published','duration']
# Drop columns
print("Number of columns before dropping : ",len(combined_df.columns))
print("Number of dropping columns : ",len(drop_columns))
combined_df.drop(columns=drop_columns, inplace=True, errors='ignore')
print("Number of columns after dropping : ",len(combined_df.columns))
"""### 5.2. Apply PowerTransformer to columns
- We saw in distribution of continuous features that some features are not linear towards target feature. So we need to transform this.
- Lets check the skewness of these distributions
"""
# check the skew of all numerical features
skew_check_col = ['views','likes','dislikes','comment']
skewed_feats = combined_df[skew_check_col].apply(lambda x : skew(x.dropna())).sort_values(ascending = False)
print('\n Skew in numberical features: \n')
skewness_df = pd.DataFrame({'Skew' : skewed_feats})
print(skewness_df.head(7))
for col in skew_check_col:
power = PowerTransformer(method='yeo-johnson', standardize=True)
combined_df[[col]] = power.fit_transform(combined_df[[col]]) # fit with combined_data to avoid overfitting with training data
print('Number of skewed numerical features got transform : ', len(skew_check_col))
"""### 5.7. Encoding Categorical Features
### Get-Dummies
"""
# Generate one-hot dummy columns
combined_df = pd.get_dummies(combined_df).reset_index(drop=True)
combined_df.head()
new_train_data = combined_df.iloc[:len(train_df), :]
new_test_data = combined_df.iloc[len(train_df):, :]
X_train = new_train_data.drop('adview', axis=1)
y_train = np.log1p(new_train_data['adview'].values.ravel())
X_test = new_test_data.drop('adview', axis=1)
# Make Pipeline
pre_precessing_pipeline = make_pipeline(RobustScaler())
X_train = pre_precessing_pipeline.fit_transform(X_train)
X_test = pre_precessing_pipeline.transform(X_test)
print(X_train.shape)
print(X_test.shape)
"""# **6. Model Development**
### 6.2. Hyperparameter Tuning using Optuna
"""
RANDOM_SEED = 23
# 10-fold CV
kfolds = KFold(n_splits=10, shuffle=True, random_state=RANDOM_SEED)
def tune(objective):
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100)
params = study.best_params
best_score = study.best_value
print(f"Best score: {best_score} \nOptimized parameters: {params}")
return params
"""### 6.3. Ridge Regression"""
def ridge_objective(trial):
_alpha = trial.suggest_float("alpha", 0.1, 20)
ridge = Ridge(alpha=_alpha, random_state=RANDOM_SEED)
score = cross_val_score(
ridge,X_train,y_train, cv=kfolds, scoring="neg_root_mean_squared_error"
).mean()
return score
# ridge_params = tune(ridge_objective)
# Best score: -1.898690687982798
ridge_params = {'alpha': 19.99855836300504}
ridge = Ridge(**ridge_params, random_state=RANDOM_SEED)
ridge.fit(X_train,y_train)
"""### 6.4. Lasso Regression"""
def lasso_objective(trial):
_alpha = trial.suggest_float("alpha", 0.0001, 1)
lasso = Lasso(alpha=_alpha, random_state=RANDOM_SEED)
score = cross_val_score(
lasso,X_train,y_train, cv=kfolds, scoring="neg_root_mean_squared_error"
).mean()
return score
# lasso_params = tune(lasso_objective)
# Best score: -1.8987548559962844
lasso_params = {'alpha': 0.0009661425571276957}
lasso = Lasso(**lasso_params, random_state=RANDOM_SEED)
lasso.fit(X_train,y_train)
"""### 6.5. Gradient Boosting Regressor"""
def gbr_objective(trial):
_n_estimators = trial.suggest_int("n_estimators", 50, 2000)
_learning_rate = trial.suggest_float("learning_rate", 0.01, 1)
_max_depth = trial.suggest_int("max_depth", 1, 20)
_min_samp_split = trial.suggest_int("min_samples_split", 2, 20)
_min_samples_leaf = trial.suggest_int("min_samples_leaf", 2, 20)
_max_features = trial.suggest_int("max_features", 10, 50)
gbr = GradientBoostingRegressor(
n_estimators=_n_estimators,
learning_rate=_learning_rate,
max_depth=_max_depth,
max_features=_max_features,
min_samples_leaf=_min_samples_leaf,
min_samples_split=_min_samp_split,
random_state=RANDOM_SEED,
)
score = cross_val_score(
gbr, X_train,y_train, cv=kfolds, scoring="neg_root_mean_squared_error"
).mean()
return score
# gbr_params = tune(gbr_objective)
# Best score: -1.8222372332051289
gbr_params = {'n_estimators': 1396, 'learning_rate': 0.014373145732630006, 'max_depth': 6, 'min_samples_split': 6, 'min_samples_leaf': 7, 'max_features': 10}
gbr = GradientBoostingRegressor(random_state=RANDOM_SEED, **gbr_params)
gbr.fit(X_train,y_train)
"""### 6.6. XGBRegressor """
def xgb_objective(trial):
_n_estimators = trial.suggest_int("n_estimators", 50, 2000)
_max_depth = trial.suggest_int("max_depth", 1, 20)
_learning_rate = trial.suggest_float("learning_rate", 0.01, 1)
_gamma = trial.suggest_float("gamma", 0.01, 1)
_min_child_weight = trial.suggest_float("min_child_weight", 0.1, 10)
_subsample = trial.suggest_float('subsample', 0.01, 1)
_reg_alpha = trial.suggest_float('reg_alpha', 0.01, 10)
_reg_lambda = trial.suggest_float('reg_lambda', 0.01, 10)
xgbr = xgb.XGBRegressor(
n_estimators=_n_estimators,
max_depth=_max_depth,
learning_rate=_learning_rate,
gamma=_gamma,
min_child_weight=_min_child_weight,
subsample=_subsample,
reg_alpha=_reg_alpha,
reg_lambda=_reg_lambda,
random_state=RANDOM_SEED,
)
score = cross_val_score(
xgbr, X_train,y_train, cv=kfolds, scoring="neg_root_mean_squared_error"
).mean()
return score
# xgb_params = tune(xgb_objective)
xgb_params = {'n_estimators': 75, 'max_depth': 4, 'learning_rate': 0.27059503805300894, 'gamma': 0.6375378736305962, 'min_child_weight': 3.2347222003450633, 'subsample': 0.8792064649951686, 'reg_alpha': 8.764034303437914, 'reg_lambda': 7.475836220328881}
# Best score : -1.8258592810003325.
xgbr = xgb.XGBRegressor(random_state=RANDOM_SEED, **xgb_params)
xgbr.fit(X_train,y_train)
"""### 6.7. LGBMRegressor"""
import lightgbm as lgb
def lgb_objective(trial):
_num_leaves = trial.suggest_int("num_leaves", 50, 100)
_max_depth = trial.suggest_int("max_depth", 1, 20)
_learning_rate = trial.suggest_float("learning_rate", 0.01, 1)
_n_estimators = trial.suggest_int("n_estimators", 50, 2000)
_min_child_weight = trial.suggest_float("min_child_weight", 0.1, 10)
_reg_alpha = trial.suggest_float('reg_alpha', 0.01, 10)
_reg_lambda = trial.suggest_float('reg_lambda', 0.01, 10)
_subsample = trial.suggest_float('subsample', 0.01, 1)
lgbr = lgb.LGBMRegressor(objective='regression',
num_leaves=_num_leaves,
max_depth=_max_depth,
learning_rate=_learning_rate,
n_estimators=_n_estimators,
min_child_weight=_min_child_weight,
subsample=_subsample,
reg_alpha=_reg_alpha,
reg_lambda=_reg_lambda,
random_state=RANDOM_SEED,
)
score = cross_val_score(
lgbr, X_train,y_train, cv=kfolds, scoring="neg_root_mean_squared_error"
).mean()
return score
# lgb_params = tune(lgb_objective)
# Best score: -1.824529794158143
lgb_params = {'num_leaves': 84, 'max_depth': 10, 'learning_rate': 0.011076909667786489, 'n_estimators': 727, 'min_child_weight': 4.921109754366219, 'reg_alpha': 4.370797996109474, 'reg_lambda': 8.552921079737136, 'subsample': 0.4411906869457217}
lgbr = lgb.LGBMRegressor(objective='regression', random_state=RANDOM_SEED, **lgb_params)
lgbr.fit(X_train,y_train)
"""### 6.8. StackingRegressor"""
# stack models
stack = StackingRegressor(
estimators=[
('ridge', ridge),
('lasso', lasso),
('gradientboostingregressor', gbr),
('xgb', xgbr),
('lgb', lgbr),
# ('svr', svr), # Not using this for now as its score is significantly worse than the others
],
cv=kfolds)
stack.fit(X_train,y_train)
"""### 6.9. Save the Model"""
joblib.dump(stack, "prediction_model.pkl")
model=joblib.load("prediction_model.pkl")
model
"""# **7. Find Prediction**"""
print('Predict submission')
final_test_df = pd.read_csv("/content/test.csv")
final_test_df['AdView'] = np.round(np.expm1(model.predict(X_test))).astype(int)
final_test_df.to_csv('submission_test.csv', index=False)
final_test_df.head()