Use on your local machine!
Example 1)
import csv
import os
def fix_turnstile_data(filenames):
#filenames is supposed to be a list of filenames
'''
Filenames is a list of MTA Subway turnstile text files. A link
to an example MTA Subway turnstile text file can be seen at the URL below:
http://web.mta.info/developers/data/nyct/turnstile/turnstile_110507.txt
As you can see, there are numerous data points included in each row of the
a MTA Subway turnstile text file.
You want to write a function that will update each row in the text
file so there is only one entry per row. A few examples below:
A002,R051,02-00-00,05-28-11,00:00:00,REGULAR,003178521,001100739
A002,R051,02-00-00,05-28-11,04:00:00,REGULAR,003178541,001100746
A002,R051,02-00-00,05-28-11,08:00:00,REGULAR,003178559,001100775
Write the updates to a different text file in the format of
"updated_" + filename.
For example:
1) if you read in a text file called "turnstile_110521.txt"
2) you should write the updated data to "updated_turnstile_110521.txt"
The order of the fields should be preserved.
You can see a sample of the turnstile text file that's passed into this function
and the the corresponding updated file in the links below:
Sample input file:
https://www.dropbox.com/s/mpin5zv4hgrx244/turnstile_110528.txt
Sample updated file:
https://www.dropbox.com/s/074xbgio4c39b7h/solution_turnstile_110528.txt
'''
for name in filenames:
outgoing_filename = "alternative_updated_" + name
path = r' ... select your path to input and output files ...'
g = open(os.path.join(path, outgoing_filename), 'w')
outgoing_file = csv.writer(g)
with open(os.path.join(path, name), 'rb') as f:
reader = csv.reader(f)
for row in reader:
i = 0
initial = row[:3]
while row[3+i:3+i+5]:
outgoing_file.writerow(initial + row[3+i:3+i+5])
i = i + 5
filenames = ['turnstile_110528.txt', 'turnstile_110529.txt']
fix_turnstile_data(filenames)
Example 2:
# -*- coding: utf-8 -*-
import os
import csv
import re
def create_master_turnstile_file(filenames, output_file):
'''
Write a function that takes the files in the list filenames, which all have the
columns 'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn', and consolidates
them into one file located at output_file. There should be ONE row with the column
headers, located at the top of the file.
For example, if file_1 has:
'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn'
line 1 ...
line 2 ...
and another file, file_2 has:
'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn'
line 3 ...
line 4 ...
line 5 ...
We need to combine file_1 and file_2 into a master_file like below:
'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn'
line 1 ...
line 2 ...
line 3 ...
line 4 ...
line 5 ...
'''
path = r' ...path to location for input and output files ...'
with open(os.path.join(path, output_file), 'w') as master_file:
master_file.write('C/A,UNIT,SCP,DATEn,TIMEn,DESCn,ENTRIESn,EXITSn\n')
for filename in filenames:
master_file.write(re.sub('C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn', '', ''.join(open(os.path.join(path, filename), "rb").readlines())))
create_master_turnstile_file([ 'file_2.txt', 'file_3.txt'], 'output_file.txt')
The Stats Are Not What They Seem
Mittwoch, 21. Oktober 2015
Samstag, 3. Oktober 2015
Project 1: NYC Subway Ridership and Weather
Font colors:
black: Udacity final project questionnaire
blue: my answers
red: selected code examples.
WARNING: the code can be applied to the turnstile_data_master_with_weather.csv right away on your local machine but will display results different from the discussion below. This is because Udacity provided a manipulated master file (a smaller "randomly chosen subset" as they said) at their UI, not visible for the user, containing only ~15% of the data contained in the original master file.
black: Udacity final project questionnaire
blue: my answers
red: selected code examples.
WARNING: the code can be applied to the turnstile_data_master_with_weather.csv right away on your local machine but will display results different from the discussion below. This is because Udacity provided a manipulated master file (a smaller "randomly chosen subset" as they said) at their UI, not visible for the user, containing only ~15% of the data contained in the original master file.
Short Questions to Analyzing the NYC Subway Dataset
Section 0. References
Section 1. Statistical Test
Section 2. Linear Regression
Section 3. Visualization
Section 4. Conclusion
Section 5. Reflection
Section 0. References
Please include a list of references you have used for this project. Please be specific - for example, instead of including a general website such as stackoverflow.com, try to include a specific topic from Stackoverflow that you have found useful.
• „Python for Data Analysis“ (1st ed.), Wes McKinney, O'Reilly, 2013:
- Chapter 4: NumPy Basics
- Chapter 5: Getting Started with pandas
- Chapter 6: Data Loading, Storage, and File Formats
- Chapter 8: Plotting and Visualization
- Chapter 9: Data Aggregation and Group Operations
• „Python 3“ (3rd ed.), Ernesti, Johannes; Kaiser, Peter, Galileo Computing, 2012
- Chapter 24.3.1: Überblick über den Datentyp numpy.ndarray (Overview of the Datatype
numpy.ndarray)
• „Street-Smart Stats – A Friendly Introduction to Statistical Research Methods“, Katie
Kormanik, http://www.amazon.com/Street-Smart-Stats-Friendly-Introduction-
Statistical/dp/1500872105
- Lesson 9: Hypothesis Testing
• Equally distributed bins for matplotlib histograms:
http://stackoverflow.com/questions/6986986/bin-size-in-matplotlib-histogram
• The Mann-Whitney-U Test:
- https://www.youtube.com/watch?v=LnfPKGhJypU#
- „MannWhitneyUTest“ in Downloadables from https://www.udacity.com/course/viewer#!/cud359/
l-649959144/m-750618549
• Residuals VS Fits Plot
- http://www.itl.nist.gov/div898/handbook/pri/section2/pri24.htm
Section 1. Statistical Test
1.1 Which statistical test did you use to analyze the NYC subway data? Did you use a one-tail or
a two-tail P value? What is the null hypothesis? What is your p-critical value?
a two-tail P value? What is the null hypothesis? What is your p-critical value?
• I used the the Mann-Whitney U test of the scipy.stats implementation, 2-tailed.
• Null Hypothesis: Let X be the population of turnstile entries on non-rainy days and Y be the
population of turnstile entries on rainy days;
H0: P(x>y) = 0.5 for each random draw x from X and y from Y .
• The p-critical value is set to 0.05.
1.2 Why is this statistical test applicable to the dataset? In particular, consider the assumptions
that the test is making about the distribution of ridership in the two samples.
that the test is making about the distribution of ridership in the two samples.
The Mann-Whitney U test assumes 2 independent samples of ordinal (or interval) datatype. The
turnstile dataset fulfills both conditions.
The Mann-Whitney U does not assume the sample data is drawn from any particular known
underlying distribution or that the samples are of equal size or variance.
1.3 What results did you get from this statistical test? These should include the following
numerical values: p-values, as well as the means for each of the two samples under test.
Results:
numerical values: p-values, as well as the means for each of the two samples under test.
Results:
1. average number of turnstile entries where 'rain'=1: 1105.45;
2. average number of turnstile entries where 'rain'=0: 1090.28;
3. Mann-Whitney statistic U = 1924409167.0
4. 1-sided p-value p: 0.024999912793489721
1.4 What is the significance and interpretation of these results?
According to the scipy.stats implementation, the obtained 1-sided p value p = 0.024999912793489721 has to be multiplied by 2 in order to compare it with our p-critical value of 0.5. This gives us p = 0.04999982558697944 and since p<0.05, we reject H0.
Meaning: p is the probability of obtaining the Mann-Whitney U test statistic of at most U =
1924409167.0, given H0 is true. This probability is less than 0.05. This means that even if there were no difference between entries on rainy days and entries on non-rainy days, we would see a value of U equal or greater than 1924409167.0 in 5% of the times.
Section 2. Linear Regression
2.1 What approach did you use to compute the coefficients theta and produce prediction for ENTRIESn_hourly in your regression model:
1. OLS using Statsmodels or Scikit Learn
2. Gradient descent using Scikit Learn
3. Or something different?
2. Gradient descent using Scikit Learn
3. Or something different?
Linear regression with gradient descent using pandas and numpy.
import numpy as np
print(compute_r_squared(df['ENTRIESn_hourly'],predictions(df)))
import numpy as np
import pandas
from pandas import Series
from dateutil.parser import parse
from problem7_R2 import compute_r_squared # this module contains the code shown in Section 2.5 below
def normalize_features(df):
"""
Normalize the features in the data set.
"""
mu = df.mean()
sigma = df.std()
if (sigma == 0).any():
raise Exception("One or more features had the same value for all samples, and thus could " + \
"not be normalized. Please do not include features with only a single value " + \
"in your model.")
df_normalized = (df - df.mean()) / df.std()
return df_normalized, mu, sigma
def compute_cost(features, values, theta):
"""
Compute the cost function given a set of features / values,
and the values for our thetas.
"""
m = len(values)
sum_of_square_errors = np.square(np.dot(features, theta) - values).sum()
cost = sum_of_square_errors / (2*m)
return cost
def gradient_descent(features, values, theta, alpha, num_iterations):
"""
Perform gradient descent given a data set with an arbitrary number of features.
"""
m = len(values)
cost_history = []
for i in range(num_iterations):
predicted_values = np.dot(features, theta)
theta = theta + ( (alpha / m) * np.dot((values - predicted_values), features) )
cost_history.append(compute_cost(features, values, theta))
return theta, pandas.Series(cost_history)
def predictions(dataframe):
'''
The NYC turnstile data is stored in a pandas dataframe called weather_turnstile. Using the information stored in the dataframe, let's predict the ridership of the NYC subway using linear regression with gradient descent. You can download the complete turnstile weather dataframe here:
https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv
Your prediction should have a R^2 value of 0.40 or better. You need to experiment using various input features contained in the dataframe. We recommend that you don't use the EXITSn_hourly feature as an input to the linear model because we cannot use it as a predictor: we cannot use exits counts as a way to predict entry counts.
'''
#Selection of features
features = dataframe[['Hour','meanpressurei', 'maxdewpti', 'rain', 'fog']]
#Adding dayofweek to features using dummy variables
dataframe['dayofweek'] = Series(parse(x).strftime('%a') for x in dataframe['DATEn'])
dummy_dayofweek = pandas.get_dummies(dataframe['dayofweek'])
features = features.join(dummy_dayofweek)
# Add UNIT to features using dummy variables
dummy_units = pandas.get_dummies(dataframe['UNIT'], prefix='unit')
features = features.join(dummy_units)
# Values
values = dataframe['ENTRIESn_hourly']
m = len(values)
features, mu, sigma = normalize_features(features)
features['ones'] = np.ones(m) # Add a column of 1s (y intercept)
# Convert features and values to numpy arrays
features_array = np.array(features)
values_array = np.array(values)
# Set values for alpha, number of iterations.
alpha = 0.1 # please feel free to change this value
num_iterations = 50 # please feel free to change this value
# Initialize theta, perform gradient descent
theta_gradient_descent = np.zeros(len(features.columns))
theta_gradient_descent, cost_history = gradient_descent(features_array,
values_array,
theta_gradient_descent,
alpha,
num_iterations)
predictions = np.dot(features_array, theta_gradient_descent)
return predictions
file = = r" ... /turnstile_data_master_with_weather.csv"
df= pandas.read_csv(file)
print(compute_r_squared(df['ENTRIESn_hourly'],predictions(df)))
2.2 What features (input variables) did you use in your model? Did you use any dummy variables as part of your features?
I accepted the predefined dummy variable 'UNIT' and I also added another dummy variable
'dayofweek'. Finally, I added 'Hour', 'meanpressurei', 'maxdewpti', 'rain' and 'fog' to the list of features.
2.3 Why did you select these features in your model? We are looking for specific reasons that
lead you to believe that the selected features will contribute to the predictive power of your model.
• Your reasons might be based on intuition. For example, response for fog might be: “Idecided to use fog because I thought that when it is very foggy outside people might decideto use the subway more often.”• Your reasons might also be based on data exploration and experimentation, for example: “I used feature X because as soon as I included it in my model, it drastically improved my R2 value.”
lead you to believe that the selected features will contribute to the predictive power of your model.
• Your reasons might be based on intuition. For example, response for fog might be: “Idecided to use fog because I thought that when it is very foggy outside people might decideto use the subway more often.”• Your reasons might also be based on data exploration and experimentation, for example: “I used feature X because as soon as I included it in my model, it drastically improved my R2 value.”
I accepted the predefined UNIT dummy variable because it provided the largest increase of the R2
value (0.425) which I could find during my experimentation. Other groups of features did not show
that strong impact on R2.
As for the 'dayofweek' dummy, my intuition was that weather based decisions to use the subway may differ significantly on weekends compared to normal working days.
In order to further boost my R2 I proceeded by searching for features with a broad variability in comparison to 'UNIT' and 'dayofweek' but this is easier said than done. So the method was rather
trial and error. Finally, I chose 'Hour' and the weather-related features ' meanpressurei', 'maxdewpti', 'rain', and 'fog'.
2.4 What are the parameters (also known as "coefficients" or "weights") of the non-dummy
features in your linear regression model?
features in your linear regression model?
Starting the regression with alpha = 0.1 and num_iterations = 50 on the random subset provided, I
obtained the following non-dummy coefficients:
'Hour': 4.63757966e+02
'meanpressurei': -2.64689006e+01
'maxdewpti': -4.89940069e+01
'rain': -1.27974911e+01
'fog': 4.94588410e+01
2.5 What is your model’s R2 (coefficients of determination) value?
R2 = 0.476546529828
import numpy as np
def compute_r_squared(data, predictions):
'''
Given a list of original data points, and also a list of predicted data points,
this function will compute and return the coefficient of determination (R^2)
for this data.
'''
nominator = np.square((data - predictions)).sum()
denominator = np.square(data - data.mean()).sum()
r_squared = 1.0 - (nominator/denominator)
return r_squared
2.6 What does this R2 value mean for the goodness of fit for your regression model? Do you think this linear model to predict ridership is appropriate for this dataset, given this R2 value?
Let v1 be the variance of the residuals around the regression line and let v2 be the overall variance (in our case: the variance of turnstile entries). The following formula was used to compute R2:
R2 = 1 – (v1/v2)
Meaning1: R2 gives a measure of how well the regression line of a model fits the data. If v1=0 (the
predicted values match the data perfectly), then R2=1. In the worst case v1=v2 (there is no
relationship between the independent variables and the output variable) and therefore R2=0. Since an R2 of 0.48 falls approximately in the middle of [0,1], there could be worse fits, but also better ones, e.g. obtainable by just adding more and more regressors (at the cost of more complicated models).
Meaning2: v1 is called „the unexplained variation“. Since v1 = v2*(1-R2) and given R2 as above,
one can therefore conclude that the given model has explained around 0.48% of the overall
variation of observed turnstile entries and left unexplained 0.52%.
Appropriateness:
Multiple regression assumes that the the residuals are normally distributed. One way to check this
assumption is to plot the residuals. While a histogram of the residuals shows a long-legged Bell
curve centered around 0 suggesting normality, I have chosen to do a „Residuals Vs Fits“ plot:
Interpretation: The higher the output variable, the higher the residual error. This implies a pattern
where the residuals should be randomly distributed about 0. Hence, the assumption of normality
does not seem to be fulfilled. Further analysis is needed to check normality conclusively. So I'm
not sure if the model can be called appropriate.
the NYC subway data.
Remember to add appropriate titles and axes labels to your plots. Also, please add a short
description below each figure commenting on the key insights depicted in the figure.
3.1 One visualization should contain two histograms: one of ENTRIESn_hourly for rainy days
and one of ENTRIESn_hourly for non-rainy days.
• You can combine the two histograms in a single plot or you can use two separate plots.
• If you decide to use to two separate plots for the two histograms, please ensure that the xaxis
limits for both of the plots are identical. It is much easier to compare the two in that
case.
• For the histograms, you should have intervals representing the volume of ridership (value of
ENTRIESn_hourly) on the x-axis and the frequency of occurrence on the y-axis. For
example, each interval (along the x-axis), the height of the bar for this interval will represent
the number of records (rows in our data) that have ENTRIESn_hourly that falls in this
interval.
• Remember to increase the number of bins in the histogram (by having larger number of
bars). The default bin width is not sufficient to capture the variability in the two samples.
import numpy as np
import pandas
import matplotlib.pyplot as plt
def entries_histogram(turnstile_weather):
fig = plt.figure(); ax = fig.add_subplot(1,1,1)
ax.set_xlim([0,4000])
ax.set_ylim([0,50000])
no_rain = list(turnstile_weather["ENTRIESn_hourly"][turnstile_weather["rain"] == 0])
ax.hist(no_rain,color='y',bins=np.arange(min(no_rain), max(no_rain) + 250, 250),label='no rain')
rain = list(turnstile_weather["ENTRIESn_hourly"][turnstile_weather["rain"] == 1])
ax.hist(rain,color='b',bins=np.arange(min(rain), max(rain) + 250, 250),label='rain')
ax.set_title('Comparison of Entries on Rainy and Non-Rainy Days')
ax.set_xlabel('Volume of Ridership (bin size = 250)')
ax.set_ylabel('Frequency')
ax.legend(loc='best')
return fig
file = r“(... turnstile_data_master_with_weather.csv“)
turnstile_weather = pandas.read_csv(file)
entries_histogram(turnstile_weather)
Note that the 'Entries_hourly' column contained the cumulative sum of the last 4 hours for a given turnstile unit. Each day was thus partitioned into 6 intervals. The histogram counts the number of occurrences of these entries per bin (binsize=250). Thus, there are more than 40k entries in the column smaller than 250 (lots of them equal to 0).
I'd like to further comment that this histogram might be easily misinterpreted by concluding that there are far more entries during rainy days than during non-rainy days. This is not the case: since there were twice as many non-rainy days (20) than rainy days (10) and the bar height ratios of both groups appear to be roughly constant, the above histogram is better interpreted by mentally dividing the absolute frequency of non-rainy days by 2, thus roughly equalling the absolute frequency of rainy days. Equivalently, a histogram of relative frequency would show that the difference between the two groups is small (by comparing the results of each class interval to the total number of entries). This is confirmed by the small difference between the average numbers mentioned in Section 1.3.
The only purpose of plotting such a histogram is to get some hint about the nature of the distribution of data. In this case, the data distribution does not appear to be normal which suggests to continue the investigation with non-parametric tools.
3.2 One visualization can be more freeform. You should feel free to implement something that we discussed in class (e.g., scatter plots, line plots) or attempt to implement something more advanced if you'd like. Some suggestions are:
• Ridership by time-of-day
• Ridership by day-of-week
Interpretation: The higher the output variable, the higher the residual error. This implies a pattern
where the residuals should be randomly distributed about 0. Hence, the assumption of normality
does not seem to be fulfilled. Further analysis is needed to check normality conclusively. So I'm
not sure if the model can be called appropriate.
Section 3. Visualization
Please include two visualizations that show the relationships between two or more variables inthe NYC subway data.
Remember to add appropriate titles and axes labels to your plots. Also, please add a short
description below each figure commenting on the key insights depicted in the figure.
3.1 One visualization should contain two histograms: one of ENTRIESn_hourly for rainy days
and one of ENTRIESn_hourly for non-rainy days.
• You can combine the two histograms in a single plot or you can use two separate plots.
• If you decide to use to two separate plots for the two histograms, please ensure that the xaxis
limits for both of the plots are identical. It is much easier to compare the two in that
case.
• For the histograms, you should have intervals representing the volume of ridership (value of
ENTRIESn_hourly) on the x-axis and the frequency of occurrence on the y-axis. For
example, each interval (along the x-axis), the height of the bar for this interval will represent
the number of records (rows in our data) that have ENTRIESn_hourly that falls in this
interval.
• Remember to increase the number of bins in the histogram (by having larger number of
bars). The default bin width is not sufficient to capture the variability in the two samples.
import numpy as np
import pandas
import matplotlib.pyplot as plt
def entries_histogram(turnstile_weather):
fig = plt.figure(); ax = fig.add_subplot(1,1,1)
ax.set_xlim([0,4000])
ax.set_ylim([0,50000])
no_rain = list(turnstile_weather["ENTRIESn_hourly"][turnstile_weather["rain"] == 0])
ax.hist(no_rain,color='y',bins=np.arange(min(no_rain), max(no_rain) + 250, 250),label='no rain')
rain = list(turnstile_weather["ENTRIESn_hourly"][turnstile_weather["rain"] == 1])
ax.hist(rain,color='b',bins=np.arange(min(rain), max(rain) + 250, 250),label='rain')
ax.set_title('Comparison of Entries on Rainy and Non-Rainy Days')
ax.set_xlabel('Volume of Ridership (bin size = 250)')
ax.set_ylabel('Frequency')
ax.legend(loc='best')
return fig
file = r“(... turnstile_data_master_with_weather.csv“)
turnstile_weather = pandas.read_csv(file)
entries_histogram(turnstile_weather)
Note that the 'Entries_hourly' column contained the cumulative sum of the last 4 hours for a given turnstile unit. Each day was thus partitioned into 6 intervals. The histogram counts the number of occurrences of these entries per bin (binsize=250). Thus, there are more than 40k entries in the column smaller than 250 (lots of them equal to 0).
I'd like to further comment that this histogram might be easily misinterpreted by concluding that there are far more entries during rainy days than during non-rainy days. This is not the case: since there were twice as many non-rainy days (20) than rainy days (10) and the bar height ratios of both groups appear to be roughly constant, the above histogram is better interpreted by mentally dividing the absolute frequency of non-rainy days by 2, thus roughly equalling the absolute frequency of rainy days. Equivalently, a histogram of relative frequency would show that the difference between the two groups is small (by comparing the results of each class interval to the total number of entries). This is confirmed by the small difference between the average numbers mentioned in Section 1.3.
The only purpose of plotting such a histogram is to get some hint about the nature of the distribution of data. In this case, the data distribution does not appear to be normal which suggests to continue the investigation with non-parametric tools.
3.2 One visualization can be more freeform. You should feel free to implement something that we discussed in class (e.g., scatter plots, line plots) or attempt to implement something more advanced if you'd like. Some suggestions are:
• Ridership by time-of-day
• Ridership by day-of-week
from pandas import *
from ggplot import *
filename = r'.../turnstile_data_master_with_weather.csv'
with open(filename,'rb') as df:
df = pandas.read_csv(filename)
grouped = df['ENTRIESn_hourly'].groupby(df['Hour'])
result = grouped.agg(['mean'])
gg = ggplot(result.reset_index(), aes(x='Hour',y='mean')) + \
geom_point(stat = "identity") + geom_line(color='blue') +\
xlab("Hours of the Day") + xlim(-0.5,24.5) + ylim(0,3000) + ylab('Means')+\
ggtitle('''Average Number of N.Y. Subway Turnstile Entries per Hour of the Day (May 2011)''')
print(gg)
Like with other time granularities on the X-axis (month,week,day) the above line plot shows a specifc pattern. But in contrast to week or day, the 'hour'-plot is very problematic. The peak values at noon and 20:00 are somewhat surprising since one would expect rush hours to be peaks. This surprise can be explained by the cumulative way of counting entries displayed in the 'Entries_hourly' column, mentioned above. Thus, one can only guess where exactly within the 4 hour interval before noon and 20:00 respectively the real peaks are to be located (if any). Since this undetermined „backwards shift in time“ applies to all points of the line plot, the analytic value of the above plot can be considered low.
Section 4. Conclusion
Please address the following questions in detail. Your answers should be 1-2 paragraphs long.4.1 From your analysis and interpretation of the data, do more people ride the NYC
subway when it is raining or when it is not raining?
Data rather inconclusive: There are slightly more turnstile entries on rainy days than on non-rainy days. The difference is statistically significant at a significance level of 0.05, though the decision is very tight. It might be uncertain whether this result will lead to practical consequences.
4.2 What analyses lead you to this conclusion? You should use results from both your statistical
tests and your linear regression to support your analysis.
First I observed the average numbers of turnstile entries:
rain mean
0 1090.278780
1 1105.446377
The difference appears to be relatively small. The histogram in Section 3 indicates that the data is not normally distributed. Thus proceeding with parameter-free tools would be promising. I ran the Mann-Whitney U-test for comparing both groups. The obtained p-value was only very slightly smaller than the p-critical value of 0.05, but enough to reject the Null Hypotesis.
A linear regression model showed that adding several weather features has indeed some small impact on the goodness of fit of the model for predicting future turnstile data.
On the other hand, a non-weather related variable like „UNIT“ has far greater impact on the coefficient of determination: R2=0.425036652566 if the only variable is „UNIT“.
Given the small amount of data (month of May, 2011), it can be doubted whether this tight result might lead to practical consequences. Rain might have a different impact on ridership depending on the season of the year and data of one month only is clearly not representative.
Section 5. Reflection
Please address the following questions in detail. Your answers should be 1-2 paragraphs long.
5.1 Please discuss potential shortcomings of the methods of your analysis, including:
1. Dataset,
- Data from 1 month only is not representative.
- Granularity: Merging the subway data with a weather table on a daily basis may be not accurate enough. Decisions to enter the subway because of weather conditions may be based partly on momentary conditions (but also on the weather forecast).
- Cumulative Counts: The cumulative sum of entries of the last four hours as presented in the „ENTRIESn_hourly“ column may cause problems in finding certain key values like maximum or minimum number of entries per hour (as mentioned in Section 3.2). In connection with the granularity problem mentioned above, it would be desireable to have a 1-1 correspondence between hourly weather data and hourly number of entries.
- Additional demographic and geographical details would be helpful, e.g. different demographic groups of the City of New York could be set in relation to certain areas containing certain subway units.
2. Analysis, such as the linear regression model or statistical test.
- It is questionable whether the linear regression model used is the best way of analyzing a possible correlation of weather and subway entries. The greatest part of the coefficient of determination R2 does not come from weather related features but from the dummy variable „UNIT“.
- Further examinations are needed to check conclusively whether all assumptions for linear regression are fulfilled (e.g. normality assumption for the residuals).
5.2 (Optional) Do you have any other insight about the dataset that you would like to share with
us?
Freitag, 2. Oktober 2015
Project 1: NYC Subway Ridership and Weather (Short Description with Links)
NYC Subway Ridership and Weather (Short Description)
"Project 1" is my final project for Udacity's course "Intro To Data Science". Here I present a short project description with links included.
------------------------------------Project Description----------------------------------------
The project consisted essentially of three parts. Given weather data (weather_underground.csv) and NYC subway data (like turnstile_110528.txt), perform
1) Data Wrangling
for producing a master file (turnstile_data_master_with_weather.csv) on which the following investigations are based:
2) Descriptive Statistics and Data Visualization
3) Data Analysis
with particular regard to the question: Do more people ride the NYC subway when it is raining or when it is not raining?
------------------------------------Project Description----------------------------------------
While the data wrangling was done in Section 2 of the course, the final project submission concentrated on parts 2 and 3. Some wrangling code can be seen HERE. The final project submission, slightly changed and extended by code examples, can be accessed HERE!
Labels:
Data Analysis,
Data Science,
Data Visualization,
Data Wrangling,
Descriptive Statistics,
Intro to Data Science,
NYC Subway Data,
Udacity,
Weather Data
Udacity Course 359 "Intro To Data Science" (Syllabus)
On September 10, I finished Udacity's Intro To Data Science course. Here I present a slightly altered and augmented syllabus of the course.
Introduction to Data Science
What is a Data Scientist
Pi-Chaun (Data Scientist @ Google): What is Data Science?
Simpson's Paradox
Intro to Numpy
Problems Solved by Data Science
Intro to Pandas
Dataframes
Exercises: Sotchi Olympic Medal Count
Pandas Vectorized Methods
Matrix Multiplication and Numpy Dot
Problem Set 1: Titanic Survivor Data
(http://www.kaggle.com/c/titanic-gettingStarted/data)
What is Data Wrangling?
Acquiring Data
Common Data Formats
CSV Data
What are Relational Databases?
Aadhaar Data
Aadhaar Data and Relational Databases
Introduction to Databases Schemas
Database Queries Using Pandas and SQLite
API’s
Data in JSON Format
How to Access an API efficiently
Missing Values
Easy Imputation
Impute using Linear Regression
Tip of the Imputation Iceberg
Problem Set 2: Wrangling Subway Data
Pandasql queries on Weather Data
Reformatting, Combining, Filtering New York Subway Data
Statistical Rigor
Kurt (Data Scientist @ Twitter) - Why is Stats Useful?
Introduction to Normal Distribution
T Test
Welch T Test
Exercise: Welch's T-Test in Python on Baseball Data (left-handed vs right-handed hitters)
Non-Parametric Tests
Non-Normal Data
Stats vs. Machine Learning
Different Types of Machine Learning
Prediction with Regression
Linear Regression with Gradient Descent
Cost Function
How to Minimize Cost Function
Coefficients of Determination
Other Considerations
Problem Set 3: Analyzing Subway Data
Histogram: Entries on Rainy Vs Entries on non-Rainy Days
Is Welch's T-Test Applicable?
Mann-Whitney U-Test (Entries on Rainy and Non-Rainy Days)
Linear Regression with Gradient Descent on Subway Data
Plotting Residuals
Compute R²
OLS Regression Using Python Module StatsModels (Optional)
Effective Information Visualization
Napoleon's March on Russia
Don (Principal Data Scientist @ AT&T): Communicating Findings
Rishiraj (Principal Data Scientist @ AT&T): Communicating Findings Well
Visual Encodings
Perception of Visual Cues
Plotting in Python (Intro to GGPLOT)
Data Types
Data Scales
Visualizing Time Series Data
Plots (Scatter, Line Charts, Loess Curve, Multivariate Data)
Problem Set 4: Visualizing Subway Data
Using Python and GGPLOT for plotting
- Ridership by time of day or day of week
- How ridership varies based on Subway station (UNIT)
- Which stations have more exits or entries at different times of day
Big Data and the MapReduce Programming Model
Basics of the MapReduce Programming Model
Mapper
Reducer
MapReduce with Aadhaar Data
MapReduce with Subway Data
Problem Set 5: MapReduce on Subway Data
Ridership per Station
Ridersip by Weather Type
Busiest Hour
- Lesson 1: Introduction to Data Science
Introduction to Data Science
What is a Data Scientist
Pi-Chaun (Data Scientist @ Google): What is Data Science?
Simpson's Paradox
Intro to Numpy
Problems Solved by Data Science
Intro to Pandas
Dataframes
Exercises: Sotchi Olympic Medal Count
Pandas Vectorized Methods
Matrix Multiplication and Numpy Dot
Problem Set 1: Titanic Survivor Data
(http://www.kaggle.com/c/titanic-gettingStarted/data)
- Lesson 2: Data Wrangling
What is Data Wrangling?
Acquiring Data
Common Data Formats
CSV Data
What are Relational Databases?
Aadhaar Data
Aadhaar Data and Relational Databases
Introduction to Databases Schemas
Database Queries Using Pandas and SQLite
API’s
Data in JSON Format
How to Access an API efficiently
Missing Values
Easy Imputation
Impute using Linear Regression
Tip of the Imputation Iceberg
Problem Set 2: Wrangling Subway Data
Pandasql queries on Weather Data
Reformatting, Combining, Filtering New York Subway Data
- Lesson 3: Data Analysis
Statistical Rigor
Kurt (Data Scientist @ Twitter) - Why is Stats Useful?
Introduction to Normal Distribution
T Test
Welch T Test
Exercise: Welch's T-Test in Python on Baseball Data (left-handed vs right-handed hitters)
Non-Parametric Tests
Non-Normal Data
Stats vs. Machine Learning
Different Types of Machine Learning
Prediction with Regression
Linear Regression with Gradient Descent
Cost Function
How to Minimize Cost Function
Coefficients of Determination
Other Considerations
Problem Set 3: Analyzing Subway Data
Histogram: Entries on Rainy Vs Entries on non-Rainy Days
Is Welch's T-Test Applicable?
Mann-Whitney U-Test (Entries on Rainy and Non-Rainy Days)
Linear Regression with Gradient Descent on Subway Data
Plotting Residuals
Compute R²
OLS Regression Using Python Module StatsModels (Optional)
- Lesson 4: Data Visualization
Effective Information Visualization
Napoleon's March on Russia
Don (Principal Data Scientist @ AT&T): Communicating Findings
Rishiraj (Principal Data Scientist @ AT&T): Communicating Findings Well
Visual Encodings
Perception of Visual Cues
Plotting in Python (Intro to GGPLOT)
Data Types
Data Scales
Visualizing Time Series Data
Plots (Scatter, Line Charts, Loess Curve, Multivariate Data)
Problem Set 4: Visualizing Subway Data
Using Python and GGPLOT for plotting
- Ridership by time of day or day of week
- How ridership varies based on Subway station (UNIT)
- Which stations have more exits or entries at different times of day
- Lesson 5: MapReduce
Big Data and the MapReduce Programming Model
Basics of the MapReduce Programming Model
Mapper
Reducer
MapReduce with Aadhaar Data
MapReduce with Subway Data
Problem Set 5: MapReduce on Subway Data
Ridership per Station
Ridersip by Weather Type
Busiest Hour
- Final Project: Analyze the New York Subway Data
First Entry
This blog was created to publish my projects in data science. It may also contain short hints, remarks and interesting or funny facts around statistics and the programming language Python - the language I use most for processing and analyzing data. I am not a statistician, though I have some university mathematics background. I'm also not a programmer, though I started learning programming in Python two and a half years ago. Nevertheless I like both very much and my aim is to improve my skills in that combination of fields called "data science". I'll be using this blog to showcase projects for employers and other interested parties.
The title of this blog is a variation of a quote from my favorite TV series "Twin Peaks": "The owls are not what they seem."
The title of this blog is a variation of a quote from my favorite TV series "Twin Peaks": "The owls are not what they seem."
Abonnieren
Posts (Atom)


