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
However, insofar as user input is concerned, we can test it _or_ we can use it as something called a "sentinel" value. Using word "sentinel" here means exactly what it means in normal speech -- something to watch out for, like the following:
# Setup choice choice = "" # Do the loop while choice != "E": # Print message to relay the user's choice print("The loop is running.") choice = input("[C]ontinue or [E]xit? ") print("You chose to exit!")
_____no_output_____
CC-BY-4.0
day-2/0_week-0-worksheet-while-loops.ipynb
allegheny-college-cmpsc-100-jan-2021/week-0
Mean`while`The conclusion we should draw from our little detour is this: `while` statements are exceptionally good at handling all kinds of `boolean` conditions. When it's merely simple counting, like our countdown example above, it's OK, too -- but, as we'll see in the near future, counting and other more complex tes...
# NOTE: YOU MUST RUN THIS CELL TO MAKE THESE VARIABLES AVAILABLE # NOTE 2: RUN THIS CELL TO RESET ALL NUMBERS AS WELL # Setup variable to handle input number = "" # Setup variable to keep running total sum = 0 # Setup a count variable to track the count count = 0 # TODO: Write code to complete activity using knowle...
_____no_output_____
CC-BY-4.0
day-2/0_week-0-worksheet-while-loops.ipynb
allegheny-college-cmpsc-100-jan-2021/week-0
" backtesting with grid search"> "Easily backtest a grid of parameters in a given trading strategy"- toc: true- branch: master- badges: true- comments: true- author: Jerome de Leon- categories: [grid search, backtest]
# uncomment to install in colab # !pip3 install fastquant
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
backtest SMAC `fastquant` offers a convenient way to backtest several trading strategies. To backtest using Simple Moving Average Crossover (`SMAC`), we do the following.```pythonbacktest('smac', dcv_data, fast_period=15, slow_period=40)````fast_period` and `slow_period` are two `SMAC` parameters that can be changed d...
from fastquant import get_stock_data, backtest symbol='JFC' dcv_data = get_stock_data(symbol, start_date='2018-01-01', end_date='2020-04-28', format='cv', ) dcv_data.head() import matplotlib.pyplot as pl pl.style.use("default") from fastq...
===Global level arguments=== init_cash : 100000 buy_prop : 1 sell_prop : 1 ===Strategy level arguments=== fast_period : 15 slow_period : 40 Final PnL: -31257.65 Time used (seconds): 0.10944700241088867 Optimal parameters: {'init_cash': 100000, 'buy_prop': 1, 'sell_prop': 1, 'execution_type': 'close', 'fast_period': 15,...
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
The plot above is optional. `backtest` returns a dataframe of parameters and corresponding metrics:
results.head()
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
define the search space Second, we specify the range of reasonable values to explore for `fast_period` and `slow_period`. Let's take between 1 and 20 trading days (roughly a month) in steps of 1 day for `fast_period`, and between 21 and 240 trading days (roughly a year) in steps of 5 days for `slow_period`.
import numpy as np fast_periods = np.arange(1,20,1, dtype=int) slow_periods = np.arange(20,241,5, dtype=int) # make a grid of 0's (placeholder) period_grid = np.zeros(shape=(len(fast_periods),len(slow_periods))) period_grid.shape
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
run grid search Third, we run backtest for each iteration over each pair of `fast_period` and `slow_period`, saving each time the net profit to the `period_grid` variable. Note: Before running backtest over a large grid, try measuring how long it takes your machine to run one backtest instance.```python%timeitbacktest...
from time import time init_cash=100000 start_time = time() for i,fast_period in enumerate(fast_periods): for j,slow_period in enumerate(slow_periods): results = backtest('smac', dcv_data, fast_period=fast_period, slow_peri...
Basic grid search took 100.4 sec
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
visualize the period grid Next, we visualize `period_grid` as a 2D matrix.
import matplotlib.colors as mcolors import matplotlib.pyplot as pl pl.style.use("default") fig, ax = pl.subplots(1,1, figsize=(8,4)) xmin, xmax = slow_periods[0],slow_periods[-1] ymin, ymax = fast_periods[0],fast_periods[-1] #make a diverging color map such that profit<0 is red and blue otherwise cmap = pl.get_cmap('...
max profit=7042 @ (105,3) days
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
From the plot above, there are only a few period combinations which we can guarantee non-negative net profit using SMAC strategy. The best result is achieved with (105,30) for period_slow and period_fast, respectively.In fact SMAC strategy is so bad such that there is only 9% chance it will yield profit when using any ...
percent_positive_profit=(period_grid>0).sum()/np.product(period_grid.shape)*100 percent_positive_profit percent_breakeven=(period_grid==0).sum()/np.product(period_grid.shape)*100 percent_breakeven
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
Anyway, let's check the results of backtest using the `best_fast_period` and `best_slow_period`.
results = backtest('smac', dcv_data, fast_period=best_fast_period, slow_period=best_slow_period, verbose=True, plot=True ) net_profit = results.final_value.values[0]-init_cash net_profit
Starting Portfolio Value: 100000.00 ===Global level arguments=== init_cash : 100000 buy_prop : 1 sell_prop : 1 ===Strategy level arguments=== fast_period : 3 slow_period : 105 2018-08-22, BUY CREATE, 286.00 2018-08-22, Cash: 100000.0 2018-08-22, Price: 286.0 2018-08-22, Buy prop size: 346 2018-08-22, Afforded size: 346...
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
There are only 6 cross-over events of which only the latest transaction yielded positive gains resulting to a 7% net profit. Is 7% profit over a ~two-year baseline better than the market benchmark? built-in grid search in fastquant The good news is `backtest` provides a built-in grid search if strategy parameters are ...
from fastquant import backtest start_time = time() results = backtest("smac", dcv_data, fast_period=fast_periods, slow_period=slow_periods, verbose=False, plot=False ) end_time = time() time_optimized ...
Optimized grid search took 95.6 sec
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
`results` is automatically ranked based on `rnorm` which is a proxy for performance. In this case, the best `fast_period`,`slow_period`=(8,200) d.The returned parameters are should have `len(fast_periods)`x`len(slow_periods)` (19x45=855 in this case).
results.shape results.head()
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
Now, we recreate the 2D matrix before, but this time using scatter plot.
fig, ax = pl.subplots(1,1, figsize=(8,4)) #make a diverging color map such that profit<0 is red and blue otherwise cmap = pl.get_cmap('RdBu') norm = mcolors.TwoSlopeNorm(vmin=period_grid.min(), vmax = period_grid.max(), vcenter=0 )...
max profit=7042 @ (105.0,3.0) days
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
Note also that built-in grid search in `backtest` is optimized and slightly faster than the basic loop-based grid search.
#time time_basic/time_optimized
_____no_output_____
MIT
examples/2020-04-20-backtest_with_grid_search.ipynb
johnmarkacala/fastquant
IBM Data Science Specialization Course 9: Applied Data ScienceThis notebook will be mainly used for the capstone project.
import pandas as pd import numpy as np print ('Hello Capstone Project Course!') # The code was removed by Watson Studio for sharing.
_____no_output_____
CC-BY-4.0
IBM_CRS9_W1_Capstone_Notebook.ipynb
mcmasty/Coursera_Capstone
Python and MySQL First import the python module containing the API
import pymysql
_____no_output_____
MIT
BAMM.101x/sql_and_python.ipynb
KECB/learn
Set up a connection and create a cursor object
db = pymysql.connect("localhost","root","None" ,database="schooldb") cursor = db.cursor()
_____no_output_____
MIT
BAMM.101x/sql_and_python.ipynb
KECB/learn
Execute a query and get the results
cursor.execute('show tables;') cursor.fetchall() query = """ SELECT course.name FROM student INNER JOIN enrolls_in ON student.ssn = enrolls_in.ssn INNER JOIN course ON course.number = enrolls_in.class WHERE f_name = "JOHN"; """ cursor.execute(query) cursor.fetchall() # 向数据库插入数据 insert = 'INSERT INTO S...
_____no_output_____
MIT
BAMM.101x/sql_and_python.ipynb
KECB/learn
Preprocessing
# Import our dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd import tensorflow as tf # Import and read the charity_data.csv. import pandas as pd application_df = pd.read_csv("Resources/charity_data.csv") application_df.head() # Dr...
(25724, 45)
ADSL
Starter_Code.ipynb
ichakrabarty/Deep-Learning-Homework-Charity-Funding-Predictor
Compile, Train and Evaluate the Model
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer. nn = tf.keras.models.Sequential() # First hidden layer nn.add(tf.keras.layers.Dense(units=80, activation ='relu', input_dim = 45)) # Second hidden layer nn.add(tf.keras.layers.Dense(units=30, activation ='relu',...
_____no_output_____
ADSL
Starter_Code.ipynb
ichakrabarty/Deep-Learning-Homework-Charity-Funding-Predictor
Attempt 2
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer. nn = tf.keras.models.Sequential() # First hidden layer nn.add(tf.keras.layers.Dense(units=80, activation ='relu', input_dim = 45)) # Second hidden layer nn.add(tf.keras.layers.Dense(units=30, activation ='relu',...
_____no_output_____
ADSL
Starter_Code.ipynb
ichakrabarty/Deep-Learning-Homework-Charity-Funding-Predictor
Attempt 3
# Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer. nn = tf.keras.models.Sequential() # First hidden layer nn.add(tf.keras.layers.Dense(units=80, activation ='relu', input_dim = 45)) # Second hidden layer nn.add(tf.keras.layers.Dense(units=30, activation ='sigmoi...
_____no_output_____
ADSL
Starter_Code.ipynb
ichakrabarty/Deep-Learning-Homework-Charity-Funding-Predictor
Tabular Q-Learning From Scratch Custom Environment to train our model on
import gym from gym import spaces import numpy as np import random from copy import deepcopy class gridworld_custom(gym.Env): """Custom Environment that follows gym interface""" metadata = {'render.modes': ['human']} def __init__(self, *args, **kwargs): super(gridworld_custom, self).__init__() ...
_____no_output_____
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Import Required Packages
import numpy as np import matplotlib.pyplot as plt from copy import deepcopy import pandas as pd #from tqdm.auto import tqdm from tqdm import tqdm
_____no_output_____
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Build the q-learning class which contains the table storing all the q values for all states and actions
class q_learning(): def __init__(self): self.q_table = pd.DataFrame(columns=['state', 'q_val_0', 'q_val_1', 'q_val_2', 'q_val_3']) for i in range(5): for j in range(5): state_str = "("+str(i)+","+str(j)+")" X = pd.DataFrame([[state_str, 0, 0, 0, 0]],...
_____no_output_____
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Check up the functionality of epsilon greedy. Just for reference.
epsilon = 1 epsilon_decay = 0.9997 episodes = 10000 epsilon_copy = deepcopy(epsilon) eps = [] for i in range(episodes): epsilon_copy = epsilon_copy * epsilon_decay eps.append(epsilon_copy) plt.plot(eps) plt.show()
_____no_output_____
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Run everything.
env = gridworld_custom() agent = q_learning() pbar = tqdm(range(episodes)) for episode in pbar: prev_obs = env.reset() done = False epsilon = epsilon * epsilon_decay while not(done): if(random.uniform(0, 1) > epsilon): action = agent.choose_action(prev_obs) else: ...
100%|███████████████████████████████████████████████████████████████████████████| 10000/10000 [00:23<00:00, 434.64it/s]
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Take a look at the Q Table after training. Gives us an understanding as to how the model might function
agent.q_table
_____no_output_____
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Test the trained model
prev_obs = env.reset() done = False env.render() while not(done): action = agent.choose_action(prev_obs) obs, reward, done, _ = env.step(action) prev_obs = obs env.render()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ D _ _ _ * _ D _ w _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * D _ _ _ _ _ D _ w _ _ _ _ _ _ _ _ _ _ * _ _ _ _ _ D _ _ _ _ _ D _ w _ _ _ _ _ _ _ _ _ _ _ * _ _ _ _ D _ _ _ _ _ D _ w _ _ _ _ _ _ _ _ _ _ _ _ * _ _ _ D _ _ _ _ _ D _ w _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ...
MIT
Week1/prerun_code/3_Q_learning_scratch_prerun.ipynb
ashwin-M-D/Northeastern_RL_Discussions
Abstractive Summarization Loading Pre-processed DatasetThe Data is preprocessed in [Data_Pre-Processing.ipynb](https://github.com/JRC1995/Abstractive-Summarization/blob/master/Data_Pre-Processing.ipynb)Dataset source: https://www.kaggle.com/snap/amazon-fine-food-reviews
import json with open('Processed_Data/Amazon_Reviews_Processed.json') as file: for json_data in file: saved_data = json.loads(json_data) vocab2idx = saved_data["vocab"] embd = saved_data["embd"] train_batches_text = saved_data["train_batches_text"] test_batches_text = save...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Hyperparameters
hidden_size = 300 learning_rate = 0.001 epochs = 5 max_summary_len = 16 # should be summary_max_len as used in data_preprocessing with +1 (+1 for <EOS>) D = 5 # D determines local attention window size window_len = 2*D+1 l2=1e-6
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Tensorflow Placeholders
import tensorflow as tf embd_dim = len(embd[0]) tf_text = tf.placeholder(tf.int32, [None, None]) tf_embd = tf.placeholder(tf.float32, [len(vocab2idx),embd_dim]) tf_true_summary_len = tf.placeholder(tf.int32, [None]) tf_summary = tf.placeholder(tf.int32,[None, None]) tf_train = tf.placeholder(tf.bool)
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Embed vectorized textDropout used for regularization (https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf)
embd_text = tf.nn.embedding_lookup(tf_embd, tf_text) embd_text = tf.layers.dropout(embd_text,rate=0.3,training=tf_train)
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
LSTM functionMore info: https://dl.acm.org/citation.cfm?id=1246450, https://www.bioinf.jku.at/publications/older/2604.pdf,https://en.wikipedia.org/wiki/Long_short-term_memory
def LSTM(x,hidden_state,cell,input_dim,hidden_size,scope): with tf.variable_scope(scope,reuse=tf.AUTO_REUSE): w = tf.get_variable("w", shape=[4,input_dim,hidden_size], dtype=tf.float32, trainable=True, ...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Bi-Directional LSTM Encoder(https://maxwell.ict.griffith.edu.au/spl/publications/papers/ieeesp97_schuster.pdf)More Info: https://machinelearningmastery.com/develop-bidirectional-lstm-sequence-classification-python-keras/Bi-directional LSTM encoder has a forward encoder and a backward encoder. The forward encoder encod...
S = tf.shape(embd_text)[1] #text sequence length N = tf.shape(embd_text)[0] #batch_size i=0 hidden=tf.zeros([N, hidden_size], dtype=tf.float32) cell=tf.zeros([N, hidden_size], dtype=tf.float32) hidden_forward=tf.TensorArray(size=S, dtype=tf.float32) #shape of embd_text: [N,S,embd_dim] embd_text_t = tf.transpose(embd_...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Backward Encoding
i=S-1 hidden=tf.zeros([N, hidden_size], dtype=tf.float32) cell=tf.zeros([N, hidden_size], dtype=tf.float32) hidden_backward=tf.TensorArray(size=S, dtype=tf.float32) def cond(i, hidden, cell, hidden_backward): return i >= 0 def body(i, hidden, cell, hidden_backward): x = embd_text_t[i] hidden,cell = LSTM(x...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Merge Forward and Backward Encoder Hidden States
hidden_forward = hidden_forward.stack() hidden_backward = hidden_backward.stack() encoder_states = tf.concat([hidden_forward,hidden_backward],axis=-1) encoder_states = tf.transpose(encoder_states,[1,0,2]) encoder_states = tf.layers.dropout(encoder_states,rate=0.3,training=tf_train) final_encoded_state = tf.layers.dr...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Implementation of attention scoring functionGiven a sequence of encoder states ($H_s$) and the decoder hidden state ($H_t$) of current timestep $t$, the equation for computing attention score is:$$Score = (H_s.W_a).H_t^T $$($W_a$ = trainable parameters)(https://nlp.stanford.edu/pubs/emnlp15_attn.pdf)
def attention_score(encoder_states,decoder_hidden_state,scope="attention_score"): with tf.variable_scope(scope,reuse=tf.AUTO_REUSE): Wa = tf.get_variable("Wa", shape=[2*hidden_size,2*hidden_size], dtype=tf.float32, trainable=True, ...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Local Attention FunctionBased on: https://nlp.stanford.edu/pubs/emnlp15_attn.pdf
def align(encoder_states, decoder_hidden_state,scope="attention"): with tf.variable_scope(scope,reuse=tf.AUTO_REUSE): Wp = tf.get_variable("Wp", shape=[2*hidden_size,125], dtype=tf.float32, trainable=True, ...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
LSTM Decoder With Local Attention
with tf.variable_scope("decoder",reuse=tf.AUTO_REUSE): SOS = tf.get_variable("sos", shape=[1,embd_dim], dtype=tf.float32, trainable=True, initializer=tf.glorot_uniform_initializer()) # SOS represents starting ma...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Define Cross Entropy Cost Function and L2 Regularization
filtered_trainables = [var for var in tf.trainable_variables() if not("Bias" in var.name or "bias" in var.name or "noreg" in var.name)] regularization = tf.reduce_sum([tf.nn.l2_loss(var) for var in filtered_trainables]) with tf.variable...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Accuracy
# Comparing predicted sequence with labels comparison = tf.cast(tf.equal(outputs, tf_summary), tf.float32) # Masking to ignore the effect of pads while calculating accuracy pad_mask = tf.sequence_mask(tf_true_summary_len, maxlen=max_summary_len, ...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Define Optimizer
all_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) optimizer = tf.contrib.opt.NadamOptimizer( learning_rate=learning_rate) gvs = optimizer.compute_gradients(cost, var_list=all_vars) capped_gvs = [(tf.clip_by_norm(grad, 5), var) for grad, var in gvs] # Gradient Clipping train_op = optimizer.apply_gra...
_____no_output_____
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Training and Validation
import pickle import random with tf.Session() as sess: # Start Tensorflow Session display_step = 100 patience = 5 load = input("\nLoad checkpoint? y/n: ") print("") saver = tf.train.Saver() if load.lower() == 'y': print('Loading pre-trained weights for the model...') saver....
Load checkpoint? y/n: n STARTING TRAINING Iter 0, Cost= 2.086, Acc = 0.00% Sample Text i 'm not a big pretzel eater , but i love this little <UNK> nibblers . i like the low fat snack and how it fills you up . Sample Predicted Summary municipality jackass municipality mongolian seats han han mongolian hah sus ...
MIT
.ipynb_checkpoints/Summarization-checkpoint.ipynb
ParasAvkirkar/AbstractiveTextSummarization
Чтение и подготовка обучающей выборки
train = pd.read_csv("./example_data/train_demo.csv", low_memory=False, index_col="line_id", parse_dates = ["datetime_" + str(i) for i in range(2)],) train = train.iloc[:, 50:100] num_col = list(filter(lambda x: "numb" in x, train.columns)) num_feature_type =...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
Чтение и подготовка тестовой выборки
test = pd.read_csv("./example_data/test_demo.csv", index_col="line_id", parse_dates = ["datetime_" + str(i) for i in range(2)]) date_col = filter(lambda x: "datetime" in x, test.columns) for col in date_col: test[col + "_year"] = test[col].map(lambda x: x.year) test[col +...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
Параметры модели Для обучения модели рекомендуется указать тип признаков для обучения.Поэтому создается словарь features_type с ключами: "real" -- вещественный признак,"cat" -- категориальный.Для признаков, которые не размечены, типы будут определены автоматом. Такой вариант будет работать, но качество порядочно прос...
cat_col = list(filter(lambda x: "str" in x, train.columns)) cat_feature_type = {x: "cat" for x in cat_col} year_col = list(filter(lambda x: "_year" in x, train.columns)) year_feature_type = {x: "cat" for x in year_col} weekday_col = list(filter(lambda x: "_weekday" in x, train.columns)) weekday_feature_type = {x: "ca...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
Feature level constrains
features_type = dict(**num_feature_type, **cat_feature_type, **year_feature_type, **weekday_feature_type, **month_feature_type)
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
- `features_monotone_constraints` - также можно указать зависимость целевой переменной от признака. Если заранее известно, что при возрастании признака feature_1, то эту информацию можно учесть в модели, добавив в словарь пару {feature_1: "1"}. Если же зависимость признака от целевой переменной обратная, то можно указа...
features_monotone_constraints = {'number_74': 'auto', 'number_83': 'auto'}
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
- `max_bin_count` - через словарь max_bin_count можно задать число бинов для WoE кодирования, если для какого-то признака оно отлично от общего.
max_bin_count = {'number_47': 3, 'number_51': 2}
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
РекомендацияВ общем случае, в первый момент построения модели лучше не указывать специальных ограничений в features_monotone_constraints и max_bin_count. Если в результате анализа полученной модели разбиение оказалось неинтерпретируемым или нестабильным по отдельным признакам, но в целом по модели ок, то ограничить с...
auto_woe = AutoWoE(interpreted_model=True, monotonic=False, max_bin_count=5, select_type=None, pearson_th=0.9, auc_th=.505, vif_th=10., imp_th=0, th_con...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
- `train` обучающая выборка- `target_name` - название целевой переменной- `features_type` - см выше описание дикта features_type. Возможно указание None для автозаполнения, но не рекомендуется- `group_kf` - название колонки-группы для GroupKFold https://scikit-learn.org/stable/modules/generated/sklearn.model_selection...
auto_woe.fit(train[features + ['target']], target_name="target", features_type=features_type, group_kf=None, max_bin_count=max_bin_count, features_monotone_constraints=features_monotone_constraints, validation=test ) pred = auto_...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
Полезные методы модели - `private_features_type` - типизация признаков- `get_woe` - рабиение на бины и WoE значения в них- `get_split` - границы разбиения. Особо полезен для категориальных признаков Замечание: ReportDeco - обертка для построения отчета. Она не обязательна для обучения и применения модели, но обязатель...
report_params = {"automl_date_column": "report_month", # колонка с датой в формате params['datetimeFormat'] "output_path": "./AUTOWOE_REPORT_1", # папка, куда сгенерится отчет и сложатся нужные файлы "report_name": "___НАЗВАНИЕ ОТЧЕТА___", "report_version_id": 1, ...
_____no_output_____
Apache-2.0
(Example_1) BasicUsageAndParams.ipynb
VitaliyPavlyukov/AutoMLWhitebox
Discussion Analysis===Notebook for analysis of discussion done in Evidence and Reconsider tasks via the annotation web client.
import os import re import pandas as pd import numpy as np import sklearn import sklearn.metrics from collections import Counter import itertools import sqlite3 import sys sys.path.append("../annotation_data") import responsibility as responsibility_utils from utils import get_webclient_url annotation_web_client_databa...
_____no_output_____
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Experiment metadata
responsibility_list = ["coordinating_support", "symptom_management", "preparation", "managing_transitions", "info_filtering", "continued_monitoring", "clinical_decisions"] user1 = "luoxx498" use...
_____no_output_____
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Load data
all_rows = [] for phase in [evidence_phase, reconsider_phase]: for users in [(user1, user2), (user2, user1)]: evidence_username, reconsider_username = users for responsibility in responsibility_list: new_rows = get_discussion_entries(responsibility, phase, evidence_username, reconsider_u...
_____no_output_____
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Analysis
# first, how many fall into the three conditions? print("Evidence phase annotation changes") for u1, u2 in [(user1, user2), (user2, user1)]: print("Evidence tasks:", u1) print("Reconsider tasks:", u2) print("="*40) for responsibility in responsibility_list: df_subset = df[(df.phase == evidence_p...
Reconsider phase annotation changes Evidence tasks: luoxx498 Reconsider tasks: eriks074 ======================================== coordinating_support 12/14 85.7% symptom_management 15/16 93.8% preparation 15/17 88.2% managing_transitions 0/ 0 ...
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Irresolvable case analysis
print("Irresolvable disagreements from reconsider phase") print("="*50) u1_all_irresolvable = 0 u2_all_irresolvable = 0 u1_all_total = 0 u2_all_total = 0 for responsibility in responsibility_list: df_subset = df[(df.phase == reconsider_phase) & (df.responsibility == responsibility) ...
_____no_output_____
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Themes in comments: - Evidence to me of a different responsibility (and thus not this one) Takeaway: A problem with soft boundaries? Evidence that lies in margins especially hard to interpret - Not clear enough (in other words, ambiguous) - An edge case that falls just outside the boundary Qualitative analysis ...
pd.set_option('display.max_colwidth', 255) df[(df.additional_discussion != "") & (df.phase == evidence_phase)][["responsibility", "highlighted_text", "additional_discussion", "evidence_username", "reconsider_username", "is_annotation_changed"]] df[(df.additional_discussion != "") & (df.phase == reconsider_phase)][["res...
_____no_output_____
MIT
patient_responsibilities/discussion-analysis.ipynb
levon003/icwsm-cancer-journeys
Note how the not operator is ~ and non **not**
df = pd.DataFrame(output) yy = '2011' dfc = df[ df['created'].str.contains(yy) ] dfu = df[ ~df['created'].str.contains(yy) ] math_cat = [ x for x in set( ' '.join(list(df['categories'])).split(' ') ) if 'math' in x] len(dfc) def date2doy(x, yy=2010): if x == '' : return None yy,mm,dd = [int(y) for y in x.split(...
_____no_output_____
MIT
Arxiv_stats.ipynb
macbuse/Arxiv-Api
Learn you bash
bash_lessons = !find ~ | grep -1 LearnYou/learnyoubash bash_lessons[2] # = bash_lessons[1] !cat '/Users/frank/Documents/JS/LearnYou/learnyoubash/arr.bash'
_____no_output_____
MIT
_productivity/learnyoubash.ipynb
aixpact/data-science
Arrays
%%! fruits=(Apple Pear Plum) echo ${fruits[*]:0:2}
_____no_output_____
MIT
_productivity/learnyoubash.ipynb
aixpact/data-science
Valores nulos em data frame
import pandas as pd import numpy as np # Importando o dataset df = pd.read_csv("data_sets/pima-data.csv") df.shape df.head() # Verificando se existem valores nulos df.isnull().values.any()
_____no_output_____
MIT
tricks/valores_nulos.ipynb
everton3x/python-tricks
_Lambda School Data Science, Unit 2_ Regression 2 Sprint Challenge: Predict drugstore sales 🏥For your Sprint Challenge, you'll use real-world sales data from a German drugstore chain, from Jan 2, 2013 — July 31, 2015.You are given three dataframes:- `train`: historical sales data for 100 stores- `test`: historical sa...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import category_encoders as ce import eli5 from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, mean_squared_log_error from sklearn.model_selection import cross_val_score from sk...
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
The dataframes have a variety of columns:- **Store** - a unique Id for each store- **DayOfWeek** - integer, 1-6- **Date** - the date, from Jan 2, 2013 — July 31, 2015.- **Sales** - the units of inventory sold on a given date (this is the target you are predicting)- **Customers** - the number of customers on a given dat...
store.head() train.head() test.head()
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Merge train, test and store
# Wrangle train, validation, and test sets def wrangle(X): X = X.copy() # Engineer date features X['Date'] = pd.to_datetime(X['Date'], infer_datetime_format=True) X['date_year'] = X['Date'].dt.year X['date_month'] = X['Date'].dt.month X['date_day'] = X['Date'].dt.day X = X.drop(columns=...
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Arrange X matrix and y target for train and test
target = 'Sales' X_train = train.drop(columns=target) X_test = test.drop(columns=target) y_train = train[target] y_test = test[target] X_train.shape, X_test.shape, y_train.shape, y_test.shape
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
log transform train and test target
y_train_log = np.log1p(y_train) y_test_log = np.log1p(y_test)
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
plot distribution of train target before and after transformation
sns.distplot(y_train); sns.distplot(y_train_log);
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
2. Fit and validate your model- **Use Gradient Boosting** or any type of regression model.- **Beat the baseline:** The estimated baseline Root Mean Squared Logarithmic Error is 0.90, if we guessed the mean sales for every prediction. Remember that RMSE with the log-transformed target is equivalent to RMSLE with the or...
def rmse(y_true, y_pred): return np.sqrt(mean_squared_error(y_true, y_pred)) def rmsle(y_true, y_pred): return np.sqrt(mean_squared_log_error(y_true, y_pred))
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Build baseline model
y_base = np.full_like(y_test_log, fill_value=y_train_log.mean()) print('Validation RMSLE, Mean Baseline:', rmse(y_test_log, y_base))
Validation RMSLE, Mean Baseline: 0.3948331905413732
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Split train data into train and validate, put all dates for a given store in the same set
stores = train['Store'].unique() train_stores, val_stores = train_test_split( stores, random_state=42 ) train_stores = train[train.Store.isin(train_stores)] val_stores = train[train.Store.isin(val_stores)] assert train_stores.shape[0] + val_stores.shape[0] == train.shape[0] target = 'Sales' X_train = train_stor...
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Use XGBoost to predict target
# Make pipeline pipeline = make_pipeline( ce.OrdinalEncoder(), XGBRegressor( n_estimators=1000, n_jobs=-1, eval_metric='rmse', early_stopping_rounds=10 ) ) # Fit pipeline.fit(X_train, y_train_log) # Validate y_pred_log = pipeline.predict(X_val) print('Validation Error', r...
[20:08:19] WARNING: C:/Jenkins/workspace/xgboost-win64_release_0.90/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror. Validation Error 0.1641765041445393
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Get the test error
y_pred_test = pipeline.predict(X_test) print('Test Error', rmse(y_test_log, y_pred_test))
Test Error 0.15633498742026974
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
3. Plot model interpretation visualizations- Choose any one of these options: - Permutation Importances plot - Partial Dependency Plot, 1 feature isolation - Partial Dependency Plot, 2 feature interaction Stretch goals- Plot 2+ visualizations.- Use permutation importances for feature selection.
X_val.columns features = [ 'date_month', 'date_day', 'DayOfWeek' ] for feature in features: isolated = pdp_isolate( model=pipeline, dataset=X_val, model_features=X_val.columns, feature=feature ) pdp_plot(isolated, feature_name=feature);
_____no_output_____
MIT
DS_Sprint_Challenge_8_Regression_2.ipynb
AndrewMarksArt/DS-Unit-2-Applied-Modeling
Deutsch Algorithmby Olga Okrut Install frameworks, and import libraries
!pip install tensornetwork jax jaxlib colorama qcircuit from qcircuit import QCircuit as qc
_____no_output_____
Apache-2.0
tutorials/Deutsch_Algorithm.ipynb
MadhavJivrajani/QCircuit
Now, after we have learned how quantum gates work and how to build a quantum circuit, we will jump to the first quantum algorithm. We begin with a very simple quantum algorithm - Deutsch algorithm, named after its inventor David Deutsch, which serves as an excellent proof of the supremacy of quantum computers and algor...
# define binary functions. Some of them are constant, other balanced def f1(x): return x def f2(x): return 1 def f3(x): return 0 def f4(x): return not x def f5(x): return x ** 2 def f6(x): return not (x ** 3) def f7(x): return (x % 3 == 2) def f8(x): return not (x % 3 == 2) # check i...
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py:123: UserWarning: No GPU/TPU found, falling back to CPU. warnings.warn('No GPU/TPU found, falling back to CPU.')
Apache-2.0
tutorials/Deutsch_Algorithm.ipynb
MadhavJivrajani/QCircuit
Read and display data from a CGNS file
import h5py import numpy as np import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
read-cgns.ipynb
mdpiper/notebooks
Access a CGNS file.
f = h5py.File('data/Test1.cgn', 'r') list(f.keys())
_____no_output_____
MIT
read-cgns.ipynb
mdpiper/notebooks
Move through the tree to find the x and y coordinate grids.
grid = f['iRIC']['iRICZone']['GridCoordinates'] x = grid['CoordinateX'][' data'] # yes, there's a space y = grid['CoordinateY'][' data'] x.shape, y.shape x.value
_____no_output_____
MIT
read-cgns.ipynb
mdpiper/notebooks
Display the coordinate grid.
plt.scatter(x, y)
_____no_output_____
MIT
read-cgns.ipynb
mdpiper/notebooks
Zoom in to see individula nodes.
plt.scatter(x, y) plt.ylim([5,15]) plt.xlim([0,10])
_____no_output_____
MIT
read-cgns.ipynb
mdpiper/notebooks
Table of Contents1&nbsp;&nbsp;Stop Reinventing Pandas2&nbsp;&nbsp;First Hacks!2.1&nbsp;&nbsp;Beautiful pipes!2.2&nbsp;&nbsp;The Penny Drops2.3&nbsp;&nbsp;Map with dict3&nbsp;&nbsp;Time Series3.1&nbsp;&nbsp;Resample3.1.1&nbsp;&nbsp;The Old Way3.1.2&nbsp;&nbsp;A Better Way3.2&nbsp;&nbsp;Slice Easily3.3&nbsp;&nbsp;Time Wi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use(['classic', 'ggplot', 'seaborn-poster', 'dean.style']) %load_ext autoreload %autoreload 2 import my_utils import warnings warnings.simplefilter("ignore")
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
First Hacks! Reading the data and a few housekeeping tasks. is the first place we can make our code more readable.
df_io = pd.read_csv('./bear_data.csv', index_col=0, parse_dates=['date_']) df_io.head() df = df_io.copy().sort_values('date_').set_index('date_').drop(columns='val_updated') df.head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Beautiful pipes!One line method chaining is hard to read and prone to human error, chaining each method in its own line makes it a lot more readable.
df_io\ .copy()\ .sort_values('date_')\ .set_index('date_')\ .drop(columns='val_updated')\ .head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
But it has a problem. You can't comment out and even comment in between
# This block will result in an error df_io\ .copy()\ # This is an inline comment # This is a regular comment .sort_values('date_')\ # .set_index('date_')\ .drop(columns='val_updated')\ .head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Even an unnoticeable space character may break everything
# This block will result in an error df_io\ .copy()\ .sort_values('date_')\ .set_index('date_')\ .drop(columns='val_updated')\ .head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
The Penny DropsI like those "penny dropping" moments, when you realize you knew everything that is presented, yet it is presented in a new way you never thought of.
# We can split these value inside () users = (134856, 195373, 295817, 294003, 262166, 121066, 129678, 307120, 258759, 277922, 220794, 192312, 318486, 314631, 306448, 297059,206892, 169046, 181703, 146200, 199876, 247904, 250884, 282989, 234280, 202520, 138064, 133577, 301053, 24...
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Map with dictA dict is a callable with $f(key) = value$, there for you can call `.map` with it. In this example I want to make int key codes into letter.
df.bear_type.map(lambda x: x+3).head() # A dict is also a callable bears = { 1: 'Grizzly', 2: 'Sun', 3: 'Pizzly', 4: 'Sloth', 5: 'Polar', 6: 'Cave', 7: 'Black', 8: 'Panda' } df['bear_type'] = df.bear_type.map(bears) df.head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Time Series ResampleTask: How many events happen each hour? The Old Way
bad = df.copy() bad['day'] = bad.index.date bad['hour'] = bad.index.hour (bad .groupby(['day','hour']) .count() )
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
* Many lines of code* unneeded columns* Index is not a time anymore* **missing rows** (Did you notice?) A Better Way
df.resample('H').count() # H is for Hour
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
But it's even better on non-round intervals
rs = df.resample('10T').count() # T is for Minute, and pandas understands 10 T, it will also under stand 11T if you wonder rs.head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
[Complete list of Pandas' time abbrevations](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Period.strftime.html) Slice EasilyPandas will automatically make string into timestamps, and it will understand what you want it to do.
# Take only timestamp in the hour of 21:00. rs.loc['2018-10-09 21',:] # Take all time stamps before 18:31 rs.loc[:'2018-10-09 18:31',:]
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Time Windows: Rolling, Expanding, EWMIf your Dataframe is indexed on a time index (Which we have)
fig, ax = plt.subplots() rs.rename(columns = {'bear_type':'bears'}).plot(ax=ax,linestyle='--') (rs .rolling('90T') .mean() .rename(columns = {'bear_type':'rolling mean'}) .plot(ax=ax) ) rs.expanding().mean().rename(columns = {'bear_type':'expanding mean'}).plot(ax=ax) rs.ewm(6).mean().rename(columns = {'bear_type'...
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
With ApplyIntuitively, windows are like GroupBy, so you can apply anything you want after the grouping, e.g.: geometric mean.
fig, ax = plt.subplots() rs.plot(ax=ax,linestyle='--') (rs .rolling(6) .apply(lambda x: np.power(np.product(x),1/len(x)),raw=True) .rename(columns = {'bear_type':'Rolling Geometric Mean'}) .plot(ax=ax) ) plt.show()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Combine with GroupBy 🤯Pandas has no problem with groupby and resample together. It's as simple as `groupby[col1,col2]`. In our specific case, we want to cound events in an interval per event type.
per_bear = (df .groupby('bear_type') .resample('15T') .apply('count') .rename(columns={'bear_type':'amount'}) ) per_bear.groupby('bear_type').head(2)
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Sorting By Values
per_bear.sort_values(by=['amount'], ascending=False).head(10)
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
By Index
per_bear.sort_index().head(7) per_bear.sort_index(level=1).head(7)
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
By Both (New in 0.23)`Index` has a name. Modern Pandas knows to address this index by name just like a regular column.
per_bear.sort_values(['amount','bear_type'], ascending=(False, True)).head(10)
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas
Stack, Unstack Unstack In this case, working with a wide format indexed on intervals, with event types as columns, will make a lot more sense. The Old wayPivot table in modern pandas is more robust than it used to be. Still, it requires you to specify everything.
pt = pd.pivot_table(per_bear,values = 'amount',columns='bear_type',index='date_') pt.head()
_____no_output_____
MIT
_Nightly.ipynb
DeanLa/dont_reinvent_pandas