In [1]:
# imports libraries
import pickle # import/export lists
import math # mathematical functions
import datetime # dates
import string
import re # regular expression
import pandas as pd # dataframes
import numpy as np # numerical computation
import matplotlib.pyplot as plt # plot graphics
import seaborn as sns # graphics supplemental
import statsmodels.formula.api as smf # statistical models
from statsmodels.stats.outliers_influence import (
variance_inflation_factor as vif) # vif
from nltk.corpus import stopwords
In [3]:
# opens cleaned data
with open ('../clean_data/df_story', 'rb') as fp:
df = pickle.load(fp)
In [4]:
# creates subset of data of online stories
df_online = df.loc[df.state == 'online', ].copy()
In [5]:
# sets current year
cyear = datetime.datetime.now().year
In [30]:
# sets stop word list for text parsing
stop_word_list = stopwords.words('english')
The success of a story is typically judged by the number of reviews, favorites, or followers it recieves. Here, we will try to predict how successful a story will be given select observable features, as well as develop a way to benchmark existing stories. That is, if we were given a story's features, we can determine whether that story is overperforming or underperforming relative to its peers.
First and foremost, let us examine the distribution of each of these "success" metrics.
In [45]:
# examines distribution of number of words
df_online['reviews'].fillna(0).plot.hist(normed=True,
bins=np.arange(0, 50, 1), alpha=0.5, histtype='step', linewidth='2')
df_online['favs'].fillna(0).plot.hist(normed=True,
bins=np.arange(0, 50, 1), alpha=0.5, histtype='step', linewidth='2')
df_online['follows'].fillna(0).plot.hist(normed=True,
bins=np.arange(0, 50, 1), alpha=0.5, histtype='step', linewidth='2')
plt.xlim(0,50)
plt.legend().set_visible(True)
plt.show()
As expected, reviews, favorites, and follows all have heavily right-skewing distributions. However, there are also differences. A story is mostly likely to have 1 or 2 reviews, not 0. A story is mostly likely to have 0 favorites, but otherwise the favorites distribution looks very similar to reviews. Follows is the one that deviates the most. About one-fourth of stories have 0 or 1 follows.
We assumed authors prefer having reviews first and foremost, then favorites, then follows. The data reveals that it is actually follows that is the most "rare" out of the three metrics, then favorites, and finally review.
This is accordance with intuition. Anyone can sign a review, with or without an account. Only users with accounts can increase a story's favorite counter. Finally, follows are the most "hassling", as they send update messages to a follower's email inbox. Consequently, they are the least common.
In [14]:
df_online.columns.values
Out[14]:
In [46]:
# creates regressand variables
df_online['ratedM'] = [row == 'M' for row in df_online['rated']]
df_online['age'] = [cyear - int(row) for row in df_online['pub_year']]
df_online['fansize'] = [fandom[row] for row in df_online['fandom']]
df_online['complete'] = [row == 'Complete' for row in df_online['status']]
df_online['lnchapters'] = np.log(df_online['chapters'])
In [47]:
# creates independent variables
df_online['lnreviews'] = np.log(df_online['reviews']+1)
df_online['lnfavs'] = np.log(df_online['favs']+1)
df_online['lnfollows'] = np.log(df_online['follows']+1)
In [59]:
df_online['lnfavs'] = np.log(df_online['favs']+1)
sns.pairplot(data=df_online, y_vars=['lnfavs'], x_vars=['lnchapters', 'lnwords1k', 'age'])
sns.pairplot(data=df_online, y_vars=['favs'], x_vars=['chapters', 'words', 'age'])
plt.show()
In [56]:
sns.pairplot(data=df_online, y_vars=['lnreviews'], x_vars=['lnchapters', 'lnwords1k', 'age'])
sns.pairplot(data=df_online, y_vars=['reviews'], x_vars=['chapters', 'words', 'age'])
plt.show()
In [66]:
# runs OLS regression
formula = 'reviews ~ chapters + words1k + ratedM + age + fansize + complete'
reg = smf.ols(data=df_online, formula=formula).fit()
print(reg.summary())
In [67]:
# runs OLS regression
formula = 'lnreviews ~ lnchapters + lnwords1k + ratedM + age + fansize + complete'
reg = smf.ols(data=df_online, formula=formula).fit()
print(reg.summary())
In [64]:
# runs OLS regression
formula = 'lnfavs ~ lnchapters + lnwords1k + ratedM + age + fansize'
reg = smf.ols(data=df_online, formula=formula).fit()
print(reg.summary())
In [32]:
# creates copy of only active users
df_active = df_profile.loc[df_profile.status != 'inactive', ].copy()
# creates age variable
df_active['age'] = 17 - pd.to_numeric(df_active['join_year'])
df_active.loc[df_active.age < 0, 'age'] = df_active.loc[df_active.age < 0, 'age'] + 100
df_active = df_active[['st', 'fa', 'fs', 'cc', 'age']]
# turns cc into binary
df_active.loc[df_active['cc'] > 0, 'cc'] = 1
In [33]:
# displays correlation matrix
df_active.corr()
Out[33]:
In [34]:
# creates design_matrix
X = df_active
X['intercept'] = 1
# displays variance inflation factor
vif_results = pd.DataFrame()
vif_results['VIF Factor'] = [vif(X.values, i) for i in range(X.shape[1])]
vif_results['features'] = X.columns
vif_results
Out[34]:
Results indicate there is some correlation between two of the independent variables: 'fa' and 'fs', implying one of them may not be necessary in the model.
We know from earlier distributions that some of the variables are heavily right-skewed. We created some scatter plots to confirm that the assumption of linearity holds.
The data is clustered around the zeros. Let's try a log transformation.
In [47]:
# runs OLS regression
formula = 'st ~ fa + fs + cc + age'
reg = smf.ols(data=df_active, formula=formula).fit()
print(reg.summary())
The log transformations helped increase the fit from and R-squared of ~0.05 to ~0.20.
From these results, we can see that:
We noted earlier that 'fa' and 'fs' had a correlation of ~0.7. As such, we reran the regression without 'fa' first, then again without 'fs'. The model without 'fs' yielded a better fit (R-squared), as well as AIC and BIC.
In [48]:
# runs OLS regression
formula = 'st ~ fa + cc + age'
reg = smf.ols(data=df_active, formula=formula).fit()
print(reg.summary())
Without 'fs', we lost some information but not much:
All these results seem to confirm a basic intuition that the more active an user reads (as measured by favoriting authors and stories), the likely it is that user will write more stories. Being longer on the site and being part of a community is also correlated to publications.
To get a sense of the actual magnitude of these effects, let's attempt some plots:
In [99]:
def graph(formula, x_range):
y = np.array(x_range)
x = formula(y)
plt.plot(y,x)
graph(lambda x : (np.exp(reg.params[0]+reg.params[1]*(np.log(x-1)))),
range(2,100,1))
graph(lambda x : (np.exp(reg.params[0]+reg.params[1]*(np.log(x-1))+reg.params[2])),
range(2,100,1))
plt.show()
In [98]:
ages = [0, 1, 5, 10, 15]
for age in ages:
graph(lambda x : (np.exp(reg.params[0]+reg.params[1]*(np.log(x-1))+reg.params[3]*age)),
range(2,100,1))
plt.show()