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
Evaluate the model on the test set:
score = sc.evaluate(x_test, y_test, verbose=0) print('Test accuracy: ', score[1])
Test accuracy: 0.8862
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Define and train auto-encoder
def ae_model(): # encoder x_in = Input(shape=(28, 28, 1)) x = Conv2D(16, (3, 3), activation='relu', padding='same')(x_in) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3), activation='relu', padding='same')(x) x = MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(4, (3, 3), ...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_2 (InputLayer) (None, 28, 28, 1) 0 ________________________________________________________...
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Calculate Trust Scores Initialize trust scores:
ts = TrustScore()
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
The key is to **fit and calculate the trust scores on the encoded instances**. The encoded data still needs to be reshaped from (60000, 4, 4, 4) to (60000, 64) to comply with the k-d tree format. This is handled internally:
x_train_enc = enc.predict(x_train) ts.fit(x_train_enc, y_train, classes=10) # 10 classes present in MNIST
Reshaping data from (60000, 4, 4, 4) to (60000, 64) so k-d trees can be built.
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
We can now calculate the trust scores and closest not predicted classes of the predictions on the test set, using the distance to the 5th nearest neighbor in each class:
x_test_enc = enc.predict(x_test) y_pred = sc.predict(x_test) score, closest_class = ts.score(x_test_enc, y_pred, k=5)
Reshaping data from (10000, 4, 4, 4) to (10000, 64) so k-d trees can be queried.
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Let's inspect which predictions have low and high trust scores:
n = 5 idx_min, idx_max = np.argsort(score)[:n], np.argsort(score)[-n:] score_min, score_max = score[idx_min], score[idx_max] closest_min, closest_max = closest_class[idx_min], closest_class[idx_max] pred_min, pred_max = np.argmax(y_pred[idx_min], axis=1), np.argmax(y_pred[idx_max], axis=1) imgs_min, imgs_max = x_test[i...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Low Trust Scores The image below makes clear that the low trust scores correspond to misclassified images. Because the trust scores are significantly below 1, they correctly identified that the images belong to another class than the predicted class, and identified that class.
plt.figure(figsize=(20, 4)) for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(imgs_min[i].reshape(28, 28)) plt.title('Model prediction: {} \n Label: {} \n Trust score: {:.3f}' \ '\n Closest other class: {}'.format(pred_min[i], label_min[i], score_min[i], closest_min[i])) ax.get_xax...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
High Trust Scores The high trust scores on the other hand all are very clear 1's:
plt.figure(figsize=(20, 4)) for i in range(n): ax = plt.subplot(1, n, i+1) plt.imshow(imgs_max[i].reshape(28, 28)) plt.title('Model prediction: {} \n Label: {} \n Trust score: {:.3f}'.format(pred_max[i], label_max[i], score_max[i])) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Comparison of Trust Scores with model prediction probabilities Let’s compare the prediction probabilities from the classifier with the trust scores for each prediction by checking whether trust scores are better than the model’s prediction probabilities at identifying correctly classified examples.First we need to set...
def run_sc(X_train, y_train, X_test): clf = sc_model() clf.fit(X_train, y_train, batch_size=128, epochs=5, verbose=0) y_pred_proba = clf.predict(X_test) y_pred = np.argmax(y_pred_proba, axis=1) probas = y_pred_proba[range(len(y_pred)), y_pred] # probabilities of predicted class return y_pred, p...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
* Define the function that generates the precision plots:
def plot_precision_curve(plot_title, percentiles, labels, final_tp, final_stderr, final_misclassification, colors = ['blue', 'darkorange', 'brown', 'red', 'purple'])...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
* The function below trains the model on a number of folds, makes predictions, calculates the trust scores, and generates the precision curves to compare the trust scores with the model prediction probabilities:
def run_precision_plt(X, y, nfolds, percentiles, run_model, test_size=.2, plt_title="", plt_names=[], predict_correct=True, classes=10): def stderr(L): return np.std(L) / np.sqrt(len(L)) all_tp = [[[] for p in percentiles] for _ in plt_names] misclassifications = [] ...
_____no_output_____
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
Detect correctly classified examples The x-axis on the plot below shows the percentiles for the model prediction probabilities of the predicted class for each instance and for the trust scores. The y-axis represents the precision for each percentile. For each percentile level, we take the test examples whose trust sco...
X = x_train y = y_train percentiles = [0 + 0.5 * i for i in range(200)] nfolds = 2 plt_names = ['Model Confidence', 'Trust Score'] plt_title = 'MNIST -- Softmax Classifier -- Predict Correct' run_precision_plt(X, y, nfolds, percentiles, run_sc, plt_title=plt_title, plt_names=plt_names, predict_correc...
Reshaping data from (48000, 4, 4, 4) to (48000, 64) so k-d trees can be built. Reshaping data from (12000, 4, 4, 4) to (12000, 64) so k-d trees can be queried. Reshaping data from (48000, 4, 4, 4) to (48000, 64) so k-d trees can be built. Reshaping data from (12000, 4, 4, 4) to (12000, 64) so k-d trees can be queried.
Apache-2.0
examples/trustscore_mnist.ipynb
SeptumCapital/alibi
CSAILVision semantic segmention modelsThis is a semantic segmentation notebook using an [ADE20K](http://groups.csail.mit.edu/vision/datasets/ADE20K/) pretrained model from the open source project [CSAILVision/semantic-segmentation-pytorch](https://github.com/CSAILVision/semantic-segmentation-pytorch).For other deep-le...
import os from os.path import exists, join, basename, splitext git_repo_url = 'https://github.com/CSAILVision/semantic-segmentation-pytorch.git' project_name = splitext(basename(git_repo_url))[0] if not exists(project_name): # clone and install dependencies !git clone -q $git_repo_url #!cd $project_name && pip i...
_____no_output_____
MIT
Deep-Learning-Notebooks/notebooks/CSAILVision_SemanticSegmentation.ipynb
deepraj1729/Resources-and-Guides
Download a pretrained modelAccording to [https://github.com/CSAILVision/semantic-segmentation-pytorchperformance](https://github.com/CSAILVision/semantic-segmentation-pytorchperformance), **UperNet101** was the best performing model. We will use it as the pretrained model:
ENCODER_NAME = 'resnet101' DECODER_NAME = 'upernet' PRETRAINED_ENCODER_MODEL_URL = 'http://sceneparsing.csail.mit.edu/model/pytorch/baseline-%s-%s/encoder_epoch_50.pth' % (ENCODER_NAME, DECODER_NAME) PRETRAINED_DECODER_MODEL_URL = 'http://sceneparsing.csail.mit.edu/model/pytorch/baseline-%s-%s/decoder_epoch_50.pth' % (...
_____no_output_____
MIT
Deep-Learning-Notebooks/notebooks/CSAILVision_SemanticSegmentation.ipynb
deepraj1729/Resources-and-Guides
Prepare modelLoad the pretrained model:
from types import SimpleNamespace import torch from models import ModelBuilder, SegmentationModule from dataset import TestDataset from utils import colorEncode from scipy.io import loadmat # options options = SimpleNamespace(fc_dim=2048, num_class=150, imgSize = [30...
_____no_output_____
MIT
Deep-Learning-Notebooks/notebooks/CSAILVision_SemanticSegmentation.ipynb
deepraj1729/Resources-and-Guides
Evaluate on a test imageFirst, download a test image from the internet:
IMAGE_URL = 'https://raw.githubusercontent.com/tugstugi/dl-colab-notebooks/master/resources/lidl.jpg' image_file = basename(IMAGE_URL) !wget -q -O $image_file $IMAGE_URL plt.figure(figsize=(10, 5)) plt.imshow(matplotlib.image.imread(image_file))
_____no_output_____
MIT
Deep-Learning-Notebooks/notebooks/CSAILVision_SemanticSegmentation.ipynb
deepraj1729/Resources-and-Guides
Now, test on the downloaded image:
t = time.time() pred = test(image_file) print("executed in %.3fs" % (time.time()-t)) pred_color = colorEncode(pred, loadmat(os.path.join(project_name, 'data/color150.mat'))['colors']) plt.imshow(pred_color)
# samples: 1 executed in 0.631s
MIT
Deep-Learning-Notebooks/notebooks/CSAILVision_SemanticSegmentation.ipynb
deepraj1729/Resources-and-Guides
In-Class Coding Lab: FunctionsThe goals of this lab are to help you to understand:- How to use Python's built-in functions in the standard library.- How to write user-defined functions- The benefits of user-defined functions to code reuse and simplicity.- How to create a program to use functions to solve a complex ide...
import math dir(math)
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
If you look through the output, you'll see a `factorial` name. Let's see if it's a function we can use:
help(math.factorial)
Help on built-in function factorial in module math: factorial(...) factorial(x) -> Integral Find x!. Raise a ValueError if x is negative or non-integral.
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
It says it's a built-in function, and requies an integer value (which it referrs to as x, but that value is arbitrary) as an argument. Let's call the function and see if it works:
math.factorial(5) #this is an example of "calling" the function with input 5. The output should be 120 math.factorial(0) # here we call the same function with input 0. The output should be 1. ## Call the factorial function with an input argument of 4. What is the output? #TODO write code here. math.factorial(5)
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Using functions to print things awesome in JuypterUp until this point we've used the boring `print()` function for our output. Let's do better. In the `IPython.display` module there are two functions `display()` and `HTML()`. The `display()` function outputs a Python object to the Jupyter notebook. The `HTML()` functi...
from IPython.display import display, HTML print("Exciting:") display(HTML("<h1>Hello</h1>")) print("Boring:") print("Hello")
Exciting:
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Let's keep the example going by writing two of our own functions to print a title and print text as normal, respectively. Execute this code:
def print_title(text): ''' This prints text to IPython.display as H1 ''' return display(HTML("<H1>" + text + "</H1>")) def print_normal(text): ''' this prints text to IPython.display as normal text ''' return display(HTML(text))
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Now let's use these two functions in a familiar program!
print_title("Area of a Rectangle") length = float(input("Enter length: ")) width = float(input("Enter width: ")) area = length * width print_normal("The area is %.2f" % area)
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Let's get back to credit cards....Now that we know how a bit about **Packages**, **Modules**, and **Functions** let's attempt to write our first function. Let's tackle the easier of our two credit card related problems:- Who is the issuing network? Visa, MasterCard, Discover or American Express.This problem can be sol...
## TODO: Write your code here ccard = input("Please enter your credit card number: ") digit = ccard[0] if digit == '4': card_issuer = "Visa" elif digit == '5': card_issuer = "MasterCard" elif digit == '6': card_issuer = "Discover" elif digit == '3': card_issuer = "American Express" else: card_issue...
Please enter your credit card number: 4215678 Visa
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
**IMPORTANT** Make sure to test your code by running it 5 times. You should test issuer and also the "Invalid Card" case. Introducing the Write - Refactor - Test - Rewrite approachIt would be nice to re-write this code to use a function. This can seem daunting / confusing for beginner programmers, which is why we teach...
def CardIssuer(card): '''This function takes a card number (card) as input, and returns the issuer name as output''' ## TODO write code here they should be the same as lines 3-13 from the code above digit = card[0] if digit == '4': card_issuer = "Visa" elif digit == '5': card_issuer...
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Step 3: TestYou wrote the function, but how do you know it works? The short answer is unless you test it you're guessing. Testing our function is as simple as calling the function with input values where WE KNOW WHAT TO EXPECT from the output. We then compare that to the ACTUAL value from the called function. If they ...
# Testing the CardIssuer() function print("WHEN card='40123456789' We EXPECT CardIssuer(card) to return Visa ACTUAL", CardIssuer("40123456789")) print("WHEN card='50123456789' We EXPECT CardIssuer(card) to return MasterCard ACTUAL", CardIssuer("50123456789")) ## TODO: You write the remaining 3 tests, you can copy the ...
WHEN card='40123456789' We EXPECT CardIssuer(card) to return Visa ACTUAL Visa WHEN card='50123456789' We EXPECT CardIssuer(card) to return MasterCard ACTUAL MasterCard WHEN card='60123456789' We EXPECT CardIssuer(card) to return Discover ACTUAL: Discover WHEN card='30123456789' We EXPECT CardIssuer(card) to return Amer...
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Step 4: RewriteThe final step is to re-write the original program, but use the function instead. The algorithm becomes```input credit card number into variable cardcall the CardIssuer function with card as input, issuer as outputprint issuer``` Now You Try It!
# TODO Re-write the program here, calling our function. ccard = input("Please enter your credit card number: ") card_issuer = CardIssuer(ccard) print(card_issuer)
Please enter your credit card number: 1234567 Invalid
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Functions are abstractions. Abstractions are good.Step on the accellerator and the car goes. How does it work? Who cares, it's an abstraction! Functions are the same way. Don't believe me. Consider the Luhn Check Algorithm: https://en.wikipedia.org/wiki/Luhn_algorithm This nifty little algorithm is used to verify that...
# Todo: execute this code def checkLuhn(card): ''' This Luhn algorithm was adopted from the pseudocode here: https://en.wikipedia.org/wiki/Luhn_algorithm''' total = 0 length = len(card) parity = length % 2 for i in range(length): digit = int(card[i]) if i%2 == parity: di...
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Is that a credit card number or the ramblings of a madman?In order to test the `checkLuhn()` function you need some credit card numbers. (Don't look at me... you ain't gettin' mine!!!!) Not to worry, the internet has you covered. The website: http://www.getcreditcardnumbers.com/ is not some mysterious site on the dark...
#TODO Write your two tests here print("When card='4716511919678261' We EXPECT checkLuhn(card) to return True. ACTUAL: %s" % checkLuhn('4716511919678261')) print("When card='4222222222222222' We EXPECT checkLuhn(card) to return False. ACTUAL: %s" % checkLuhn('4222222222222222'))
_____no_output_____
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Putting it all togetherFinally use our two functions to write the following program. It will ask for a series of credit card numbers, until you enter 'quit' for each number it will output whether it's invalid or if valid name the issuer.Here's the Algorithm:```loop input a credit card number if card = 'quit' sto...
## TODO Write code here while True: ccard = input("Enter your credit card number or'quit'to end the program. ") if ccard == 'quit': break try: if checkLuhn(ccard) == True: issuer = CardIssuer(ccard) print(issuer) else: print("Invalid card. Try aga...
Enter your credit card number or'quit'to end the program. qwqwewq Please enter a number. Try again. Enter your credit card number or'quit'to end the program. 601139199679300 Invalid card. Try again. Enter your credit card number or'quit'to end the program. 4916741594665261 Visa Enter your credit card number or'quit'...
MIT
content/lessons/06/Class-Coding-Lab/CCL-Functions.ipynb
auramnar/Summer2018Learn2Code
Generate dataset
np.random.seed(12) y = np.random.randint(0,3,500) idx= [] for i in range(3): print(i,sum(y==i)) idx.append(y==i) x = np.zeros((500,)) np.random.seed(12) x[idx[0]] = np.random.uniform(low =-1,high =0,size= sum(idx[0])) x[idx[1]] = np.random.uniform(low =0,high =1,size= sum(idx[1])) x[idx[2]] = np.random.uniform(...
_____no_output_____
MIT
AAAI/Learnability/CIN/older/ds1/synthetic_type0_MLP2_m_250_lr0001.ipynb
lnpandey/DL_explore_synth_data
Bayesian Camera Calibration> Let's apply Bayesian analysis to calibrate a camera- toc: true - badges: true- comments: true- categories: [Bayesian, Computer Vision]- image: images/2020-03-28-Bayesian-Camera-Calibration/header.jpg
import numpy as np import matplotlib.pyplot as plt import pymc3 as pm plt.rcParams['figure.figsize'] = [10,10] def x_rot(theta,x,y,z): theta *= np.pi/180 x_rot = x y_rot = np.cos(theta)*y - np.sin(theta)*z z_rot = np.sin(theta)*y + np.cos(theta)*z return(x_rot,y_rot,z_rot) def y_rot(theta,x,y,z): ...
_____no_output_____
Apache-2.0
_drafts/2020-03-28-Bayesian-Camera-Calibration.ipynb
CGCooke/Blog
Projet de Machine Learning : Test de classification bout en bout 1.Chargement des données
#importation des modules necessaires import pyspark from pyspark.sql import SparkSession import joblib #creation d'une session spark mon_spark=SparkSession.builder.master("local").appName("MLproject").getOrCreate() ccdefault = mon_spark.read.format("csv").options(header=True,inferSchema=True).load("Doc_Evaluation/se...
+---+---------+---+---------+--------+---+-----+-----+-----+-----+-----+-----+---------+---------+---------+---------+---------+---------+--------+--------+--------+--------+--------+--------+-------+ | ID|LIMIT_BAL|SEX|EDUCATION|MARRIAGE|AGE|PAY_0|PAY_2|PAY_3|PAY_4|PAY_5|PAY_6|BILL_AMT1|BILL_AMT2|BILL_AMT3|BILL_AMT4|B...
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
2. Analyse exploratoire
# Affichage des attributs ccdefault.printSchema() import pandas as pd import seaborn as sns from matplotlib import pyplot as plt # Conversion en dataframe pandas pour une meilleure manipulation ccdefault.pd=ccdefault.toPandas() # Changement de nom de colonnnes, la colonne "PAY_0" devrait plutot etre "PAY_1" ccdefau...
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
2.1 Distribution des variables continues
## variables quantitatives var_quant=ccdefault.pd[['LIMIT_BAL','AGE','BILL_AMT4','BILL_AMT5','BILL_AMT6','PAY_AMT1','PAY_AMT2','PAY_AMT3','PAY_AMT4','PAY_AMT5','PAY_AMT6']] var_quant for col in var_quant: plt.figure() sns.distplot(var_quant[col])
/home/tabsoba/ML/lib/python3.8/site-packages/seaborn/distributions.py:2619: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms)....
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
2.2 Distribution des variables qualitatives
## variables qualitatives var_qual=ccdefault.pd[['SEX','MARRIAGE','EDUCATION','PAY_1','PAY_2','PAY_3','PAY_4','PAY_5','PAY_6']] var_qual ## Presentation des differentes catégories pour chaque variable qualitative for col in var_qual: print(f'{col:-<50} {var_qual[col].unique()}') ## Presentation des differentes cat...
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
2.3 Relation entre variables explicatives et variable cible
# Changement du code de 'SEX' (1,2) en 'F' and 'M' ccdefault.pd["SEX"]=ccdefault.pd["SEX"].map({1:'M',2:'F'}).astype('category') ccdefault.pd["SEX"].dtypes # Creation d'une nouvelle colonne nommée "RET_PAY" indiquant les clients ayant au moins un retard de payement de PAY_1 to Pay_6 # 0 : PAS_RETARD ; 1: RETARD con...
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
Relation entre la variable cible et le sexe, le status matrimonial et le niveau d'education des clients
var_qual1=["SEX","MARRIAGE","EDUCATION"] for col in var_qual1: relation_var(col)
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
Relation variable cible et age des clients
bornes= [21,30,40,50,60,70,80] tranches_ages = ['20-30','30-40','40-50','50-60','60-70','70-80'] ccdefault.pd['AGE'] = pd.cut(ccdefault.pd['AGE'],bins=bornes, labels=tranches_ages ,right=False) relation_var('AGE')
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
2.4 Tendance des paiements entre avril 2005 et septembre 2005
# Extraction des clients ayant au moins un retard de payement entre avril et septembre retard= ccdefault.pd[ccdefault.pd['RET_PAY']== 1] tendance= retard[['PAY_6','PAY_5','PAY_4','PAY_3','PAY_2','PAY_1']].sum(axis=0) fig,ax = plt.subplots() ax.plot(tendance) plt.xticks(['PAY_6','PAY_5','PAY_4','PAY_3','PAY_2','PAY_1'...
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
3. Etude comparative de modèles de machine learning pour la prediction de la variable cible
## Valeurs manquantes for c in ccdefaultNew.columns: count=ccdefaultNew.filter(c+" is NULL" or c+"is ''" or c+"is NaN" or c+"is null").count() print(str(count) +" valeurs manquantes dans la colonne "+ c) from pyspark.ml.feature import VectorAssembler, StringIndexer, VectorIndexer, MinMaxScaler from pysp...
_____no_output_____
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
3.1 Regression logistique
logit = LogisticRegression(labelCol = "label", featuresCol = "features", maxIter = 20, regParam = 0.2) model = logit.fit(ccdefault_train) predictions = model.transform(ccdefault_test) predictions.select("prediction", "label", "features").show(5) # select (prediction, true label) and compute test error evaluator = Bin...
+----------+-----+--------------------+ |prediction|label| features| +----------+-----+--------------------+ | 0.0| 0|[1.0,-3768.0,-393...| | 0.0| 0|[1.0,-2640.0,0.0,...| | 1.0| 1|(15,[0,1,2,4,5,6,...| | 0.0| 0|[1.0,-2000.0,780....| | 0.0| 0|(15,[0,1,2,4,5,6,...| ...
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
3.2 Arbre de decision
dt = DecisionTreeClassifier().setLabelCol("label").setFeaturesCol("features") # train the model dtModel = dt.fit(ccdefault_train) # make predictions on the test data predictions = dtModel.transform(ccdefault_test) predictions.select("prediction", "label", "features").show(5) # select (prediction, true label) and com...
+----------+-----+--------------------+ |prediction|label| features| +----------+-----+--------------------+ | 1.0| 1|[1.0,1.0,-6029.0,...| | 0.0| 0|[1.0,1.0,-6028.0,...| | 0.0| 0|[1.0,1.0,-3768.0,...| | 0.0| 0|[1.0,1.0,-2640.0,...| | 0.0| 0|(16,[0,1,2,4,5,6,...| ...
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
3.3 Forêt aleatoire
# TODO: Replace <FILL IN> with appropriate code rf = RandomForestClassifier().setLabelCol("label").setFeaturesCol("features") # train the model rfModel = rf.fit(ccdefault_train) # make predictions on the test data predictions = rfModel.transform(ccdefault_test) predictions.select("prediction", "label", "features")...
+----------+-----+--------------------+ |prediction|label| features| +----------+-----+--------------------+ | 1.0| 1|[1.0,1.0,-6029.0,...| | 0.0| 0|[1.0,1.0,-6028.0,...| | 0.0| 0|[1.0,1.0,-3768.0,...| | 0.0| 0|[1.0,1.0,-2640.0,...| | 0.0| 0|(16,[0,1,2,4,5,6,...| ...
MIT
Projet_ML.ipynb
maigaabdoul/Projet_ML
Explore Random Graphs Using NetworkX In this example, we build a simple UI for exploring random graphs with [NetworkX](http://networkx.github.io/).
from ipywidgets import interact %matplotlib inline import matplotlib.pyplot as plt import networkx as nx # wrap a few graph generation functions so they have the same signature def random_lobster(n, m, k, p): return nx.random_lobster(n, p, p / m) def powerlaw_cluster(n, m, k, p): return nx.powerlaw_cluster_gr...
_____no_output_____
BSD-3-Clause
docs/source/examples/Exploring Graphs.ipynb
vidartf/ipywidgets
How to read data from varius file formatssome of the most basic things noone ever treaches you is how to actually access your data in various formats. This notebook shows a couple of examples on how to read data from a number of sources. Feel free to edit this notebook with more methods that you have worked with.
#import relevant packages #from urllib.request import urlretrieve from urllib2 import urlopen import matplotlib.pyplot as plt import pandas as pd from sqlalchemy import create_engine import numpy as np from astropy.io import fits import urllib import h5py import pickle %matplotlib inline
_____no_output_____
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
importing files from the internet
# Assign url of file: url url ='https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv' # Save file locally testfile = urllib.URLopener() testfile.retrieve(url, "winequality-red.csv") # or use wget #file_name = wget.download(url) # Read file into a DataFrame and print its head...
fixed acidity volatile acidity citric acid residual sugar chlorides \ 0 7.4 0.70 0.00 1.9 0.076 1 7.8 0.88 0.00 2.6 0.098 2 7.8 0.76 0.04 2.3 0.092 3 ...
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
same thing with csv or txt file
example_sheet='cereal.csv' example_file='cereal.txt' xl = pd.read_csv(example_sheet) x2 = pd.read_csv(example_sheet) # akternatively you can use read_csv print (xl.keys()) # pandas lets you specify seperators as well as number of colums and filling nans #pd.read_csv(file, sep='\t', comment='#', na_v...
Index([u'name', u'mfr', u'type', u'calories', u'protein', u'fat', u'sodium', u'fiber', u'carbo', u'sugars', u'potass', u'vitamins', u'shelf', u'weight', u'cups', u'rating'], dtype='object')
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
Chunks
chunksize = 10 ** 6 for chunk in pd.read_csv(example_file,sep='\t', chunksize=chunksize): print len(chunk) # print len can be replaced with any process that you would want to use #similarly using read_table for chunk in pd.read_table(example_file,sep='\t', chunksize=chunksize): len(chunk)
77
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
reading fits files
filename= 'example.fits' hdulist = fits.open(filename) final_data = hdulist[1].data final_data.columns() final_data[1]
_____no_output_____
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
writing and reading HDF5 files
data_matrix = np.random.uniform(-1, 1, size=(10, 3)) # Write data to HDF5 data_file = h5py.File('file.hdf5', 'w') data_file.create_dataset('group_name', data=data_matrix) data_file.close() filename_hdf = 'file.hdf5' f = h5py.File(filename_hdf, 'r') # List all groups print("Keys: %s" % f.keys()) a_group_key = list(f...
Keys: [u'group_name']
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
SQL databasesassuming you want to read them into pythonalso have a look at the databases talk sarah gave (27/04/18)
# make sql database with pandas engine = create_engine('PATH') pd.to_sql('new_database', engine) pd.read_sql("SELCT * FROM new_database", engine)
_____no_output_____
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
Reading pickled filesI didn't have a pickled file ready so we will make a mock file to start with
your_data = {'foo': 'bar'} #makes dictionary #alternatively use pandas to make and read pickled files # Store data (serialize) with open('filename.pickle', 'wb') as handle: pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL) # Load data (deserialize) with open('filename.pickle', 'rb') as handle: ...
{'foo': 'bar'}
MIT
tutorials/file_types/reading_files.ipynb
mshamohammadi/cookies-n-code
Using Faker to generate fake data- https://faker.readthedocs.io/en/stable/
!pip3 install Faker==4.1.1 import pandas as pd df = pd.read_parquet("./techsparks_candidate_table_dataset_2.parquet") df df_sample = df.sample(1000) df_sample[df_sample['candidate_id'].str.contains("@")] from faker import Faker fake = Faker() import random def replace_fake_emails(val): if "@" in val: retur...
_____no_output_____
Apache-2.0
class3_null_and_conditions/generating_fake_data.ipynb
techsparksguru/data_analysis_pandas_spark_koalas
Filtering Rows
# import pandas import pandas as pd # read movie data movies = pd.read_csv("http://bit.ly/imdbratings") # examine first few rows movies.head()
_____no_output_____
CC0-1.0
book/pandas/08-Filtering Rows.ipynb
hossainlab/dsnotes
Filtering Movies with `for` Loop
booleans = [] for length in movies.duration: if length >= 200: booleans.append(True) else: booleans.append(False) # Check length of booleans len(booleans) # Inspect booleans elements booleans[0:5] # create a pandas series is_long = pd.Series(booleans) # Inspect few values is_long.head() ...
_____no_output_____
CC0-1.0
book/pandas/08-Filtering Rows.ipynb
hossainlab/dsnotes
Filtering by Condition
# filtering by conditions is_long = movies.duration >= 200 is_long.head() # show the rows duration >200 movies[is_long]
_____no_output_____
CC0-1.0
book/pandas/08-Filtering Rows.ipynb
hossainlab/dsnotes
Filtering in DataFrame
# filtering by columns movies[movies.duration >= 200] # select only genre movies[movies.duration >= 200].genre # same as above movies[movies.duration >= 200]['genre'] # select columns by label movies.loc[movies.duration >= 200, 'genre']
_____no_output_____
CC0-1.0
book/pandas/08-Filtering Rows.ipynb
hossainlab/dsnotes
Multiple Filtering Criteria
# True and True == True # True and False == False # True or True == True # True or False == True # False or False == False True and True True and False True or True True or False # multiple criteria movies[(movies.duration >= 200) & (movies.genre == 'Drama')] # multiple criteria movies[(movies.duration >= 200)...
_____no_output_____
CC0-1.0
book/pandas/08-Filtering Rows.ipynb
hossainlab/dsnotes
The following Model Project is based on the classic Solow model as we know it from Macroeconomics. First, we will model the Solow model in its simplest form. Next we will build on this simple Solow model by adding Total Factor Productivity (TFP).1) Our model is defined by the framework below. Note that TFP is not part ...
#Below is run to get LaTex format sm.init_printing(use_unicode=True) # Define varibles k = sm.symbols('k') y = sm.symbols('y') K = sm.symbols('K') B = sm.symbols('B') L = sm.symbols('L') Y = sm.symbols('Y') alpha = sm.symbols('alpha') delta = sm.symbols('delta') s = sm.symbols('s') n = sm.symbols('n') # Define tran...
Steady state for y is
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
Above we have found the expression for steady state in capital per capita and income per capita. We test our steady state expressions by plugging in arbitrary values for each parameter in each expression: $B=1.5$, $s=0.20$, $n=2\%$, $\alpha=\frac{1}{3}$ and $\delta=1$. We use a simple function: solution(x), to retriev...
s=0.2 n=0.02 delta=1 alpha=1/3 B=10 opt_steadystate_k1= lambda steadystate_k1: steadystate_k1 - ( ((1)/(1+n)*(s*B*(steadystate_k1)**alpha+(1-delta)*steadystate_k1)) ) result1 = optimize.root_scalar(opt_steadystate_k1,bracket=[0.1,10],method='brentq') print('the steady state for k is', result1.root)
the steady state for k is 2.74564722358436
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
Given the specified parameter values, steady state of capital per capita is 2.75. We now wish to investigate how the steady state value of capital per capita changes when the savings rate changes by an arbitrary amount.
n=0.02 delta=1 alpha=1/3 B=10 savings = [0.05,0.1,0.2,0.25,0.4,0.5,0.75,0.9] for s1 in savings: obj_kss = lambda steadystate_k1: steadystate_k1 - ((1)/(1+n)*(s1*B*(steadystate_k1)**alpha+(1-delta)*steadystate_k1)) result1 = optimize.root_scalar(obj_kss,bracket=[0.1,1000],method='brentq') print(f'for saving...
for savings = 0.050 the steady state for k is 0.343205902947649 for savings = 0.100 the steady state for k is 0.9707328852712966 for savings = 0.200 the steady state for k is 2.7456472235841 for savings = 0.250 the steady state for k is 3.8371586463550824 for savings = 0.400 the steady state for k is 7.765863082169994 ...
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
From above result it is instantly clear that the savings rate, s, has a substantial impact on the capital accumulation in the society. Below is a visualisation of how the parameteres impact the accumulation of capital as well as income.In order to create this visualisation, our next step is to create an interactive gra...
# We define below the possible numeric intervals of the parameters alpha = np.arange(0,1) s = np.arange(0,1) k = np.arange(100) B = np.arange(0,100) n = np.arange(0,0.2) delta = np.arange(0,1.1) def interactive_transition1(B,s,alpha,n,delta,k): k0 = ((1)/(1+n)*(s*B*(k**alpha)+(1-delta)*k)) m0 = k #plt.pl...
_____no_output_____
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
In the figure we notice that as B, s and alpha increases, so does steady state for capital accumulation. Conversely, when n and delta increase, steady state for capital accumulation decreases. **2) We now consider the Solow-model with a productive externality per worker where:**A small closed economy can be described b...
#Below is run to get LaTex format sm.init_printing(use_unicode=True) # Define additional variables # Define varibles k = sm.symbols('k') y = sm.symbols('y') K = sm.symbols('K') B = sm.symbols('B') L = sm.symbols('L') Y = sm.symbols('Y') alpha = sm.symbols('alpha') delta = sm.symbols('delta') s = sm.symbols('s') n = sm....
Steady state for y is
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
Above we have found the expression for steady state in capital per capita and income per capits. We test our steady state expressions by plugging in arbitrary values for each parameter in each expression: $B=10$, $s=0.20$, $n=2\%$, $\alpha=\frac{1}{3}$, $\phi=0.56$. We use a simple function: solution(x), to retrieve a...
print('Inserting the values gives the steadystate value of:') Solution=sm.lambdify((B,s,n,alpha,phi),steadystate_k) Solution(10, 0.2, 0.02, 1/3, 0.4) s=0.2 n=0.02 phi=0.4 alpha=1/3 B=10 f = lambda k: A*k**alpha opt_steadystate_k= lambda steadystate_k: steadystate_k - ( ((s*B)/(1+n))*steadystate_k**(alpha+phi*(1-alpha)...
the steady state for k is 5.383622007028104
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
Given the specified parameter values, steady state of capital per capita is 5.38. We now wish to investigate how the steady state value of capital per capita changes when the savings rate changes by an arbitrary amount.
n=0.02 phi=0.4 alpha=1/3 B=10 savings_rate = [0.05,0.1,0.2,0.25,0.4,0.5,0.75,0.9] for s1 in savings_rate: f = lambda k: A*k**alpha opt_steadystate_k= lambda steadystate_k: steadystate_k - ( ((s1*B)/(1+n))*steadystate_k**(alpha+phi*(1-alpha)) ) result = optimize.root_scalar(opt_steadystate_k,bracket=[0.1,100...
for s = 0.050 the steady state for k is 0.16823818771955754 for s = 0.100 the steady state for k is 0.951698907128675 for s = 0.200 the steady state for k is 5.383622007028105 for s = 0.250 the steady state for k is 9.40480060381148 for s = 0.400 the steady state for k is 30.4543650281175 for s = 0.500 the steady state...
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
Similar to part 1, it is instantly clear that the savings rate, s, has a substantial impact on the capital accumulation in the society. Below is a visualisation of how the parameteres impact the accumulation of capital as well as income.Our next step is to create an interactive graph plotting the transition curve and t...
alpha = np.arange(0,1) s = np.arange(0,1) k = np.arange(100) B = np.arange(0,100) n = np.arange(0,0.2) phi = np.arange(0,1) y = np.arange(100) def interactive_transition(B,s,alpha,n,phi,k): k1 = ( ((s*B)/(1+n))*k**(alpha+phi*(1-alpha)) ) m = k #plt.plot(m) fig = plt.figure(dpi=90) ax...
_____no_output_____
MIT
modelproject/modelproject/ModelProject7.ipynb
NumEconCopenhagen/projects-2019-athena
L = 2, W_chain, AdamCalculate $var(Z\otimes Z) = (\langle\tilde{\psi}|ZZ|\tilde{\psi}\rangle^2 - \langle\psi|ZZ|\psi\rangle^2)$
import sys sys.path.insert(1, '../') import qtm.fubini_study import qtm.nqubit import qtm.base num_layers = 2 thetas = np.ones(num_layers*num_qubits*4) qc = qiskit.QuantumCircuit(num_qubits, num_qubits) qc.initialize(psi, range(0, num_qubits)) loss_values = [] thetass = [] for i in range(0, 400): if i % 20 == 0...
_____no_output_____
MIT
codes/tomography/shadow_tomography2.ipynb
vutuanhai237/QuantumTomography
Building a docker container for training/deploying our classifierIn this exercise we'll create a Docker image that will have the required code for training and deploying a ML model. In this particular example, we'll use scikit-learn (https://scikit-learn.org/) and the **Random Forest Tree** implementation of that libr...
%%writefile train.py import os import pandas as pd import re import joblib import json import traceback import sys from sklearn.ensemble import RandomForestClassifier def load_dataset(path): # Take the set of files and read them all into a single pandas dataframe files = [ os.path.join(path, file) for file in ...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
1.2 Ok. Lets then create the handler. The **Inference Handler** is how we use the SageMaker Inference Toolkit to encapsulate our code and expose it as a SageMaker container.SageMaker Inference Toolkit: https://github.com/aws/sagemaker-inference-toolkit
%%writefile handler.py import os import sys import joblib from sagemaker_inference.default_inference_handler import DefaultInferenceHandler from sagemaker_inference.default_handler_service import DefaultHandlerService from sagemaker_inference import content_types, errors, transformer, encoder, decoder class HandlerSer...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
1.3 Now we need to create the entrypoint of our container. The main functionWe'll use **SageMaker Training Toolkit** (https://github.com/aws/sagemaker-training-toolkit) to work with the arguments and environment variables defined by SageMaker. This library will make our code simpler.
%%writefile main.py import train import argparse import sys import os import traceback from sagemaker_inference import model_server from sagemaker_training import environment if __name__ == "__main__": if len(sys.argv) < 2 or ( not sys.argv[1] in [ "serve", "train" ] ): raise Exception("Invalid argument: y...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
1.4 Then, we can create the DockerfileJust pay attention to the packages we'll install in our container. Here, we'll use **SageMaker Inference Toolkit** (https://github.com/aws/sagemaker-inference-toolkit) and **SageMaker Training Toolkit** (https://github.com/aws/sagemaker-training-toolkit) to prepare the container f...
%%writefile Dockerfile FROM python:3.7-buster # Set a docker label to advertise multi-model support on the container LABEL com.amazonaws.sagemaker.capabilities.multi-models=false # Set a docker label to enable container to use SAGEMAKER_BIND_TO_PORT environment variable if present LABEL com.amazonaws.sagemaker.capabil...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
1.5 Finally, let's create the buildspecThis file will be used by CodeBuild for creating our Container image. With this file, CodeBuild will run the "docker build" command, using the assets we created above, and deploy the image to the Registry. As you can see, each command is a bash command that will be executed fro...
%%writefile buildspec.yml version: 0.2 phases: install: runtime-versions: docker: 18 pre_build: commands: - echo Logging in to Amazon ECR... - $(aws ecr get-login --no-include-email --region $AWS_DEFAULT_REGION) build: commands: - echo Build started on `date` - echo Bui...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
PART 2 - Local Test: Let's build the image locally and do some tests 2.1 Building the image locally, firstEach SageMaker Jupyter Notebook already has a **docker** envorinment pre-installed. So we can play with Docker containers just using the same environment.
!docker build -f Dockerfile -t iris_model:1.0 .
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
2.2 Now that we have the algorithm image we can run it to train/deploy a model Then, we need to prepare the datasetYou'll see that we're splitting the dataset into training and validation and also saving these two subsets of the dataset into csv files. These files will be then uploaded to an S3 Bucket and shared with...
!rm -rf input !mkdir -p input/data/train !mkdir -p input/data/validation import pandas as pd import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split iris = datasets.load_iris() dataset = np.insert(iris.data, 0, iris.target,axis=1) df = pd.DataFrame(data=dataset, columns...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
2.3 Just a basic local test, using the local Docker daemonHere we will simulate SageMaker calling our docker container for training and serving. We'll do that using the built-in Docker Daemon of the Jupyter Notebook Instance.
!rm -rf input/config && mkdir -p input/config %%writefile input/config/hyperparameters.json {"max_depth": 20, "n_jobs": 4, "n_estimators": 120} %%writefile input/config/resourceconfig.json {"current_host": "localhost", "hosts": ["algo-1-kipw9"]} %%writefile input/config/inputdataconfig.json {"train": {"TrainingInputMod...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
2.4 This is the serving test. It simulates an Endpoint exposed by SagemakerAfter you execute the next cell, this Jupyter notebook will freeze. A webservice will be exposed at the port 8080.
!docker run --rm --name "my_model" \ -p 8080:8080 \ -v "$PWD/model:/opt/ml/model" \ -v "$PWD/input:/opt/ml/input" iris_model:1.0 serve
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
> While the above cell is running, click here [TEST NOTEBOOK](02_Testing%20our%20local%20model%20server.ipynb) to run some tests.> After you finish the tests, press **STOP** PART 3 - Integrated Test: Everything seems ok, now it's time to put all togetherWe'll start by running a local **CodeBuild** test, to check the b...
import boto3 sts_client = boto3.client("sts") session = boto3.session.Session() account_id = sts_client.get_caller_identity()["Account"] region = session.region_name credentials = session.get_credentials() credentials = credentials.get_frozen_credentials() repo_name="iris-model" image_tag="test" !sudo rm -rf tests &...
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
> Now that we have an image deployed in the ECR repo we can also run some local tests using the SageMaker Estimator.> Click on this [TEST NOTEBOOK](03_Testing%20the%20container%20using%20SageMaker%20Estimator.ipynb) to run some tests.> After you finishing the tests, come back to **this notebook** to push the assets to ...
%%bash cd ../../../mlops git branch iris_model git checkout iris_model cp $OLDPWD/buildspec.yml $OLDPWD/handler.py $OLDPWD/train.py $OLDPWD/main.py $OLDPWD/Dockerfile . git add --all git commit -a -m " - files for building an iris model image" git push --set-upstream origin iris_model
_____no_output_____
MIT-0
lab/01_CreateAlgorithmContainer/01_Creating a Classifier Container.ipynb
doctorai-in/amazon-sagemaker-workshop
PoseNet
import torch import cv2 import time #import argparse import posenet #parser = argparse.ArgumentParser() #parser.add_argument('--model', type=int, default=101) #parser.add_argument('--cam_id', type=int, default=0) #parser.add_argument('--cam_width', type=int, default=1280) #parser.add_argument('--cam_height', type=int...
_____no_output_____
MIT
lstm_run_posenet.ipynb
haithienld/har
Convert to TensorRT
import torch from torch2trt import torch2trt model = LSTM(n_joints,n_hidden,n_categories,n_layer) model.load_state_dict(torch.load('lstm_6_bn.pkl')) rnn.cuda().eval() x = torch.ones((1,32,36)).half().cuda() rnn(x) import pdb pdb.pm() class LSTM(nn.Module): def __init__(self): super(LSTM,self).__init__...
_____no_output_____
MIT
lstm_run_posenet.ipynb
haithienld/har
Simulate Artificial Physiological Signals Neurokit's core signal processing functions surround electrocardiogram (ECG), respiratory (RSP), electrodermal activity (EDA), and electromyography (EMG) data. Hence, this example shows how to use Neurokit to simulate these physiological signals with customized parametric cont...
# Load NeuroKit and other useful packages import neurokit2 as nk import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = [8, 5] # Bigger images
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
Cardiac Activity (ECG) With `ecg_simulate()`, you can generate an artificial ECG signal of a desired length (in this case here, `duration=10`), noise, and heart rate. As you can see in the plot below, *ecg50* has about half the number of heart beats than *ecg100*, and *ecg50* also has more noise in the signal than the...
# Alternate heart rate and noise levels ecg50 = nk.ecg_simulate(duration=10, noise=0.05, heart_rate=50) ecg100 = nk.ecg_simulate(duration=10, noise=0.01, heart_rate=100) # Visualize pd.DataFrame({"ECG_100": ecg100, "ECG_50": ecg50}).plot()
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
You can also choose to generate the default, simple simulation based on Daubechies wavelets, which roughly approximates one cardiac cycle, or a more complex one by specifiying `method="ecgsyn"`.
# Alternate methods ecg_sim = nk.ecg_simulate(duration=10, method="simple") ecg_com = nk.ecg_simulate(duration=10, method="ecgsyn") # Visualize pd.DataFrame({"ECG_Simple": ecg_sim, "ECG_Complex": ecg_com}).plot(subplots=True)
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
Respiration (RSP) To simulate a synthetic respiratory signal, you can use `rsp_simulate()` and choose a specific duration and breathing rate. In this example below, you can see that *rsp7* has a lower breathing rate than *rsp15*. You can also decide which model you want to generate the signal. The *simple rsp15* signa...
# Simulate rsp15_sim = nk.rsp_simulate(duration=20, respiratory_rate=15, method="sinusoidal") rsp15_com = nk.rsp_simulate(duration=20, respiratory_rate=15, method="breathmetrics") rsp7 = nk.rsp_simulate(duration=20, respiratory_rate=7, method="breathmetrics") # Visualize respiration rate pd.DataFrame({"RSP7": rsp7, ...
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
Electromyography (EMG) Now, we come to generating an artificial EMG signal using `emg_simulate()`. Here, you can specify the number of bursts of muscular activity (`n_bursts`) in the signal as well as the duration of the bursts (`duration_bursts`). As you can see the active muscle periods in *EMG2_Longer* are greater ...
# Simulate emg2 = nk.emg_simulate(duration=10, burst_number=2, burst_duration=1.0) emg2_long = nk.emg_simulate(duration=10, burst_number=2, burst_duration=1.5) emg5 = nk.emg_simulate(duration=10, burst_number=5, burst_duration=1.0) # Visualize pd.DataFrame({"EMG2": emg2, "EMG2_Longer": emg2_long, ...
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
Electrodermal Activity (EDA) Finally, `eda_simulate()` can be used to generate a synthetic EDA signal of a given duration, specifying the number of skin conductance responses or activity 'peaks' (`n_scr`) and the `drift` of the signal. You can also modify the noise level of the signal.
# Simulate eda1 = nk.eda_simulate(duration=10, scr_number=1, drift=-0.01, noise=0.05) eda3 = nk.eda_simulate(duration=10, scr_number=3, drift=-0.01, noise=0.01) eda3_long = nk.eda_simulate(duration=10, scr_number=3, drift=-0.1, noise=0.01) # Visualize pd.DataFrame({"EDA1": eda1, "EDA3": eda3, ...
_____no_output_____
MIT
docs/examples/simulation.ipynb
vansjyo/NeuroKit
from Users' Bio Url
reddit_users = data[data['author.entities.url.urls'].str.contains('reddit.com/u', na=False)] # reddit_users.to_csv('reddit_users_2020.csv') reddit_users=reddit_users.drop_duplicates(subset=['author.username']).reset_index() # reddit_users.to_csv('reddit_unique_users_2020.csv') reddit_users.info() index=40 print(reddit_...
<ipython-input-195-0f4a9594bba6>:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-c...
MIT
UserName_extraction.ipynb
ali-darvishi/crossPlatform-account-linking
From Source
reddit_source = data[data['source']=='Reddit Official'] # reddit_source=reddit_source.drop_duplicates(subset=['author.username']).reset_index() # reddit_source.to_csv('reddit_unique_source_2020.csv') reddit_source.info() reddit_source_user = reddit_source[reddit_source['entities.urls'].str.contains('reddit.com/r/u_', n...
<ipython-input-223-07455e72156e>:2: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-c...
MIT
UserName_extraction.ipynb
ali-darvishi/crossPlatform-account-linking
A/B Testing from Scratch: Frequentist Approach Frequentist A/B testing is one of the most used and abused statistical methods in the world. This article starts with a simple problem of comparing two online ads campaigns (or teatments, user interfaces or slot machines). It outlines several useful statistical concepts ...
# #depedencies for colab # %%capture # !pip install plotnine import numpy as np import pandas as pd from typing import Collection, Tuple #widgets เอาออก เปลี่ยนไปใช้ colab form แทน #from ipywidgets import interact, interactive, fixed, interact_manual #import ipywidgets as widgets # from IPython.display import display ...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
Start with A Problem A typical situation marketers (research physicians, UX researchers, or gamblers) find themselves in is that they have two variations of ads (treatments, user interfaces, or slot machines) and want to find out which one has the better performance in the long run.Practitioners know this as A/B testi...
def gen_bernoulli_campaign(p1: float, p2: float, lmh: Collection = [500, 1000, 1500], timesteps: int = 60, scaler: float = 300, seed: int = 1412) -> pd.DataFrame: ''' :meth: generate fake impression-conversion campaign based on spe...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
Random Variables and Probability Distributions Take a step back and think about the numbers we consider in our daily routines, whether it is conversion rate of an ads campaign, the relative risk of a patient group, or sales and revenues of a shop during a given period of time. From our perspective, they have one thing...
def bernoulli(n,p): flips = np.random.choice([0,1], size=n, p=[1-p,p]) flips_df = pd.DataFrame(flips) flips_df.columns = ['conv_flag'] g = (ggplot(flips_df,aes(x='factor(conv_flag)')) + geom_bar(aes(y = '(..count..)/sum(..count..)')) + theme_minimal() + xlab('Conversion Flag') + ylab('Percenta...
Expectation: 0.1 Variance: 0.09000000000000001 Sample Mean: 0.05 Sample Variance: 0.04749999999999999
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
**Probability distribution** is represented with the values of a random variable we are interested in the X-axis, and the chance of them appearing after a number of trials in the Y-axis. The distribution above is called [Bernoulli Distribution](http://mathworld.wolfram.com/BernoulliDistribution.html), usually used to m...
def lln(n_max,p): mean_flips = [] var_flips = [] ns = [] for n in range(1,n_max): flips = np.random.choice([0,1], size=n, p=[1-p,p]) ns.append(n) mean_flips.append(flips.mean()) var_flips.append(flips.var()) flips_df = pd.DataFrame({'n':ns,'mean_flips':mean_flips,'var...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
Notice that even though LLN does not says that sample variance will also converge to variance as $n$ grows large enough, it is also the case. Mathematically, it can be derived as follows:\begin{align}s^2 &= \frac{1}{n}\sum_{i=1}^{n}(X_i - \bar{X}^2) \\&= \frac{1}{n}\sum_{i=1}^{n}(X_i - \mu)^2 \text{; as }n\rightarrow\i...
c_df = pd.DataFrame({'campaign_id':'C','clicks':1000,'conv_cnt':107,'conv_per':0.107},index=[0]) c_df
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
CLT goes as follows: > If $X_i$ is an independent and identically distributed (i.i.d.) random variable with expectation $\mu$ and variance $\sigma^2$ and $\bar{X_j}$ is the sample mean of $n$ samples of $X_i$ we drew as part of sample group $j$, then when $n$ is large enough, $\bar{X_j}$ will follow a [normal distribut...
ind_df = pd.DataFrame({'iid':[False]*100+[True]*100, 'order': list(range(100)) + list(range(100)), 'conv_flag':[1]*50+ [0]*50+ list(np.random.choice([0,1], size=100))}) g = (ggplot(ind_df,aes(x='order',y='conv_flag',color='iid')) + geom_point() + facet_wrap('~iid') + t...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
**and $\bar{X_j}$ is the sample mean of $n$ samples of $X_i$ we drew as part of sample group $j$, then**For campaign `C`, we can think of all the clicks we observed as one sample group, which exists in parallel with an infinite number of sample groups that we have not seen yet but can be drawn from the distribution by ...
def clt(n, dist): n_total = n * 10000 if dist == 'discrete uniform': r = np.random.uniform(size=n_total) elif dist =='bernoulli': r = np.random.choice([0,1],size=n_total,p=[0.9,0.1]) elif dist =='poisson': r = np.random.poisson(size=n_total) else: raise ValueError('Ch...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
The expectation and variance of the sample mean distribution can be derived as follows:\begin{align}E[\bar{X_j}] &= E[\frac{\sum_{i=1}^{n} X_i}{n}] \\&= \frac{1}{n} \sum_{i=1}^{n} E[X_i] = \frac{1}{n} \sum_{i=1}^{n} \mu\\&= \frac{n\mu}{n} = \mu \\Var(\bar{X_j}) &= Var(\frac{\sum_{i=1}^{n} X_i}{n}) \\&= \frac{1}{n^2} \s...
n = c_df.clicks[0] x_bar = c_df.conv_per[0] p = 0.1 mu = p; variance = p*(1-p)/n; sigma = (variance)**(0.5) # mu = 0; variance = 1; sigma = (variance)**(0.5) x = np.arange(0.05, 0.15, 1e-3) y = np.array([sp.stats.norm.pdf(i, loc=mu, scale=sigma) for i in x]) sm_df = pd.DataFrame({'x': x, 'y': y, 'crit':[False if i>x_b...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
As long as we know the expectation (which we usually do as part of the assumption) and variance (which is more tricky) of the base distribution, we can use this normal distribution to model random variable from *any* distribution. That is, we can model *any* data as long as we can assume their expectation and variance....
g = (ggplot(sm_df, aes(x='x', y='y', group='crit')) + geom_area(aes(fill='crit')) + theme_minimal() + xlab('Sample Means') + ylab('Probability Density Function') + ggtitle('Sample mean distribution under our assumption') + guides(fill=guide_legend(title="Conversion Rate < 0.1"))) g
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
Whether 23% is unlikely *beyond reasonable doubt* depends on how much we are willing to tolerate the false positive rate (the percentage of innocent people you are willing to execute). By convention, a lot of practioners set this to 1-5% depending on their problems; for instance, an experiment in physics may use 1% or ...
def shift_normal(m,v): n = c_df.clicks[0] x_bar = c_df.conv_per[0] p = 0.1 mu = p; variance = p*(1-p)/n; sigma = (variance)**(0.5) x = np.arange(0.05, 0.15, 1e-3) y = np.array([sp.stats.norm.pdf(i, loc=mu, scale=sigma) for i in x]) sm_df = pd.DataFrame({'x': x, 'y': y}) #normalize p...
Expectation of sample mean: 0.0; Variance of sample mean: 1.0
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest
By shifting and scaling, we can find out where `C`'s sample mean of 0.107 lands on the X-axis of a standard normal distribution:\begin{align}\bar{Z_j} &= \frac{\bar{X_j} - \mu}{\sigma / \sqrt{n}} \\&= \frac{0.107 - 0.1}{0.3 / \sqrt{1000}} \approx 0.7378648\\\end{align} With $\bar{Z_j}$ and $-\bar{Z_j}$, we can calculat...
n = c_df.clicks[0] x_bar = c_df.conv_per[0] p = 0.1; mu = p; variance = p*(1-p)/n; sigma = (variance)**(0.5) x_bar_norm = (x_bar - mu) / sigma def standard_normal(x_bar_norm, legend_title): x_bar_norm = abs(x_bar_norm) x = np.arange(-3, 3, 1e-2) y = np.array([sp.stats.norm.pdf(i, loc=0, scale=1) for i in x...
_____no_output_____
Apache-2.0
notebooks/frequentist_colab.ipynb
cstorm125/abtest