markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Build the Neural Network Apply the functions you implemented above to: Apply embedding to the input data for the encoder. Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob). Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function...
def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int): """ Build the Sequence-to-Sequence part of the neural network :param input_data: Inpu...
language-translation/dlnd_language_translation_23.ipynb
blua/deep-learning
mit
Neural Network Training Hyperparameters Tune the following parameters: Set epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set num_layers to the number of layers. Set encoding_embedding_size to the size of the embedding for the encoder. Set decoding_embedding_siz...
# Number of Epochs epochs = 20 # Batch Size batch_size = 512 # RNN Size rnn_size = 512 # Number of Layers num_layers = 1 # Embedding Size encoding_embedding_size = 512 decoding_embedding_size = 512 # Learning Rate learning_rate = 0.001 # Dropout Keep Probability keep_probability = 0.6
language-translation/dlnd_language_translation_23.ipynb
blua/deep-learning
mit
Build the Graph Build the graph using the neural network you implemented.
""" DON'T MODIFY ANYTHING IN THIS CELL """ save_path = 'checkpoints/dev' (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() max_target_sentence_length = max([len(sentence) for sentence in source_int_text]) train_graph = tf.Graph() with train_graph.as_default():...
language-translation/dlnd_language_translation_23.ipynb
blua/deep-learning
mit
Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import time def get_accuracy(target, logits): """ Calculate accuracy """ max_seq = max(target.shape[1], logits.shape[1]) if max_seq - target.shape[1]: target = np.pad( target_batch, [(0,0),(0,max_seq - target_batch.shape[1])...
language-translation/dlnd_language_translation_23.ipynb
blua/deep-learning
mit
Sentence to Sequence To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences. Convert the sentence to lowercase Convert words into ids using vocab_to_int Convert words not in the vocabulary, to the <UNK> word id.
def sentence_to_seq(sentence, vocab_to_int): """ Convert a sentence to a sequence of ids :param sentence: String :param vocab_to_int: Dictionary to go from the words to an id :return: List of word ids """ # TODO: Implement Function words = sentence.split(" ") word_ids = [] ...
language-translation/dlnd_language_translation_23.ipynb
blua/deep-learning
mit
载入数据 上一个ipython notebook已经做了下面这些数据特征预处理 1. City因为类别太多丢掉 2. DOB生成Age字段,然后丢掉原字段 3. EMI_Loan_Submitted_Missing 为1(EMI_Loan_Submitted) 为0(EMI_Loan_Submitted缺省) EMI_Loan_Submitted丢掉 4. EmployerName丢掉 5. Existing_EMI对缺省值用均值填充 6. Interest_Rate_Missing同 EMI_Loan_Submitted 7. Lead_Creation_Date丢掉 8. Loan_Amount_Applied, Loan_Te...
train = pd.read_csv('train_modified.csv') test = pd.read_csv('test_modified.csv') train.shape, test.shape target='Disbursed' IDcol = 'ID' train['Disbursed'].value_counts()
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
建模与交叉验证 写一个大的函数完成以下的功能 1. 数据建模 2. 求训练准确率 3. 求训练集AUC 4. 根据xgboost交叉验证更新n_estimators 5. 画出特征的重要度
#test_results = pd.read_csv('test_results.csv') def modelfit(alg, dtrain, dtest, predictors,useTrainCV=True, cv_folds=5, early_stopping_rounds=50): if useTrainCV: xgb_param = alg.get_xgb_params() xgtrain = xgb.DMatrix(dtrain[predictors].values, label=dtrain[target].values) xgtest = xgb.DMat...
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
第1步- 对于高的学习率找到最合适的estimators个数
predictors = [x for x in train.columns if x not in [target, IDcol]] xgb1 = XGBClassifier( learning_rate =0.1, n_estimators=1000, max_depth=5, min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4,...
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
Tune subsample and colsample_bytree
#对subsample 和 colsample_bytree用grid search寻找最合适的参数 param_test4 = { 'subsample':[i/10.0 for i in range(6,10)], 'colsample_bytree':[i/10.0 for i in range(6,10)] } gsearch4 = GridSearchCV(estimator = XGBClassifier( learning_rate =0.1, n_estimators=177, max_depth=4, min_child...
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
tune subsample:
# 同上 param_test5 = { 'subsample':[i/100.0 for i in range(75,90,5)], 'colsample_bytree':[i/100.0 for i in range(75,90,5)] } gsearch5 = GridSearchCV(estimator = XGBClassifier( learning_rate =0.1, n_estimators=177, max_depth=4, min_child_weight=6, gamma=0, subsample=0.8, col...
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
对正则化做交叉验证
#对reg_alpha用grid search寻找最合适的参数 param_test6 = { 'reg_alpha':[1e-5, 1e-2, 0.1, 1, 100] } gsearch6 = GridSearchCV(estimator = XGBClassifier( learning_rate =0.1, n_estimators=177, max_depth=4, min_child_weight=6, gamma=0.1, subsample=0.8, colsample_bytree=0.8, ...
kaggle/Feature_engineering_and_model_tuning/Feature-engineering_and_Parameter_Tuning_XGBoost/XGBoost models tuning.ipynb
thushear/MLInAction
apache-2.0
Analyze image stats
import matplotlib from numpy.random import randn import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter %matplotlib inline def to_percent(y, position): # Ignore the passed in position. This has the effect of scaling the default # tick locations. s = str(100 * y) # The percent symb...
notebook/winter2017_004.images_data.ipynb
svebk/qpr-winter-2017
mit
Images distribution
def get_ad_images(ad_id, ads_images_dict, url_sha1_dict, verbose=False): images_url_list = ads_images_dict[ad_id] images_sha1s = [] for image_url in images_url_list: if image_url is None or not image_url: continue try: images_sha1s.append(url_sha1_dict[image_url.strip...
notebook/winter2017_004.images_data.ipynb
svebk/qpr-winter-2017
mit
Faces distribution
def get_faces_images(images_sha1s, faces_dict): faces_out = {} for sha1 in images_sha1s: img_notfound = False try: tmp_faces = faces_dict[sha1] except: img_notfound = True if img_notfound or tmp_faces['count']==0: faces_out[sha1] = [] ...
notebook/winter2017_004.images_data.ipynb
svebk/qpr-winter-2017
mit
Show images and faces of one ad
def get_fnt(img, txt): from PIL import ImageFont # portion of image width you want text width to be img_fraction = 0.20 fontsize = 2 font = ImageFont.truetype("arial.ttf", fontsize) while font.getsize(txt)[0] < img_fraction*img.size[0]: # iterate until the text size is just larger than t...
notebook/winter2017_004.images_data.ipynb
svebk/qpr-winter-2017
mit
Dataset: "Some time-series"
def gimme_one_random_number(): return nd.random_uniform(low=0, high=1, shape=(1,1)).asnumpy()[0][0] def create_one_time_series(seq_length=10): freq = (gimme_one_random_number()*0.5) + 0.1 # 0.1 to 0.6 ampl = gimme_one_random_number() + 0.5 # 0.5 to 1.5 x = np.sin(np.arange(0, seq_length) * freq) * ampl r...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Check the data real quick
# num_sampling_points = min(SEQ_LENGTH, 400) # (data_train.sample(4).transpose().iloc[range(0, SEQ_LENGTH, SEQ_LENGTH//num_sampling_points)]).plot()
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Preparing the data for training
# print(data_train.loc[:,data_train.columns[:-1]]) # inputs # print(data_train.loc[:,data_train.columns[1:]]) # outputs (i.e. inputs shift by +1) batch_size = 64 batch_size_test = 1 seq_length = 16 num_batches_train = data_train.shape[0] // batch_size num_batches_test = data_test.shape[0] // batch_size_test num_fea...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Long short-term memory (LSTM) RNNs An LSTM block has mechanisms to enable "memorizing" information for an extended number of time steps. We use the LSTM block with the following transformations that map inputs to outputs across blocks at consecutive layers and consecutive time steps: $\newcommand{\xb}{\mathbf{x}} \newc...
num_inputs = num_features # for a 1D time series, this is just a scalar equal to 1.0 num_outputs = num_features # same comment num_hidden_units = [8, 8] # num of hidden units in each hidden LSTM layer num_hidden_layers = len(num_hidden_units) # num of hidden LSTM layers num_units_layers = [num_features] + num_hidde...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Attach the gradients
params = [] for i_layer in range(1, num_hidden_layers+1): params += [Wxg[i_layer], Wxi[i_layer], Wxf[i_layer], Wxo[i_layer], Whg[i_layer], Whi[i_layer], Whf[i_layer], Who[i_layer], bg[i_layer], bi[i_layer], bf[i_layer], bo[i_layer]] params += [Why, by] # add the output layer for param in params: param.attach...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Softmax Activation
def softmax(y_linear, temperature=1.0): lin = (y_linear-nd.max(y_linear)) / temperature exp = nd.exp(lin) partition = nd.sum(exp, axis=0, exclude=True).reshape((-1,1)) return exp / partition
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Cross-entropy loss function
def cross_entropy(yhat, y): return - nd.mean(nd.sum(y * nd.log(yhat), axis=0, exclude=True)) def rmse(yhat, y): return nd.mean(nd.sqrt(nd.sum(nd.power(y - yhat, 2), axis=0, exclude=True)))
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Averaging the loss over the sequence
def average_ce_loss(outputs, labels): assert(len(outputs) == len(labels)) total_loss = 0. for (output, label) in zip(outputs,labels): total_loss = total_loss + cross_entropy(output, label) return total_loss / len(outputs) def average_rmse_loss(outputs, labels): assert(len(outputs) == len(la...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Optimizer
def SGD(params, learning_rate): for param in params: # print('grrrrr: ', param.grad) param[:] = param - learning_rate * param.grad def adam(params, learning_rate, M , R, index_adam_call, beta1, beta2, eps): k = -1 for param in params: k += 1 M[k] = beta1 * M[k] + (1. - beta1...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Define the model
def single_lstm_unit_calcs(X, c, Wxg, h, Whg, bg, Wxi, Whi, bi, Wxf, Whf, bf, Wxo, Who, bo): g = nd.tanh(nd.dot(X, Wxg) + nd.dot(h, Whg) + bg) i = nd.sigmoid(nd.dot(X, Wxi) + nd.dot(h, Whi) + bi) f = nd.sigmoid(nd.dot(X, Wxf) + nd.dot(h, Whf) + bf) o = nd.sigmoid(nd.dot(X, Wxo) + nd.dot(h, Who) + bo) ...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Test and visualize predictions
def test_prediction(one_input_seq, one_label_seq, temperature=1.0): ##################################### # Set the initial state of the hidden representation ($h_0$) to the zero vector ##################################### # some better initialization needed?? h, c = {}, {} for i_layer in range(1,...
deep-lstm-rnn-anomaly-detector/deep-lstm-time-series.ipynb
GuillaumeDec/machine-learning
gpl-3.0
Initial point method The point method of determining enthalpy of adsorption is the simplest method. It just returns the first measured point in the enthalpy curve. Depending on the data, the first point method may or may not be representative of the actual value.
import matplotlib.pyplot as plt # Initial point method isotherm = next(i for i in isotherms_calorimetry if i.material=='HKUST-1(Cu)') res = pgc.initial_enthalpy_point(isotherm, 'enthalpy', verbose=True) plt.show() isotherm = next(i for i in isotherms_calorimetry if i.material=='Takeda 5A') res = pgc.initial_enthalpy_...
docs/examples/initial_enthalpy.ipynb
pauliacomi/pyGAPS
mit
Compound model method This method attempts to model the enthalpy curve by the superposition of several contributions. It is slower, as it runs a constrained minimisation algorithm with several initial starting guesses, then selects the optimal one.
# Modelling method isotherm = next(i for i in isotherms_calorimetry if i.material=='HKUST-1(Cu)') res = pgc.initial_enthalpy_comp(isotherm, 'enthalpy', verbose=True) plt.show() isotherm = next(i for i in isotherms_calorimetry if i.material=='Takeda 5A') res = pgc.initial_enthalpy_comp(isotherm, 'enthalpy', verbose=Tru...
docs/examples/initial_enthalpy.ipynb
pauliacomi/pyGAPS
mit
Now we mus define the function which we want to minimize
def distances(x,y): '''Function that return distance between two locations Input: Two 2D numpy arrays Output: Distance between locations''' x_rp = np.repeat(x,x_n.shape[0],0).reshape(-1,1) y_rp = np.repeat(y,x_n.shape[0],0).reshape(-1,1) dist_x = (x_rp - x_n[:,:1])**2 dist_y = (y_rp - x_n[:,1:2])...
Center of Gravity with JAX.ipynb
jomavera/Work
mit
With the defined function we can calculate the gradient with JAX
gradient_funcion = jit(grad(cost_function)) #jit (just in time) compile makes faster the evaluation of the gradient.
Center of Gravity with JAX.ipynb
jomavera/Work
mit
Now lets define the procedure to apply gradient descent or newton nethod
def optimize(funtion_opt, grad_fun, x_0, method, n_iter): '''Input: funtion_opt: Function to minimize grad_fun: gradient of the function to minimize x_0: initial 2D coordiantes of depot/distribution center method: method to use for minimize n_iter: Number of iterations of the method ...
Center of Gravity with JAX.ipynb
jomavera/Work
mit
Lets minimize with gradient descent
#Initial locationl of depots/distribution centers x0=np.array([[4.0,-84.0]]) print("Initial Cost: {:0.2f}".format(cost_function(x0 ) )) xs, ys, fs = optimize(cost_function, gradient_funcion, x0, 'grad_desc', 100) print("Final Cost: {:0.2f}".format(fs[-1]))
Center of Gravity with JAX.ipynb
jomavera/Work
mit
Now lets plot the trayectory of the optimization procedure.
from mpl_toolkits import mplot3d import matplotlib.pyplot as plt #We must modified how we feed the input to the cost function to plot values of x and y coordinates def cost_function_2(x,y): dist = distances(x,y) dist_costo = quantities*costs*dist return np.sum(dist_costo) FIGSIZE = (9, 7) xs = np.ar...
Center of Gravity with JAX.ipynb
jomavera/Work
mit
Define a year as a "Superman year" whose films feature more Superman characters than Batman. How many years in film history have been Superman years?
c = cast c = c[(c.character == 'Superman') | (c.character == 'Batman')] c = c.groupby(['year', 'character']).size() c = c.unstack() c = c.fillna(0) c.head() d = c.Superman - c.Batman print('Superman years:') print(len(d[d > 0.0]))
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
How many years have been "Batman years", with more Batman characters than Superman characters?
d = c.Superman - c.Batman print('Batman years:') print(len(d[d < 0.0]))
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Plot the number of actor roles each year and the number of actress roles each year over the history of film.
c = cast #c = c[(c.character == 'Superman') | (c.character == 'Batman')] c = c.groupby(['year', 'type']).size() c = c.unstack() c = c.fillna(0) c.plot()
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Plot the number of actor roles each year and the number of actress roles each year, but this time as a kind='area' plot.
c.plot(kind='area')
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Plot the difference between the number of actor roles each year and the number of actress roles each year over the history of film.
c = cast c = c.groupby(['year', 'type']).size() c = c.unstack('type') (c.actor - c.actress).plot()
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Plot the fraction of roles that have been 'actor' roles each year in the hitsory of film.
(c.actor/ (c.actor + c.actress)).plot(ylim=[0,1])
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Plot the fraction of supporting (n=2) roles that have been 'actor' roles each year in the history of film.
c = cast[(cast["n"] == 2) ] c = c.groupby(['year','type']).size() c = c.unstack('type') (c.actor/ (c.actor + c.actress)).plot(ylim=[0,1])
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
Build a plot with a line for each rank n=1 through n=3, where the line shows what fraction of that rank's roles were 'actor' roles for each year in the history of film.
c = cast c = c[c.n <= 3] c = c.groupby(['year', 'type', 'n']).size() c = c.unstack('type') r = c.actor / (c.actor + c.actress) r = r.unstack('n') r.plot(ylim=[0,1])
Exercises-4.ipynb
climberwb/pycon-pandas-tutorial
mit
By doing this we get a few variables initialized. First, a symmetric transition count matrix, $\mathbf{N}$, where we see that the most frequent transitions are those within metastable states (corresponding to the terms in the diagonal $N_{ii}$). Non-diagonal transitions are much less frequent (i.e. $N_{ij}<<N_{ii}$ for...
fig, ax = plt.subplots() ax.bar([0.5,1.5,2.5], -1./bhs.evals[1:], width=1) ax.set_xlabel(r'Eigenvalue', fontsize=16) ax.set_ylabel(r'$\tau_i$', fontsize=18) ax.set_xlim([0,4]) plt.show()
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
Committors and fluxes Next we calculate the committors and fluxes for this four state model. For this we define two end states, so that we estimate the flux between folded ($F$) and unfolded ($U$). The values of the committor or $p_{fold}$ are defined to be 1 and 0 for $U$ and $F$, respectively, and using the Berezhkov...
bhs.run_commit()
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
We also obtain the flux matrix, $\mathbf{J}$, containing local fluxes ($J_{ji}=J_{i\rightarrow j}$) for the different edges in the network. The signs represent the direction of the transition: positive for those fluxes going from low to high $p_{fold}$ and negative for those going from high to low $p_{fold}$. For examp...
print " j J_j(<-) J_j(->)" print " - -------- --------" for i in [1,2]: print "%2i %10.4e %10.4e"%(i, np.sum([bhs.J[i,x] for x in range(4) if bhs.pfold[x] < bhs.pfold[i]]),\ np.sum([bhs.J[x,i] for x in range(4) if bhs.pfold[x] > bhs.pfold[i]]))
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
Paths through the network Another important bit in transition path theory is the possibility of identifying paths through the network. The advantage of a simple case like the one we are looking at is that we can enumerate all those paths and check how much flux each of them carry. For example, the contribution of one g...
import tpt_functions Jnode, Jpath = tpt_functions.gen_path_lengths(range(4), bhs.J, bhs.pfold, \ bhs.sum_flux, [3], [0]) JpathG = nx.DiGraph(Jpath.transpose()) print Jnode print Jpath
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
We can exhaustively enumerate the paths and check whether the fluxes add up to the total flux.
tot_flux = 0 paths = {} k = 0 for path in nx.all_simple_paths(JpathG, 0, 3): paths[k] ={} paths[k]['path'] = path f = bhs.J[path[1],path[0]] print "%2i -> %2i: %10.4e "%(path[0], path[1], \ bhs.J[path[1],path[0]]) for i in range(2, len(path)): print "%2i -> %2i: %10.4e %10.4e...
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
So indeed the cumulative flux is equal to the total flux we estimated before. Below we print the sorted paths for furu
sorted_paths = sorted(paths.items(), key=operator.itemgetter(1)) sorted_paths.reverse() k = 1 for path in sorted_paths: print k, ':', path[1]['path'], ':', 'flux = %g'%path[1]['flux'] k +=1
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
Highest flux paths One of the great things of using TPT is that it allows for visualizing the highest flux paths. In general we cannot just enumerate all the paths, so we resort to Dijkstra's algorithm to find the highest flux path. The problem with this is that the algorithm does not find the second highest flux path....
while True: Jnode, Jpath = tpt_functions.gen_path_lengths(range(4), bhs.J, bhs.pfold, \ bhs.sum_flux, [3], [0]) # generate nx graph from matrix JpathG = nx.DiGraph(Jpath.transpose()) # find shortest path try: path = nx.dijkstra_path(JpathG, 0, 3) ...
example/fourstate/fourstate_tpt.ipynb
daviddesancho/BestMSM
gpl-2.0
Under the hood: Inferring chlorophyll distribution ~~Grid approximation: computing probability everywhere~~ <font color='red'>Magical MCMC: Dealing with computational complexity</font> Probabilistic Programming with PyMC3: Industrial grade MCMC Back to Contents <a id="MCMC"></a> Magical MCMC: Dealing with computation...
def mcmc(data, μ_0=0.5, n_samples=1000,): print(f'{data.size} data points') data = data.reshape(1, -1) # set priors σ=0.75 # keep σ fixed for simplicity trace_μ = np.nan * np.ones(n_samples) # trace: where the sampler has been trace_μ[0] = μ_0 # start with a first guess for i in range(1, n_s...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
Timing MCMC
%%time mcmc_n_samples = 2000 trace1 = mcmc(data=df_data_s.chl_l.values, n_samples=mcmc_n_samples) f, ax = pl.subplots(nrows=2, figsize=(8, 8)) ax[0].plot(np.arange(mcmc_n_samples), trace1, marker='.', ls=':', color='k') ax[0].set_title('trace of μ, 500 data points') ax[1].set_title('μ marginal posterior') p...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<img src='./resources/mcmc_1.svg?modified="1"'>
%%time samples = 2000 trace2 = mcmc(data=df_data.chl_l.values, n_samples=samples) f, ax = pl.subplots(nrows=2, figsize=(8, 8)) ax[0].plot(np.arange(samples), trace2, marker='.', ls=':', color='k') ax[0].set_title(f'trace of μ, {df_data.chl_l.size} data points') ax[1].set_title('μ marginal posterior') pm.plo...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<img src='./figJar/Presentation/mcmc_2.svg?modified=2'>
f, ax = pl.subplots(ncols=2, figsize=(12, 5)) ax[0].stem(pm.autocorr(trace1[1500:])) ax[1].stem(pm.autocorr(trace2[1500:])) ax[0].set_title(f'{df_data_s.chl_l.size} data points') ax[1].set_title(f'{df_data.chl_l.size} data points') f.suptitle('trace autocorrelation', fontsize=19) f.savefig('./figJar/Presentation/grid8....
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
What's going on? Highly autocorrelated trace: <br> $\rightarrow$ inadequate parameter space exploration<br> $\rightarrow$ poor convergence... Metropolis MCMC<br> $\rightarrow$ easy to implement + memory efficient<br> $\rightarrow$ inefficient parameter space exploration<br> $\rightarrow$ better MCMC sampler...
with pm.Model() as m1: μ_ = pm.Normal('μ', mu=1, sd=1) σ = pm.Uniform('σ', lower=0, upper=2) lkl = pm.Normal('likelihood', mu=μ_, sd=σ, observed=df_data.chl_l.dropna()) graph_m1 = pm.model_to_graphviz(m1) graph_m1.format = 'svg' graph_m1.render('./figJar/Presentation/graph_m1');
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<center> <img src="./resources/graph_m1.svg"/> </center>
with m1: trace_m1 = pm.sample(2000, tune=1000, chains=4) pm.traceplot(trace_m1); ar.plot_posterior(trace_m1, kind='hist', round_to=2);
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
Back to Contents <a id='Reg'></a> <u><font color='purple'>Tutorial Overview:</font></u> Probabilistic modeling for the beginner<br> $\rightarrow$~~The basics~~<br> $\rightarrow$~~Starting easy: inferring chlorophyll~~<br> <font color='red'>$\rightarrow$Regression: adding a predictor to estimate chlorophyll...
df_data.head().T df_data['Gr-MxBl'] = -1 * df_data['MxBl-Gr']
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
Regression coefficients easier to interpret with centered predictor:<br><br> $$x_c = x - \bar{x}$$
df_data['Gr-MxBl_c'] = df_data['Gr-MxBl'] - df_data['Gr-MxBl'].mean() df_data[['Gr-MxBl_c', 'chl_l']].info() x_c = df_data.dropna()['Gr-MxBl_c'].values y = df_data.dropna().chl_l.values
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
$$ y = \alpha + \beta x_c$$<br> $\rightarrow \alpha=y$ when $x=\bar{x}$<br> $\rightarrow \beta=\Delta y$ when $x$ increases by one unit
g3 = sb.PairGrid(df_data.loc[:, ['Gr-MxBl_c', 'chl_l']], height=3, diag_sharey=False,) g3.map_diag(sb.kdeplot, color='k') g3.map_offdiag(sb.scatterplot, color='k'); make_lower_triangle(g3) f = pl.gcf() axs = f.get_axes() xlabel = r'$log_{10}\left(\frac{Rrs_{green}}{max(Rrs_{blue})}\right), cent...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
Back to Contents <a id='RegPyMC3'></a> Regression: Adding a predictor to estimate chlorophyll ~~Data preparation~~ <font color=red>Writing a regression model in PyMC3</font> Are my priors making sense? Model fitting Flavors of uncertainty
with pm.Model() as m_vague_prior: # priors σ = pm.Uniform('σ', lower=0, upper=2) α = pm.Normal('α', mu=0, sd=1) β = pm.Normal('β', mu=0, sd=1) # deterministic model μ = α + β * x_c # likelihood chl_i = pm.Normal('chl_i', mu=μ, sd=σ, observed=y)
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<center> <img src="./resources/m_vague_graph.svg"/> </center> Back to Contents <a id='PriorCheck'></a> Regression: Adding a predictor to estimate chlorophyll ~~Data preparation~~ ~~Writing a regression model in PyMC3~~ <font color=red>Are my priors making sense?</font> Model fitting Flavors of uncertainty
vague_priors = pm.sample_prior_predictive(samples=500, model=m_vague_prior, vars=['α', 'β',]) x_dummy = np.linspace(-1.5, 1.5, num=50).reshape(-1, 1) α_prior_vague = vague_priors['α'].reshape(1, -1) β_prior_vague = vague_priors['β'].reshape(1, -1) chl_l_prior_μ_vague = α_prior_vague + β_prior_vague * x_dummy f, ax =...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<center> <img src='./figJar/Presentation/prior_checks_1.png?modified=3' width=65%> </center
with pm.Model() as m_informative_prior: α = pm.Normal('α', mu=0, sd=0.2) β = pm.Normal('β', mu=0, sd=0.5) σ = pm.Uniform('σ', lower=0, upper=2) μ = α + β * x_c chl_i = pm.Normal('chl_i', mu=μ, sd=σ, observed=y) prior_info = pm.sample_prior_predictive(model=m_informative_prior, vars=['α', 'β']) α_p...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<table> <tr> <td> <img src='./resources/prior_checks_1.png?modif=1' /> </td> <td> <img src='./resources/prior_checks_2.png?modif=2' /> </td> </tr> </table> Back to Contents <a id='Mining'></a> Regression: Adding a predictor to estimate chlorophyll ~~Dat...
with m_vague_prior: trace_vague = pm.sample(2000, tune=1000, chains=4) with m_informative_prior: trace_inf = pm.sample(2000, tune=1000, chains=4) f, axs = pl.subplots(ncols=2, nrows=2, figsize=(12, 7)) ar.plot_posterior(trace_vague, var_names=['α', 'β'], round_to=2, ax=axs[0,:], kind='hist'); ar.plot_posterio...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<center> <img src='./resources/reg_posteriors.svg'/> </center> Back to Contents <a id='UNC'></a> Regression: Adding a predictor to estimate chlorophyll ~~Data preparation~~ ~~Writing a regression model in PyMC3~~ ~~Are my priors making sense?~~ ~~Data review and model fitting~~ <font color=red>Flavors of uncertainty<...
α_posterior = trace_inf.get_values('α').reshape(1, -1) β_posterior = trace_inf.get_values('β').reshape(1, -1) σ_posterior = trace_inf.get_values('σ').reshape(1, -1)
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
model uncertainty: uncertainty around the model mean
μ_posterior = α_posterior + β_posterior * x_dummy pl.plot(x_dummy, μ_posterior[:, ::16], color='k', alpha=0.1); pl.plot(x_dummy, μ_posterior[:, 1], color='k', label='model mean') pl.scatter(x_c, y, color='orange', edgecolor='k', alpha=0.5, label='obs'); pl.legend(); pl.ylim(-2.5, 2.5); pl.xlim(-1, 1); pl.xlabel(r'$lo...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
<center> <img src='./resources/mu_posterior.svg/'> </center> prediction uncertainty: posterior predictive checks
ppc = norm.rvs(loc=μ_posterior, scale=σ_posterior); ci_94_perc = pm.hpd(ppc.T, alpha=0.06); pl.scatter(x_c, y, color='orange', edgecolor='k', alpha=0.5, label='obs'); pl.legend(); pl.plot(x_dummy, ppc.mean(axis=1), color='k', label='mean prediction'); pl.fill_between(x_dummy.flatten(), ci_94_perc[:, 0], ci_94_perc[:, ...
posts/a-bayesian-tutorial-in-python-part-II.ipynb
madHatter106/DataScienceCorner
mit
Global variables are shared between cells. Try executing the cell below:
y = 2 * x print(y)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Keyboard Shortcuts There are a few keyboard shortcuts you should be aware of to make your notebook experience more pleasant. To escape editing of a cell, press esc. Escaping a Markdown cell won't render it, so make sure to execute it if you wish to render the markdown. Notice how the highlight color switches back to bl...
!python --version
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Basics of Python Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort...
def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quicksort(left) + middle + quicksort(right) print(quicksort([3,6,8,10,1,2,1]))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Basic data types Numbers Integers and floats work as you would expect from other languages:
x = 3 print(x, type(x)) print(x + 1) # Addition print(x - 1) # Subtraction print(x * 2) # Multiplication print(x ** 2) # Exponentiation x += 1 print(x) x *= 2 print(x) y = 2.5 print(type(y)) print(y, y + 1, y * 2, y ** 2)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--) operators. Python also has built-in types for long integers and complex numbers; you can find all of the details in the documentation. Booleans Python implements all of the usual operators for Boolean logic, but uses English ...
t, f = True, False print(type(t))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Now we let's look at the operations:
print(t and f) # Logical AND; print(t or f) # Logical OR; print(not t) # Logical NOT; print(t != f) # Logical XOR;
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Strings
hello = 'hello' # String literals can use single quotes world = "world" # or double quotes; it does not matter print(hello, len(hello)) hw = hello + ' ' + world # String concatenation print(hw) hw12 = '{} {} {}'.format(hello, world, 12) # string formatting print(hw12)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
String objects have a bunch of useful methods; for example:
s = "hello" print(s.capitalize()) # Capitalize a string print(s.upper()) # Convert a string to uppercase; prints "HELLO" print(s.rjust(7)) # Right-justify a string, padding with spaces print(s.center(7)) # Center a string, padding with spaces print(s.replace('l', '(ell)')) # Replace all instances of on...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can find a list of all string methods in the documentation. Containers Python includes several built-in container types: lists, dictionaries, sets, and tuples. Lists A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
xs = [3, 1, 2] # Create a list print(xs, xs[2]) print(xs[-1]) # Negative indices count from the end of the list; prints "2" xs[2] = 'foo' # Lists can contain elements of different types print(xs) xs.append('bar') # Add a new element to the end of the list print(xs) x = xs.pop() # Remove and return the...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
As usual, you can find all the gory details about lists in the documentation. Slicing In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
nums = list(range(5)) # range is a built-in function that creates a list of integers print(nums) # Prints "[0, 1, 2, 3, 4]" print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]" print(nums[:2]) # Get ...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Loops You can loop over the elements of a list like this:
animals = ['cat', 'dog', 'monkey'] for animal in animals: print(animal)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
If you want access to the index of each element within the body of a loop, use the built-in enumerate function:
animals = ['cat', 'dog', 'monkey'] for idx, animal in enumerate(animals): print('#{}: {}'.format(idx + 1, animal))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
List comprehensions When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
nums = [0, 1, 2, 3, 4] squares = [] for x in nums: squares.append(x ** 2) print(squares)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can make this code simpler using a list comprehension:
nums = [0, 1, 2, 3, 4] squares = [x ** 2 for x in nums] print(squares)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
List comprehensions can also contain conditions:
nums = [0, 1, 2, 3, 4] even_squares = [x ** 2 for x in nums if x % 2 == 0] print(even_squares)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Dictionaries A dictionary stores (key, value) pairs, similar to a Map in Java or an object in Javascript. You can use it like this:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data print(d['cat']) # Get an entry from a dictionary; prints "cute" print('cat' in d) # Check if a dictionary has a given key; prints "True" d['fish'] = 'wet' # Set an entry in a dictionary print(d['fish']) # Prints "wet" prin...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can find all you need to know about dictionaries in the documentation. It is easy to iterate over the keys in a dictionary:
d = {'person': 2, 'cat': 4, 'spider': 8} for animal, legs in d.items(): print('A {} has {} legs'.format(animal, legs))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
nums = [0, 1, 2, 3, 4] even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0} print(even_num_to_square)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Sets A set is an unordered collection of distinct elements. As a simple example, consider the following:
animals = {'cat', 'dog'} print('cat' in animals) # Check if an element is in a set; prints "True" print('fish' in animals) # prints "False" animals.add('fish') # Add an element to a set print('fish' in animals) print(len(animals)) # Number of elements in a set; animals.add('cat') # Adding an elem...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
animals = {'cat', 'dog', 'fish'} for idx, animal in enumerate(animals): print('#{}: {}'.format(idx + 1, animal))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
from math import sqrt print({int(sqrt(x)) for x in range(30)})
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Tuples A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys t = (5, 6) # Create a tuple print(type(t)) print(d[t]) print(d[(1, 2)]) t[0] = 1
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Functions Python functions are defined using the def keyword. For example:
def sign(x): if x > 0: return 'positive' elif x < 0: return 'negative' else: return 'zero' for x in [-1, 0, 1]: print(sign(x))
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
We will often define functions to take optional keyword arguments, like this:
def hello(name, loud=False): if loud: print('HELLO, {}'.format(name.upper())) else: print('Hello, {}!'.format(name)) hello('Bob') hello('Fred', loud=True)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Classes The syntax for defining classes in Python is straightforward:
class Greeter: # Constructor def __init__(self, name): self.name = name # Create an instance variable # Instance method def greet(self, loud=False): if loud: print('HELLO, {}'.format(self.name.upper())) else: print('Hello, {}!'.format(self.name)) g = Greet...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Numpy Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. If you are already familiar with MATLAB, you might find this tutorial useful to get started with Numpy. To use Numpy, we first need to import the num...
import numpy as np
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Arrays A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. We can initialize numpy arrays from nested Python lists, a...
a = np.array([1, 2, 3]) # Create a rank 1 array print(type(a), a.shape, a[0], a[1], a[2]) a[0] = 5 # Change an element of the array print(a) b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array print(b) print(b.shape) print(b[0, 0], b[0, 1], b[1, 0])
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Numpy also provides many functions to create arrays:
a = np.zeros((2,2)) # Create an array of all zeros print(a) b = np.ones((1,2)) # Create an array of all ones print(b) c = np.full((2,2), 7) # Create a constant array print(c) d = np.eye(2) # Create a 2x2 identity matrix print(d) e = np.random.random((2,2)) # Create an array filled with random values print...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Array indexing Numpy offers several ways to index into arrays. Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array:
import numpy as np # Create the following rank 2 array with shape (3, 4) # [[ 1 2 3 4] # [ 5 6 7 8] # [ 9 10 11 12]] a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) # Use slicing to pull out the subarray consisting of the first 2 rows # and columns 1 and 2; b is the following array of shape (2, 2): # [[2 3...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
A slice of an array is a view into the same data, so modifying it will modify the original array.
print(a[0, 1]) b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1] print(a[0, 1])
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array. Note that this is quite different from the way that MATLAB handles array slicing:
# Create the following rank 2 array with shape (3, 4) a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print(a)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Two ways of accessing the data in the middle row of the array. Mixing integer indexing with slices yields an array of lower rank, while using only slices yields an array of the same rank as the original array:
row_r1 = a[1, :] # Rank 1 view of the second row of a row_r2 = a[1:2, :] # Rank 2 view of the second row of a row_r3 = a[[1], :] # Rank 2 view of the second row of a print(row_r1, row_r1.shape) print(row_r2, row_r2.shape) print(row_r3, row_r3.shape) # We can make the same distinction when accessing columns of a...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view will always be a subarray of the original array. In contrast, integer array indexing allows you to construct arbitrary arrays using the data from another array. Here is an example:
a = np.array([[1,2], [3, 4], [5, 6]]) # An example of integer array indexing. # The returned array will have shape (3,) and print(a[[0, 1, 2], [0, 1, 0]]) # The above example of integer array indexing is equivalent to this: print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # When using integer array indexing, you can re...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
One useful trick with integer array indexing is selecting or mutating one element from each row of a matrix:
# Create a new array from which we will select elements a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]]) print(a) # Create an array of indices b = np.array([0, 2, 0, 1]) # Select one element from each row of a using the indices in b print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]" # Mutate one element from...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
Boolean array indexing: Boolean array indexing lets you pick out arbitrary elements of an array. Frequently this type of indexing is used to select the elements of an array that satisfy some condition. Here is an example:
import numpy as np a = np.array([[1,2], [3, 4], [5, 6]]) bool_idx = (a > 2) # Find the elements of a that are bigger than 2; # this returns a numpy array of Booleans of the same # shape as a, where each slot of bool_idx tells # whether that element of a is ...
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit
For brevity we have left out a lot of details about numpy array indexing; if you want to know more you should read the documentation. Datatypes Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. Numpy tries to guess a datatype ...
x = np.array([1, 2]) # Let numpy choose the datatype y = np.array([1.0, 2.0]) # Let numpy choose the datatype z = np.array([1, 2], dtype=np.int64) # Force a particular datatype print(x.dtype, y.dtype, z.dtype)
jupyter-notebook-tutorial.ipynb
cs231n/cs231n.github.io
mit