markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
EvaluationUsually, the model and its predictions is not sufficient. In the following we want to evaluate our classifiers. Let's start by computing their error. The sklearn.metrics package contains several errors such as* Mean squared error* Mean absolute error* Mean squared log error* Median absolute error
#computing the squared error of the first model print("Mean squared error model 1: %.2f" % mean_squared_error(targetFeature1, targetFeature1_predict))
Mean squared error model 1: 0.56
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
We can also visualize the errors:
plt.scatter(targetFeature1_predict, (targetFeature1 - targetFeature1_predict) ** 2, color = "blue", s = 10,) ## plotting line to visualize zero error plt.hlines(y = 0, xmin = 0, xmax = 15, linewidth = 2) ## plot title plt.title("Squared errors Model 1") ## function to show plot plt.show()
_____no_output_____
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Now it is your turn. Compute the mean squared error and visualize the squared errors. Play around using different error metrics.
#Your turn print("Mean squared error model 2: %.2f" % mean_squared_error(targetFeature2,targetFeature2_predict)) print("Mean absolute error model 2: %.2f" % mean_absolute_error(targetFeature2,targetFeature2_predict)) plt.scatter(targetFeature2_predict, (targetFeature2 - targetFeature2_predict) ** 2, color = "blue",) ...
Mean squared error model 2: 8.89 Mean absolute error model 2: 2.32
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Handling multiple descriptive features at once - Multiple linear regressionIn most cases, we will have more than one descriptive feature . As an example we use an example data set of the scikit package. The dataset describes housing prices in Boston based on several attributes. Note, in this format the data is already...
from sklearn import datasets ## imports datasets from scikit-learn df3 = datasets.load_boston() #The sklearn package provides the data splitted into a set of descriptive features and a target feature. #We can easily transform this format into the pandas data frame as used above. descriptiveFeatures3 = pd.DataFrame(df3...
Descriptive features: CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX \ 0 0.00632 18.0 2.31 0.0 0.538 6.575 65.2 4.0900 1.0 296.0 1 0.02731 0.0 7.07 0.0 0.469 6.421 78.9 4.9671 2.0 242.0 2 0.02729 0.0 7.07 0.0 0.469 7.185 61.1 4.9671 2.0 242.0 3 0.0...
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
To predict the housing price we will use a Multiple Linear Regression model. In Python this is very straightforward: we use the same function as for simple linear regression, but our set of descriptive features now contains more than one element (see above).
classifier = LinearRegression() model3 = classifier.fit(descriptiveFeatures3,targetFeature3) targetFeature3_predict = classifier.predict(descriptiveFeatures3) print('Coefficients: \n', classifier.coef_) print('Intercept: \n', classifier.intercept_) print("Mean squared error: %.2f" % mean_squared_error(targetFeature3, ...
Coefficients: [[-1.08011358e-01 4.64204584e-02 2.05586264e-02 2.68673382e+00 -1.77666112e+01 3.80986521e+00 6.92224640e-04 -1.47556685e+00 3.06049479e-01 -1.23345939e-02 -9.52747232e-01 9.31168327e-03 -5.24758378e-01]] Intercept: [36.45948839] Mean squared error: 21.89
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
As you can see above, we have a coefficient for each descriptive feature. Handling categorical descriptive featuresSo far we always encountered numerical dscriptive features, but data sets can also contain categorical attributes. The regression function can only handle numerical input. There are several ways to tranfo...
#example using pandas df4 = pd.DataFrame({'A':['a','b','c'],'B':['c','b','a'] }) one_hot_pd = pd.get_dummies(df4) one_hot_pd #example using scikit from sklearn.preprocessing import LabelEncoder, OneHotEncoder #apply the one hot encoder encoder = OneHotEncoder(categories='auto') encoder.fit(df4) df4_OneHot = encoder.tr...
Transformed by One-hot Encoding: [[1. 0. 0. 0. 0. 1.] [0. 1. 0. 0. 1. 0.] [0. 0. 1. 1. 0. 0.]] Replacing categories by numerical labels: A B 0 0 2 1 1 1 2 2 0
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Now it is your turn. Perform linear regression using the data set given below. Don't forget to transform your categorical descriptive features. The rental price attribute represents the target variable.
from sklearn.preprocessing import LabelEncoder df5 = pd.DataFrame({'Size':[500,550,620,630,665],'Floor':[4,7,9,5,8], 'Energy rating':['C', 'A', 'A', 'B', 'C'], 'Rental price': [320,380,400,390,385] }) #Your turn # To transform the categorial feature to_trannsform = df5[['Energy rating']] encoder = LabelEncoder() trans...
Coefficients: [ 0.39008474 -0.54300185 -18.80539593] Intercept: 166.068958800039 Mean squared error: 4.68
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Predicting a categorical target value - Logistic regression We might also encounter data sets where our target feature is categorical. Here we don't transform them into numerical values, but insetad we use a logistic regression function. Luckily, sklearn provides us with a suitable function that is similar to the line...
# Importing the dataset iris = pd.read_csv('iris.csv') print('First look at the data set: ') print(iris.head()) #defining the descriptive and target features descriptiveFeatures_iris = iris[['sepal_length']] #we only use the attribute 'sepal_length' in this example targetFeature_iris = iris['species'] #we want to pre...
First look at the data set: sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 ...
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Now it is your turn. In the example above we only used the first attribute as descriptive variable. Change the example such that all available attributes are used.
#Your turn # Importing the dataset iris2 = pd.read_csv('iris.csv') print('First look at the data set: ') print(iris2.head()) #defining the descriptive and target features descriptiveFeatures_iris2 = iris[['sepal_length','sepal_width','petal_length','petal_width']] targetFeature_iris2 = iris['species'] #we want to pr...
First look at the data set: sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 ...
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Note, that the regression classifier (both logistic and non-logistic) can be tweaked using several parameters. This includes, but is not limited to, non-linear regression. Check out the documentation for details and feel free to play around! Support Vector Machines Aside from regression models, the sklearn package als...
from sklearn.svm import SVC #define descriptive and target features as before descriptiveFeatures_iris = iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']] targetFeature_iris = iris['species'] #this time, we train an SVM classifier classifier = SVC(C=1, kernel='linear', gamma = 'auto') classifier.fi...
_____no_output_____
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
As explained in the lecture, a support vector machine is defined by its support vectors. In the sklearn package we can access them and their properties very easily:* support_: indicies of support vectors* support_vectors_: the support vectors* n_support_: the number of support vectors for each class
print('Indicies of support vectors:') print(classifier.support_) print('The support vectors:') print(classifier.support_vectors_) print('The number of support vectors for each class:') print(classifier.n_support_)
Indicies of support vectors: [ 23 24 41 52 56 63 66 68 70 72 76 77 83 84 98 106 110 119 123 126 127 129 133 138 146 147 149] The support vectors: [[5.1 3.3 1.7 0.5] [4.8 3.4 1.9 0.2] [4.5 2.3 1.3 0.3] [6.9 3.1 4.9 1.5] [6.3 3.3 4.7 1.6] [6.1 2.9 4.7 1.4] [5.6 3. 4.5 1.5] [6.2 2.2 4.5 1.5] [5.9 3...
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
We can also calculate the distance of the data points to the separating hyperplane by using the decision_function(X) method. Score(X,y) calculates the mean accuracy of the classification. The classification report shows metrics such as precision, recall, f1-score and support. You will learn more about these quality met...
from sklearn.metrics import classification_report classifier.decision_function(descriptiveFeatures_iris) print('Accuracy: \n', classifier.score(descriptiveFeatures_iris,targetFeature_iris)) print('Classification report: \n') print(classification_report(targetFeature_iris, targetFeature_iris_predict))
Accuracy: 0.9933333333333333 Classification report: precision recall f1-score support setosa 1.00 1.00 1.00 50 versicolor 1.00 0.98 0.99 50 virginica 0.98 1.00 0.99 50 accuracy 0.99 ...
MIT
Instruction4/Instruction4-RegressionSVM.ipynb
danikhani/ITDS-Instructions-WS20
Prepare final dataset
# organize dataset into a useful structure # create directories dataset_home = train_folder # create label subdirectories labeldirs = ['separate_singleDouble/single/', 'separate_singleDouble/double/'] for labldir in labeldirs: newdir = dataset_home + labldir os.makedirs(newdir, exist_ok=True) # copy train...
_____no_output_____
MIT
NASA/Python_codes/ML_Books/01_01_transfer_learning_model_EVI.ipynb
HNoorazar/Kirti
Plot For Fun
# plot dog photos from the dogs vs cats dataset from matplotlib.image import imread # define location of dataset # plot first few images files = os.listdir(train_folder)[2:4] # files = [sorted(os.listdir(train_folder))[2]] + [sorted(os.listdir(train_folder))[-2]] for i in range(2): # define subplot pyplot.sub...
_____no_output_____
MIT
NASA/Python_codes/ML_Books/01_01_transfer_learning_model_EVI.ipynb
HNoorazar/Kirti
Full Code
# define cnn model def define_model(): # load model model = VGG16(include_top=False, input_shape=(224, 224, 3)) # mark loaded layers as not trainable for layer in model.layers: layer.trainable = False # add new classifier layers flat1 = Flatten()(model.layers[-1].output) class1 = Den...
_____no_output_____
MIT
NASA/Python_codes/ML_Books/01_01_transfer_learning_model_EVI.ipynb
HNoorazar/Kirti
Spark SQLSpark SQL is arguably one of the most important and powerful features in Spark. In a nutshell, with Spark SQL you can run SQL queries against views or tables organized into databases. You also can use system functions or define user functions and analyze query plans in order to optimize their workloads. This ...
spark.sql("SELECT 1 + 1").show()
+-------+ |(1 + 1)| +-------+ | 2| +-------+
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
As we have seen before, you can completely interoperate between SQL and DataFrames, as you see fit. For instance, you can create a DataFrame, manipulate it with SQL, and then manipulate it again as a DataFrame. It’s a powerful abstraction that you will likely find yourself using quite a bit:
bucket = spark._jsc.hadoopConfiguration().get("fs.gs.system.bucket") data = "gs://" + bucket + "/notebooks/data/" spark.read.json(data + "flight-data/json/2015-summary.json")\ .createOrReplaceTempView("flights_view") # DF => SQL spark.sql(""" SELECT DEST_COUNTRY_NAME, sum(count) FROM flights_view GROUP BY DEST_COUNT...
_____no_output_____
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
Creating TablesYou can create tables from a variety of sources. For instance below we are creating a table from a SELECT statement:
spark.sql(''' CREATE TABLE IF NOT EXISTS flights_from_select USING parquet AS SELECT * FROM flights_view ''') spark.sql('SELECT * FROM flights_from_select').show(5) spark.sql(''' DESCRIBE TABLE flights_from_select ''').show()
+-------------------+---------+-------+ | col_name|data_type|comment| +-------------------+---------+-------+ | DEST_COUNTRY_NAME| string| null| |ORIGIN_COUNTRY_NAME| string| null| | count| bigint| null| +-------------------+---------+-------+
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
CatalogThe highest level abstraction in Spark SQL is the Catalog. The Catalog is an abstraction for the storage of metadata about the data stored in your tables as well as other helpful things like databases, tables, functions, and views. The catalog is available in the `spark.catalog` package and contains a number of...
Cat = spark.catalog Cat.listTables() spark.sql('SHOW TABLES').show(5, False) Cat.listDatabases() spark.sql('SHOW DATABASES').show() Cat.listColumns('flights_from_select') Cat.listTables()
_____no_output_____
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
Caching Tables
spark.sql(''' CACHE TABLE flights_view ''') spark.sql(''' UNCACHE TABLE flights_view ''')
_____no_output_____
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
Explain
spark.sql(''' EXPLAIN SELECT * FROM just_usa_view ''').show(1, False)
+-----------------------------------------------------------------------------------------------------------------+ |plan | +---------------------------------------------------------------------------------------...
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
VIEWS - create/drop
spark.sql(''' CREATE VIEW just_usa_view AS SELECT * FROM flights_from_select WHERE dest_country_name = 'United States' ''') spark.sql(''' DROP VIEW IF EXISTS just_usa_view ''')
_____no_output_____
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
Drop tables
spark.sql('DROP TABLE flights_from_select') spark.sql('DROP TABLE IF EXISTS flights_from_select')
_____no_output_____
MIT
docs/Supplementary-Materials/01-Spark-SQL.ipynb
ymei9/Big-Data-Analytics-for-Business
Как выложить бота на HEROKU*Подготовил Ян Пиле* Сразу оговоримся, что мы на heroku выкладываем**echo-Бота в телеграме, написанного с помощью библиотеки [pyTelegramBotAPI](https://github.com/eternnoir/pyTelegramBotAPI)**.А взаимодействие его с сервером мы сделаем с использованием [flask](http://flask.pocoo.org/)То есть...
import os import telebot from flask import Flask, request TOKEN = '1403467808:AAEaaLPkIqrhrQ62p7ToJclLtNNINdOopYk' # это мой токен bot = telebot.TeleBot(token=TOKEN) server = Flask(__name__) # Если строка на входе непустая, то бот повторит ее @bot.message_handler(func=lambda msg: msg.text is not None) def reply_...
_____no_output_____
MIT
lect13_NumPy/2021_DPO_13_2_heroku.ipynb
weqrwer/Python_DPO_2021_fall
Computing Alpha, Beta, and R Squared in Python *Suggested Answers follow (usually there are multiple ways to solve a problem in Python).* *Running a Regression in Python - continued:*
import numpy as np import pandas as pd from scipy import stats import statsmodels.api as sm import matplotlib.pyplot as plt data = pd.read_excel('D:/Python/Data_Files/IQ_data.xlsx') X = data['Test 1'] Y = data['IQ'] plt.scatter(X,Y) plt.axis([0, 120, 0, 150]) plt.ylabel('IQ') plt.xlabel('Test 1') plt.show()
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
**** Use the statsmodels’ **.add_constant()** method to reassign the X data on X1. Use OLS with arguments Y and X1 and apply the fit method to obtain univariate regression results. Help yourself with the **.summary()** method.
X1 = sm.add_constant(X) reg = sm.OLS(Y, X1).fit() reg.summary()
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
By looking at the p-values, would you conclude Test 1 scores are a good predictor? ***** Imagine a kid would score 84 on Test 1. How many points is she expected to get on the IQ test, approximately?
45 + 84*0.76
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
****** Alpha, Beta, R^2: Apply the stats module’s **linregress()** to extract the value for the slope, the intercept, the r squared, the p_value, and the standard deviation.
slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y) slope intercept r_value r_value ** 2 p_value std_err
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
Use the values of the slope and the intercept to predict the IQ score of a child, who obtained 84 points on Test 1. Is the forecasted value different than the one you obtained above?
intercept + 84 * slope
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
****** Follow the steps to draw the best fitting line of the provided regression. Define a function that will use the slope and the intercept value to calculate the dots of the best fitting line.
def fitline(b): return intercept + slope * b
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
Apply it to the data you have stored in the variable X.
line = fitline(X)
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
Draw a scatter plot with the X and Y data and then plot X and the obtained fit-line.
plt.scatter(X,Y) plt.plot(X,line) plt.show()
_____no_output_____
MIT
Python for Finance - Code Files/83 Computing Alpha, Beta, and R Squared in Python/Python 2/Computing Alpha, Beta, and R Squared in Python - Solution.ipynb
siddharthjain1611/Python_for_Finance_Investment_Fundamentals-and-Data-Analytics
# Installs %%capture !pip install --upgrade category_encoders plotly # Imports import os, sys os.chdir('/content') !git init . !git remote add origin https://github.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge.git !git pull origin master !pip install -r requirements.txt os.chdir('module1') # Disable warning import wa...
_____no_output_____
MIT
Kaggle_Challenge_Assignment_Submission5.ipynb
JimKing100/DS-Unit-2-Kaggle-Challenge
Data generators
@numba.njit def event_series_bernoulli(series_length, event_count): '''Generate an iid Bernoulli distributed event series. series_length: length of the event series event_count: number of events''' event_series = np.zeros(series_length) event_series[np.random.choice(np.arange(0, series_length), ev...
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
Visualization of the impact models
default_T = 8192 default_N = 64 default_q = 4 es = event_series_bernoulli(default_T, default_N) for ts in [ time_series_mean_impact(es, order=default_q, signal_to_noise=10.), time_series_meanconst_impact(es, order=default_q, const=5.), time_series_var_impact(es, order=default_q, variance=4.), time_ser...
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
Simulations
def test_simul_pairs(impact_model, param_T, param_N, param_q, param_r, n_pairs, lag_cutoff, instantaneous, sample_method, twosamp_test, multi_test, alpha): true_positive = 0. false_positive = 0. for _ in tqdm(range(n_pairs)): es = event_series_bernoulli(para...
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
Mean impact model
default_N = 64 default_r = 1. default_q = 4
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
... by number of events
vals = [4, 8, 16, 32, 64, 128, 256] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='mean', param_T=default_T, param_N=val, param_q=default_q, param_r=default_r, ...
100%|██████████| 100/100 [00:05<00:00, 18.73it/s] 100%|██████████| 100/100 [00:00<00:00, 451.99it/s] 100%|██████████| 100/100 [00:00<00:00, 439.85it/s] 100%|██████████| 100/100 [00:00<00:00, 379.15it/s] 100%|██████████| 100/100 [00:00<00:00, 276.60it/s] 100%|██████████| 100/100 [00:00<00:00, 163.88it/s] 100%|██████████...
MIT
simulations.ipynb
diozaka/eitest
... by impact order
vals = [1, 2, 4, 8, 16, 32] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='mean', param_T=default_T, param_N=default_N, param_q=val, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 218.61it/s] 100%|██████████| 100/100 [00:00<00:00, 187.72it/s] 100%|██████████| 100/100 [00:00<00:00, 207.15it/s] 100%|██████████| 100/100 [00:00<00:00, 200.33it/s] 100%|██████████| 100/100 [00:00<00:00, 213.18it/s] 100%|██████████| 100/100 [00:00<00:00, 215.75it/s]
MIT
simulations.ipynb
diozaka/eitest
... by signal-to-noise ratio
vals = [1./32, 1./16, 1./8, 1./4, 1./2, 1., 2., 4.] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='mean', param_T=default_T, param_N=default_N, param_q=default_q, param_r=val, ...
100%|██████████| 100/100 [00:00<00:00, 179.47it/s] 100%|██████████| 100/100 [00:00<00:00, 210.34it/s] 100%|██████████| 100/100 [00:00<00:00, 206.91it/s] 100%|██████████| 100/100 [00:00<00:00, 214.85it/s] 100%|██████████| 100/100 [00:00<00:00, 212.98it/s] 100%|██████████| 100/100 [00:00<00:00, 182.82it/s] 100%|█████████...
MIT
simulations.ipynb
diozaka/eitest
Meanconst impact model
default_N = 64 default_r = 0.5 default_q = 4
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
... by number of events
vals = [4, 8, 16, 32, 64, 128, 256] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='meanconst', param_T=default_T, param_N=val, param_q=default_q, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 370.92it/s] 100%|██████████| 100/100 [00:00<00:00, 387.87it/s] 100%|██████████| 100/100 [00:00<00:00, 364.85it/s] 100%|██████████| 100/100 [00:00<00:00, 313.86it/s] 100%|██████████| 100/100 [00:00<00:00, 215.43it/s] 100%|██████████| 100/100 [00:00<00:00, 115.63it/s] 100%|█████████...
MIT
simulations.ipynb
diozaka/eitest
... by impact order
vals = [1, 2, 4, 8, 16, 32] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='meanconst', param_T=default_T, param_N=default_N, param_q=val, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 191.97it/s] 100%|██████████| 100/100 [00:00<00:00, 209.09it/s] 100%|██████████| 100/100 [00:00<00:00, 181.51it/s] 100%|██████████| 100/100 [00:00<00:00, 170.74it/s] 100%|██████████| 100/100 [00:00<00:00, 196.70it/s] 100%|██████████| 100/100 [00:00<00:00, 191.42it/s]
MIT
simulations.ipynb
diozaka/eitest
... by mean value
vals = [0.125, 0.25, 0.5, 1, 2] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='meanconst', param_T=default_T, param_N=default_N, param_q=default_q, param_r=val, ...
100%|██████████| 100/100 [00:00<00:00, 172.66it/s] 100%|██████████| 100/100 [00:00<00:00, 212.73it/s] 100%|██████████| 100/100 [00:00<00:00, 210.24it/s] 100%|██████████| 100/100 [00:00<00:00, 153.75it/s] 100%|██████████| 100/100 [00:00<00:00, 211.59it/s]
MIT
simulations.ipynb
diozaka/eitest
Variance impact modelIn the paper, we show results with the variance impact model parametrized by the **variance increase**. Here we directly modulate the variance.
default_N = 64 default_r = 8. default_q = 4
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
... by number of events
vals = [4, 8, 16, 32, 64, 128, 256] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='var', param_T=default_T, param_N=val, param_q=default_q, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 379.83it/s] 100%|██████████| 100/100 [00:00<00:00, 399.36it/s] 100%|██████████| 100/100 [00:00<00:00, 372.13it/s] 100%|██████████| 100/100 [00:00<00:00, 319.38it/s] 100%|██████████| 100/100 [00:00<00:00, 216.67it/s] 100%|██████████| 100/100 [00:00<00:00, 121.62it/s] 100%|█████████...
MIT
simulations.ipynb
diozaka/eitest
... by impact order
vals = [1, 2, 4, 8, 16, 32] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='var', param_T=default_T, param_N=default_N, param_q=val, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 205.11it/s] 100%|██████████| 100/100 [00:00<00:00, 208.57it/s] 100%|██████████| 100/100 [00:00<00:00, 208.42it/s] 100%|██████████| 100/100 [00:00<00:00, 215.50it/s] 100%|██████████| 100/100 [00:00<00:00, 210.17it/s] 100%|██████████| 100/100 [00:00<00:00, 213.72it/s]
MIT
simulations.ipynb
diozaka/eitest
... by variance
vals = [2., 4., 8., 16., 32.] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='var', param_T=default_T, param_N=default_N, param_q=default_q, param_r=val, ...
100%|██████████| 100/100 [00:00<00:00, 211.99it/s] 100%|██████████| 100/100 [00:00<00:00, 213.48it/s] 100%|██████████| 100/100 [00:00<00:00, 209.49it/s] 100%|██████████| 100/100 [00:00<00:00, 214.06it/s] 100%|██████████| 100/100 [00:00<00:00, 213.53it/s]
MIT
simulations.ipynb
diozaka/eitest
Tail impact model
default_N = 512 default_r = 3. default_q = 4
_____no_output_____
MIT
simulations.ipynb
diozaka/eitest
... by number of events
vals = [64, 128, 256, 512, 1024] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='tail', param_T=default_T, param_N=val, param_q=default_q, param_r=default_r, ...
100%|██████████| 100/100 [00:00<00:00, 210.81it/s] 100%|██████████| 100/100 [00:00<00:00, 117.61it/s] 100%|██████████| 100/100 [00:01<00:00, 58.35it/s] 100%|██████████| 100/100 [00:03<00:00, 26.73it/s] 100%|██████████| 100/100 [00:07<00:00, 13.43it/s]
MIT
simulations.ipynb
diozaka/eitest
... by impact order
vals = [1, 2, 4, 8, 16, 32] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='tail', param_T=default_T, param_N=default_N, param_q=val, param_r=default_r, ...
100%|██████████| 100/100 [00:03<00:00, 28.23it/s] 100%|██████████| 100/100 [00:03<00:00, 27.89it/s] 100%|██████████| 100/100 [00:03<00:00, 28.22it/s] 100%|██████████| 100/100 [00:03<00:00, 27.32it/s] 100%|██████████| 100/100 [00:03<00:00, 27.25it/s] 100%|██████████| 100/100 [00:03<00:00, 26.63it/s]
MIT
simulations.ipynb
diozaka/eitest
... by degrees of freedom
vals = [2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.] tprs = np.empty(len(vals)) fprs = np.empty(len(vals)) for i, val in enumerate(vals): tprs[i], fprs[i] = test_simul_pairs(impact_model='tail', param_T=default_T, param_N=default_N, param_q=default_q, param_r=val, ...
100%|██████████| 100/100 [00:03<00:00, 27.68it/s] 100%|██████████| 100/100 [00:03<00:00, 27.97it/s] 100%|██████████| 100/100 [00:03<00:00, 27.91it/s] 100%|██████████| 100/100 [00:03<00:00, 28.07it/s] 100%|██████████| 100/100 [00:03<00:00, 27.99it/s] 100%|██████████| 100/100 [00:03<00:00, 27.71it/s] 100%|██████████| 100...
MIT
simulations.ipynb
diozaka/eitest
%%capture %pip install nflfastpy --upgrade import nflfastpy from nflfastpy.utils import convert_to_gsis_id from nflfastpy import default_headshot from matplotlib import pyplot as plt import pandas as pd import seaborn as sns import requests print('Example default player headshot\n') plt.imshow(default_headshot); df = ...
_____no_output_____
MIT
examples/Top 25 AY Graph w Roster and Team Logo Data.ipynb
AccidentalGuru/nflfastpy
The Analysis of The Evolution of The Russian Comedy. Part 3. In this analysis,we will explore evolution of the French five-act comedy in verse based on the following features:- The coefficient of dialogue vivacity;- The percentage of scenes with split verse lines;- The percentage of scenes with split rhymes;- The perc...
import pandas as pd import numpy as np import json from os import listdir from scipy.stats import shapiro import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns def make_plot(feature, title): mean, std, median = summary(feature) plt.figure(figsize=(10, 7)) plt.title(title, fontsize=17) ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Part 1. Feature Descriptions For the Russian corpus of the five-act comedies, we generated additional features that inspired by Iarkho. So far, we had no understanding how these features evolved over time and whether they could differentiate literary periods. The features include the following:1. **The Coefficient of ...
comedies = pd.read_csv('../Russian_Comedies/Data/Comedies_Raw_Data.csv') # sort by creation date comedies_sorted = comedies.sort_values(by='creation_date').copy() # select only original comedies and five act original_comedies = comedies_sorted[(comedies_sorted['translation/adaptation'] == 0) & ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Part 1. Feature Correlations
comedies_verse_features[['dialogue_vivacity', 'percentage_scene_split_verse', 'percentage_scene_split_rhymes', 'percentage_open_scenes', 'percentage_scenes_rhymes_split_verse']].corr().round(2) original_comedies[['dialogue_vivac...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Dialogue vivacity is moderately positively correlated with the percentage of scenes with split verse lines (0.53), with the percentage of scenes with split rhymes (0.51), and slightly less correlated with the percentage of open scenes (0.45). However, it is strongly positively correlated with the percentage of scenes w...
make_plot(comedies_verse_features['dialogue_vivacity'], 'Distribution of the Dialogue Vivacity Coefficient') mean, std, median = summary(comedies_verse_features['dialogue_vivacity']) print('Mean dialogue vivacity coefficient', round(mean, 2)) print('Standard deviation of the dialogue vivacity coefficient:', r...
Mean dialogue vivacity coefficient 0.46 Standard deviation of the dialogue vivacity coefficient: 0.1 Median dialogue vivacity coefficient: 0.4575
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Shapiro-Wilk Normality Test
print('The p-value of the Shapiro-Wilk normality test:', shapiro(comedies_verse_features['dialogue_vivacity'])[1])
The p-value of the Shapiro-Wilk normality test: 0.2067030817270279
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Shapiro-Wilk test showed that the probability of the coefficient of dialogue vivacity of being normally distributed was 0.2067030817270279, which was above the 0.05 significance level. We failed to reject the null hypothesis of the normal distribution.
make_plot(comedies_verse_features['percentage_scene_split_verse'], 'Distribution of The Percentage of Scenes with Split Verse Lines') mean, std, median = summary(comedies_verse_features['percentage_scene_split_verse']) print('Mean percentage of scenes with split verse lines:', round(mean, 2)) print('Standard ...
The p-value of the Shapiro-Wilk normality test: 0.8681985139846802
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Shapiro-Wilk showed that the probability of the percentage of scenes with split verse lines of being normally distributed was very high (the p-value is 0.8681985139846802). We failed to reject the null hypothesis of normal distribution.
make_plot(comedies_verse_features['percentage_scene_split_rhymes'], 'Distribution of The Percentage of Scenes with Split Rhymes') mean, std, median = summary(comedies_verse_features['percentage_scene_split_rhymes']) print('Mean percentage of scenes with split rhymes:', round(mean, 2)) print('Standard deviation ...
The p-value of the Shapiro-Wilk normality test: 0.5752763152122498
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Shapiro-Wilk test showed that the probability of the number of dramatic characters of being normally distributed was 0.5752763152122498. This probability was much higher than the 0.05 significance level. Therefore, we failed to reject the null hypothesis of normal distribution.
make_plot(comedies_verse_features['percentage_open_scenes'], 'Distribution of The Percentage of Open Scenes') mean, std, median = summary(comedies_verse_features['percentage_open_scenes']) print('Mean percentage of open scenes:', round(mean, 2)) print('Standard deviation of the percentage of open scenes:', rou...
The p-value of the Shapiro-Wilk normality test: 0.3018988370895386
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Shapiro-Wilk test showed that the probability of the number of the percentage of open scenes of being normally distributed was 0.3018988370895386, which was quite a lot higher than the significance level of 0.05. Therefore, we failed to reject the null hypothesis of normal distribution of the percentage of open sce...
make_plot(comedies_verse_features['percentage_scenes_rhymes_split_verse'], 'Distribution of The Percentage of Scenes with Split Verse Lines and Rhymes') mean, std, median = summary(comedies_verse_features['percentage_scenes_rhymes_split_verse']) print('Mean percentage of scenes with split rhymes and verse line...
The p-value of the Shapiro-Wilk normality test: 0.015218793414533138
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Shapiro-Wilk test showed that the probability of the percentage of scenes with split verse lines and rhymes of being normally distributed was very low (the p-value was 0.015218793414533138). Therefore, we rejected the hypothesis of normal distribution. Summary:1. The majority of the verse features were normally di...
comedies_verse_features['period'] = comedies_verse_features.creation_date.apply(determine_period) period_one = comedies_verse_features[comedies_verse_features['period'] == 1].copy() period_two = comedies_verse_features[comedies_verse_features['period'] == 2].copy() period_one.shape period_two.shape
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The T-Test The Coefficient of Dialogue Vivacity
from scipy.stats import ttest_ind ttest_ind(period_one['dialogue_vivacity'], period_two['dialogue_vivacity'], equal_var=False)
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Verse Lines
ttest_ind(period_one['percentage_scene_split_verse'], period_two['percentage_scene_split_verse'], equal_var=False)
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scnes With Split Rhymes
ttest_ind(period_one['percentage_scene_split_rhymes'], period_two['percentage_scene_split_rhymes'], equal_var=False)
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Open Scenes
ttest_ind(period_one['percentage_open_scenes'], period_two['percentage_open_scenes'], equal_var=False)
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Summary|Feature |p-value |Result|---------------------------| ----------------|--------------------------------| The coefficient of dialogue vivacity |0.92 | Not Significant|The percentage of scenes with split verse lines|0.009 | Significant|The percentage of scenes with split rhymes|...
small_sample_mann_whitney_u_test(period_one['percentage_scenes_rhymes_split_verse'], period_two['percentage_scenes_rhymes_split_verse'])
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Critical Value of U |Periods |Critical Value of U |---------------------------| ----------------| Period One (n=6) and Period Two (n=10) |11 Summary|Feature |u-statistic |Result|---------------------------| ----------------|---------------------------...
def scatter(df, feature, title, xlabel, text_y): sns.jointplot('creation_date', feature, data=df, color='b', height=7).plot_joint( sns.kdeplot, zorder=0, n_levels=20) plt.axvline(1795, color='grey',line...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Coefficient of Dialogue Vivacity
scatter(comedies_verse_features, 'dialogue_vivacity', 'The Coefficient of Dialogue Vivacity by Year', 'The Coefficient of Dialogue Vivacity', 0.85)
/opt/anaconda3/envs/text_extraction/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterp...
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Verse Lines
scatter(comedies_verse_features, 'percentage_scene_split_verse', 'The Percentage of Scenes With Split Verse Lines by Year', 'Percentage of Scenes With Split Verse Lines', 80)
/opt/anaconda3/envs/text_extraction/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterp...
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Rhymes
scatter(comedies_verse_features, 'percentage_scene_split_rhymes', 'The Percentage of Scenes With Split Rhymes by Year', 'The Percentage of Scenes With Split Rhymes', 80)
/opt/anaconda3/envs/text_extraction/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterp...
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Open Scenes
scatter(comedies_verse_features, 'percentage_open_scenes', 'The Percentage of Open Scenes by Year', 'The Percentage of Open Scenes', 100)
/opt/anaconda3/envs/text_extraction/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterp...
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Verse Lines and Rhymes
scatter(comedies_verse_features, 'percentage_scenes_rhymes_split_verse', ' The Percentage of Scenes With Split Verse Lines and Rhymes by Year', ' The Percentage of Scenes With Split Verse Lines and Rhymes', 45)
/opt/anaconda3/envs/text_extraction/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterp...
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Part 5. Descriptive Statistics For Two Periods and Overall The Coefficient of Dialogue Vivacity In Entire Corpus
comedies_verse_features.describe().loc[:, 'dialogue_vivacity'][['mean', 'std', '50%', 'min', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
By Tentative Periods
comedies_verse_features.groupby('period').describe().loc[:, 'dialogue_vivacity'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Verse Lines In Entire Corpus
comedies_verse_features.describe().loc[:, 'percentage_scene_split_verse'][['mean', 'std', '50%', 'min', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
By Periods
comedies_verse_features.groupby('period').describe().loc[:, 'percentage_scene_split_verse'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Rhymes
comedies_verse_features.describe().loc[:, 'percentage_scene_split_rhymes'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
By Tentative Periods
comedies_verse_features.groupby('period').describe().loc[:, 'percentage_scene_split_rhymes'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Open Scenes In Entire Corpus
comedies_verse_features.describe().loc[:, 'percentage_open_scenes'][['mean', 'std', '50%', 'min', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
By Tenative Periods
comedies_verse_features.groupby('period').describe().loc[:, 'percentage_open_scenes'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
The Percentage of Scenes With Split Verse Lines or Rhymes
comedies_verse_features.describe().loc[:, 'percentage_scenes_rhymes_split_verse'][['mean', 'std', '50%', ...
_____no_output_____
MIT
Analyses/The Evolution of The Russian Comedy_Verse_Features.ipynb
innawendell/European_Comedy
Lalonde Pandas API Exampleby Adam Kelleher We'll run through a quick example using the high-level Python API for the DoSampler. The DoSampler is different from most classic causal effect estimators. Instead of estimating statistics under interventions, it aims to provide the generality of Pearlian causal inference. In...
import os, sys sys.path.append(os.path.abspath("../../../")) from rpy2.robjects import r as R %load_ext rpy2.ipython #%R install.packages("Matching") %R library(Matching) %R data(lalonde) %R -o lalonde lalonde.to_csv("lalonde.csv",index=False) # the data already loaded in the previous cell. we include the import # her...
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
The `causal` Namespace We've created a "namespace" for `pandas.DataFrame`s containing causal inference methods. You can access it here with `lalonde.causal`, where `lalonde` is our `pandas.DataFrame`, and `causal` contains all our new methods! These methods are magically loaded into your existing (and future) datafram...
import dowhy.api
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
Now that we have the `causal` namespace, lets give it a try! The `do` OperationThe key feature here is the `do` method, which produces a new dataframe replacing the treatment variable with values specified, and the outcome with a sample from the interventional distribution of the outcome. If you don't specify a value ...
do_df = lalonde.causal.do(x='treat', outcome='re78', common_causes=['nodegr', 'black', 'hisp', 'age', 'educ', 'married'], variable_types={'age': 'c', 'educ':'c', 'black': 'd', 'hisp': 'd', 'married':...
WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs. INFO:dowhy.causal_graph:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named "Unobserved Confounders" to reflect this. INFO:dowhy.causal_model:M...
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
Notice you get the usual output and prompts about identifiability. This is all `dowhy` under the hood!We now have an interventional sample in `do_df`. It looks very similar to the original dataframe. Compare them:
lalonde.head() do_df.head()
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
Treatment Effect EstimationWe could get a naive estimate before for a treatment effect by doing
(lalonde[lalonde['treat'] == 1].mean() - lalonde[lalonde['treat'] == 0].mean())['re78']
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
We can do the same with our new sample from the interventional distribution to get a causal effect estimate
(do_df[do_df['treat'] == 1].mean() - do_df[do_df['treat'] == 0].mean())['re78']
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
We could get some rough error bars on the outcome using the normal approximation for a 95% confidence interval, like
import numpy as np 1.96*np.sqrt((do_df[do_df['treat'] == 1].var()/len(do_df[do_df['treat'] == 1])) + (do_df[do_df['treat'] == 0].var()/len(do_df[do_df['treat'] == 0])))['re78']
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
but note that these DO NOT contain propensity score estimation error. For that, a bootstrapping procedure might be more appropriate. This is just one statistic we can compute from the interventional distribution of `'re78'`. We can get all of the interventional moments as well, including functions of `'re78'`. We can l...
do_df['re78'].describe() lalonde['re78'].describe()
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
and even plot aggregations, like
%matplotlib inline import seaborn as sns sns.barplot(data=lalonde, x='treat', y='re78') sns.barplot(data=do_df, x='treat', y='re78')
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
Specifying InterventionsYou can find the distribution of the outcome under an intervention to set the value of the treatment.
do_df = lalonde.causal.do(x={'treat': 1}, outcome='re78', common_causes=['nodegr', 'black', 'hisp', 'age', 'educ', 'married'], variable_types={'age': 'c', 'educ':'c', 'black': 'd', 'hisp': 'd', 'marr...
_____no_output_____
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
This new dataframe gives the distribution of `'re78'` when `'treat'` is set to `1`. For much more detail on how the `do` method works, check the docstring:
help(lalonde.causal.do)
Help on method do in module dowhy.api.causal_data_frame: do(x, method='weighting', num_cores=1, variable_types={}, outcome=None, params=None, dot_graph=None, common_causes=None, estimand_type='nonparametric-ate', proceed_when_unidentifiable=False, stateful=False) method of dowhy.api.causal_data_frame.CausalAccessor in...
MIT
Utils/dowhy/docs/source/example_notebooks/lalonde_pandas_api.ipynb
maliha93/Fairness-Analysis-Code
Welcome to the Datenguide Python PackageWithin this notebook the functionality of the package will be explained and demonstrated with examples. Topics- Import- get region IDs- get statstic IDs- get the data - for single regions - for multiple regions 1. Import **Import the helper functions 'get_all_regions' and...
# ONLY FOR TESTING LOCAL PACKAGE # %cd .. from datenguidepy.query_helper import get_all_regions, get_statistics from datenguidepy import Query
C:\Users\Alexandra\Documents\GitHub\datenguide-python
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python
**Import pandas and matplotlib for the usual display of data as tables and graphs**
import pandas as pd import matplotlib %matplotlib inline pd.set_option('display.max_colwidth', 150)
_____no_output_____
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python
2. Get Region IDs How to get the ID of the region I want to query Regionalstatistik - the database behind Datenguide - has data for differently granular levels of Germany. nuts: 1 – Bundesländer 2 – Regierungsbezirke / statistische Regionen 3 – Kreise / kreisfreie Städte. lau: 1 -...
# get_all_regions returns all ids get_all_regions()
_____no_output_____
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python
To get a specific ID, use the common pandas function `query()`
# e.g. get all "Bundesländer get_all_regions().query("level == 'nuts1'") # e.g. get the ID of Havelland get_all_regions().query("name =='Havelland'")
_____no_output_____
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python
3. Get statistic IDs How to find statistics
# get all statistics get_statistics()
_____no_output_____
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python
If you already know the statsitic ID you are looking for - perfect. Otherwise you can use the pandas `query()` function so search e.g. for specific terms.
# find out the name of the desired statistic about birth get_statistics().query('long_description.str.contains("Statistik der Geburten")', engine='python')
_____no_output_____
MIT
use_case/01_intro_tutorial.ipynb
elekt/datenguide-python