repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
CPernet/LanguageDecision
notebooks/individuals/analysis_patients.ipynb
gpl-3.0
""" Environment setup """ %matplotlib inline %cd /lang_dec import warnings; warnings.filterwarnings('ignore') import hddm import numpy as np import matplotlib.pyplot as plt from utils import model_tools # Import patient data (as pandas dataframe) patients_data = hddm.load_csv('/lang_dec/data/patients_clean.csv') """ Explanation: Patient Data Analysis Dataset gathered from stroke patients TODO ADD DETAILS ABOUT STROKE PATIENTS End of explanation """ us = patients_data.loc[patients_data['stim'] == 'US'] ss = patients_data.loc[patients_data['stim'] == 'SS'] cp = patients_data.loc[patients_data['stim'] == 'CP'] cs = patients_data.loc[patients_data['stim'] == 'CS'] plt.boxplot([ss.rt.values, cp.rt.values, cs.rt.values, us.rt.values], labels=('SS', 'CP', 'CS', 'US'),) plt.title('Comparison of Reaction Time Differences Between Stimuli Groups') plt.show() ss_accuracy = (len([x for x in ss.response.values if x >= 1]) / len(ss.response.values)) * 100 cp_accuracy = (len([x for x in cp.response.values if x >= 1]) / len(cp.response.values)) * 100 cs_accuracy = (len([x for x in cs.response.values if x >= 1]) / len(cs.response.values)) * 100 us_accuracy = (len([x for x in us.response.values if x >= 1]) / len(us.response.values)) * 100 print("SS Accuracy: " + str(ss_accuracy) + "%") print("CP Accuracy: " + str(cp_accuracy) + "%") print("CS Accuracy: " + str(cs_accuracy) + "%") print("US Accuracy: " + str(us_accuracy) + "%") plt.bar([1,2,3,4], [ss_accuracy, cp_accuracy, cs_accuracy, us_accuracy]) """ Explanation: Reaction Time & Accuracy Here we include the reaction time and accuracy metrics from the original dataset End of explanation """ """ Plot Drift Diffusion Model for controls """ patients_model = hddm.HDDM(patients_data, depends_on={'v': 'stim'}, bias=True) patients_model.find_starting_values() patients_model.sample(9000, burn=200, dbname='language_decision/models/patients', db='txt') """ Explanation: Does the drift rate depend on stimulus type? End of explanation """ patients_model.plot_posteriors() """ Explanation: Convergence Checks Before carrying on with analysing the output of the model, we need to check that the markov chains have properly converged. There's a number of ways to do this, which the authors of the hddm library recommend$^1$. We'll begin by visually inspecting the MCMC posterior plots. End of explanation """ models = [] for i in range(5): m = hddm.HDDM(patients_data, depends_on={'v': 'stim'}) m.find_starting_values() m.sample(6000, burn=20) models.append(m) model_tools.check_convergence(models) """ Explanation: PASS - No problematic patterns, such as drifts or large jumps, can be in any of the traces above. Autocorrelation also drops to zero quite quickly when considering past samples - which is what we want. We can also formally test for model convergence using the Gelman-Rubin R statistic$^2$, which compares the within- and between-chain variance of different runs of the same model; models converge if variables are between $0.98$ and $1.02$. A simple algorithm to check this is outlined below: End of explanation """ patients_stats = patients_model.gen_stats() print("Threshold (a) Mean: " + str(patients_stats['mean']['a']) + " (std: " + str(patients_stats['std']['a']) + ")") print("Non-Decision (t) Mean: " + str(patients_stats['mean']['t']) + " (std: " + str(patients_stats['std']['t']) + ")") print("Bias (z) Mean: " + str(patients_stats['mean']['z']) + " (std: " + str(patients_stats['std']['z']) + ")") print("SS Mean Drift Rate: " + str(patients_stats['mean']['v(SS)']) + " (std: " + str(patients_stats['std']['v(SS)']) + ")") print("CP Mean Drift Rate: " + str(patients_stats['mean']['v(CP)']) + " (std: " + str(patients_stats['std']['v(CP)']) + ")") print("CS Mean Drift Rate: " + str(patients_stats['mean']['v(CS)']) + " (std: " + str(patients_stats['std']['v(CS)']) + ")") print("US Mean Drift Rate: " + str(patients_stats['mean']['v(US)']) + " (std: " + str(patients_stats['std']['v(US)']) + ")") v_SS, v_CP, v_CS, v_US = patients_model.nodes_db.node[['v(SS)', 'v(CP)', 'v(CS)', 'v(US)']] hddm.analyze.plot_posterior_nodes([v_SS, v_CP, v_CS, v_US]) print('P(SS > US) = ' + str((v_SS.trace() > v_US.trace()).mean())) print('P(CP > SS) = ' + str((v_CP.trace() > v_SS.trace()).mean())) print('P(CS > SS) = ' + str((v_CS.trace() > v_SS.trace()).mean())) print('P(CP > CS) = ' + str((v_CP.trace() > v_CS.trace()).mean())) print('P(CP > US) = ' + str((v_CP.trace() > v_US.trace()).mean())) print('P(CS > US) = ' + str((v_CS.trace() > v_US.trace()).mean())) """ Explanation: PASS - Formal testing reveals no convergence problems; Gelman-Rubin R statistic values for all model variables fall within the desired range ($0.98$ to $1.02$) Drift Rate Analysis Here, we examine whether the type of stimulus significantly affects the drift rate of the decision-making process. End of explanation """ """ Distribution for the non-decision time t """ time_nondec = patients_model.nodes_db.node[['t']] hddm.analyze.plot_posterior_nodes(time_nondec) """ Distribution of bias z """ z = patients_model.nodes_db.node[['z']] hddm.analyze.plot_posterior_nodes(z) """ Explanation: The drift rate for CP is significantly lower than both SS and US; no significant difference detected for CS No other statistical significance detected at $p <0.05$ End of explanation """ patients_model_threshold = hddm.HDDM(patients_data, depends_on={'v': 'stim', 'a': 'stim'}, bias=True) patients_model_threshold.find_starting_values() patients_model_threshold.sample(10000, burn=200, dbname='language_decision/models/patients_threshold', db='txt') """ Explanation: Does the stimulus type affect the distance between the two boundaries (threshold)? Threshold (or a) describes the relative difference in the distance between the upper and lower response boundaries of the DDM. We explore whether stimulus type affects the threshold / distance between the two boundaries End of explanation """ models_threshold = [] for i in range(5): m = hddm.HDDM(patients_data, depends_on={'v': 'stim', 'a': 'stim'}) m.find_starting_values() m.sample(6000, burn=20) models_threshold.append(m) model_tools.check_convergence(models_threshold) """ Explanation: Convergence checks End of explanation """ a_SS, a_CP, a_CS, a_US = patients_model_threshold.nodes_db.node[['a(SS)', 'a(CP)', 'a(CS)', 'a(US)']] hddm.analyze.plot_posterior_nodes([a_SS, a_CP, a_CS, a_US]) print('P(SS > US) = ' + str((a_SS.trace() > a_US.trace()).mean())) print('P(SS > CS) = ' + str((a_SS.trace() > a_CS.trace()).mean())) print('P(CP > SS) = ' + str((a_CP.trace() > a_SS.trace()).mean())) print('P(CP > CS) = ' + str((a_CP.trace() > a_CS.trace()).mean())) print('P(CP > US) = ' + str((a_CP.trace() > a_US.trace()).mean())) print('P(CS > US) = ' + str((a_CS.trace() > a_US.trace()).mean())) """ Explanation: Threshold analysis Since models converge, we can check the posteriors for significant differences in threshold between stimuli groups as we did for drift rates. End of explanation """ print("a(US) mean: " + str(a_US.trace().mean())) print("a(SS) mean: " + str(a_SS.trace().mean())) print("a(CS) mean: " + str(a_CS.trace().mean())) print("a(CP) mean: " + str(a_CP.trace().mean())) """ Explanation: Threshold for US is significantly larger than both SS & CS End of explanation """ patients_model_lumped = hddm.HDDM(patients_data) patients_model_lumped.find_starting_values() patients_model_lumped.sample(10000, burn=200, dbname='language_decision/models/patients_lumped', db='txt') patients_model_lumped.plot_posteriors() """ Explanation: Lumped Model End of explanation """
mne-tools/mne-tools.github.io
0.17/_downloads/e5dc759ac64748035446c9149fa0c4d3/plot_sensor_regression.ipynb
bsd-3-clause
# Authors: Tal Linzen <linzen@nyu.edu> # Denis A. Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import pandas as pd import mne from mne.stats import linear_regression, fdr_correction from mne.viz import plot_compare_evokeds from mne.datasets import kiloword # Load the data path = kiloword.data_path() + '/kword_metadata-epo.fif' epochs = mne.read_epochs(path) print(epochs.metadata.head()) """ Explanation: Analysing continuous features with binning and regression in sensor space Predict single trial activity from a continuous variable. A single-trial regression is performed in each sensor and timepoint individually, resulting in an :class:mne.Evoked object which contains the regression coefficient (beta value) for each combination of sensor and timepoint. This example shows the regression coefficient; the t and p values are also calculated automatically. Here, we repeat a few of the analyses from [1]_. This can be easily performed by accessing the metadata object, which contains word-level information about various psycholinguistically relevant features of the words for which we have EEG activity. For the general methodology, see e.g. [2]_. References .. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand words are worth a picture: Snapshots of printed-word processing in an event-related potential megastudy. Psychological Science, 2015 .. [2] Hauk et al. The time course of visual word recognition as revealed by linear regression analysis of ERP data. Neuroimage, 2006 End of explanation """ name = "Concreteness" df = epochs.metadata df[name] = pd.cut(df[name], 11, labels=False) / 10 colors = {str(val): val for val in df[name].unique()} epochs.metadata = df.assign(Intercept=1) # Add an intercept for later evokeds = {val: epochs[name + " == " + val].average() for val in colors} plot_compare_evokeds(evokeds, colors=colors, split_legend=True, cmap=(name + " Percentile", "viridis")) """ Explanation: Psycholinguistically relevant word characteristics are continuous. I.e., concreteness or imaginability is a graded property. In the metadata, we have concreteness ratings on a 5-point scale. We can show the dependence of the EEG on concreteness by dividing the data into bins and plotting the mean activity per bin, color coded. End of explanation """ names = ["Intercept", name] res = linear_regression(epochs, epochs.metadata[names], names=names) for cond in names: res[cond].beta.plot_joint(title=cond, ts_args=dict(time_unit='s'), topomap_args=dict(time_unit='s')) """ Explanation: We observe that there appears to be a monotonic dependence of EEG on concreteness. We can also conduct a continuous analysis: single-trial level regression with concreteness as a continuous (although here, binned) feature. We can plot the resulting regression coefficient just like an Event-related Potential. End of explanation """ reject_H0, fdr_pvals = fdr_correction(res["Concreteness"].p_val.data) evoked = res["Concreteness"].beta evoked.plot_image(mask=reject_H0, time_unit='s') """ Explanation: Because the linear_regression function also estimates p values, we can -- after applying FDR correction for multiple comparisons -- also visualise the statistical significance of the regression of word concreteness. The :func:mne.viz.plot_evoked_image function takes a mask parameter. If we supply it with a boolean mask of the positions where we can reject the null hypothesis, points that are not significant will be shown transparently, and if desired, in a different colour palette and surrounded by dark contour lines. End of explanation """
erikdrysdale/erikdrysdale.github.io
_rmd/extra_auroc/auc_max.ipynb
mit
# Import the necessary modules import numpy as np from scipy.optimize import minimize def sigmoid(x): return( 1 / (1 + np.exp(-x)) ) def idx_I0I1(y): return( (np.where(y == 0)[0], np.where(y == 1)[0] ) ) def AUROC(eta,idx0,idx1): den = len(idx0) * len(idx1) num = 0 for i in idx1: num += sum( eta[i] > eta[idx0] ) + 0.5*sum(eta[i] == eta[idx0]) return(num / den) def cAUROC(w,X,idx0,idx1): eta = X.dot(w) den = len(idx0) * len(idx1) num = 0 for i in idx1: num += sum( np.log(sigmoid(eta[i] - eta[idx0])) ) return( - num / den) def dcAUROC(w, X, idx0, idx1): eta = X.dot(w) n0, n1 = len(idx0), len(idx1) den = n0 * n1 num = 0 for i in idx1: num += ((1 - sigmoid(eta[i] - eta[idx0])).reshape([n0,1]) * (X[[i]] - X[idx0]) ).sum(axis=0) # * return( - num / den) """ Explanation: Direct AUROC optimization with PyTorch $$ \newcommand{\by}{\boldsymbol{y}} \newcommand{\beta}{\boldsymbol{\eta}} \newcommand{\bw}{\boldsymbol{w}} \newcommand{\bx}{\boldsymbol{x}} $$ In this post I'll discuss how to directly optimize the Area Under the Receiver Operating Characteristic Curve (AUROC), which measures the discriminatory ability of a model across a range of sensitivity/specicificity thresholds for binary classification. The AUROC is often used as method to benchmark different models and has the added benefit that its properties are independent of the underlying class imbalance. The AUROC is a specific instance of the more general learning to rank class of problems as the AUROC is the proportion of scores from a positive class that exceed the scores from a negative class. More formally if the outcome for the $i^{th}$ observation is $y \in {0,1}$ and has a corresponding risk score $\eta_i$, then the AUROC for $\by$ and $\beta$ will be: $$ \begin{align} \text{AUROC}(\by,\beta) &= \frac{1}{|I_1|\cdot|I_0|} \sum_{i \in I_1} \sum_{j \in I_0} \Big[ I[\eta_i > \eta_j] + 0.5I[\eta_i = \eta_j] \Big] \ I_k &= {i: y_i = k } \end{align} $$ Most AUROC formulas grant a half-point for tied scores. As has been discussed before, optimizing indicator functions $I(\cdot)$ is NP-hard, so instead a convex relation of the AUROC can be calculated. $$ \begin{align} \text{cAUROC}(\by,\beta) &= \frac{1}{|I_1|\cdot|I_0|} \sum_{i \in I_1} \sum_{j \in I_0} \log \sigma [\eta_i - \eta_j] \ \sigma(z) &= \frac{1}{1+\exp(-z)} \end{align} $$ The cAUROC formula encorages the log-odds of the positive class ($y=1$) to be as large as possible with respect to the negative class ($y=0$). (1) Optimization with linear methods Before looking at a neural network method, this first section will show how to directly optimize the cAUROC with a linear combination of features. We'll compare this approach to the standard logistic regression method and see if there is a meaningful difference. If we encode $\eta_i = \bx_i^T\bw$, and apply the chain rule we can see that the derivative for the cAUROC will be: $$ \begin{align} \frac{\partial \text{cAUROC}(\by,\beta)}{\partial \bw} &= \frac{1}{|I_1|\cdot|I_0|} \sum_{i \in I_1} \sum_{j \in I_0} (1 - \sigma [\eta_i - \eta_j] ) [\bx_i - \bx_j] \end{align} $$ End of explanation """ import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler X, y = load_boston(return_X_y=True) # binarize y = np.where(y > np.quantile(y,0.9), 1 , 0) nsim = 100 holder_auc = [] holder_w = [] winit = np.repeat(0,X.shape[1]) for kk in range(nsim): y_train, y_test, X_train, X_test = train_test_split(y, X, test_size=0.2, random_state=kk, stratify=y) enc = StandardScaler().fit(X_train) idx0_train, idx1_train = idx_I0I1(y_train) idx0_test, idx1_test = idx_I0I1(y_test) w_auc = minimize(fun=cAUROC,x0=winit, args=(enc.transform(X_train), idx0_train, idx1_train), method='L-BFGS-B',jac=dcAUROC).x eta_auc = enc.transform(X_test).dot(w_auc) mdl_logit = LogisticRegression(penalty='none') eta_logit = mdl_logit.fit(enc.transform(X_train),y_train).predict_proba(X_test)[:,1] auc1, auc2 = roc_auc_score(y_test,eta_auc), roc_auc_score(y_test,eta_logit) holder_auc.append([auc1, auc2]) holder_w.append(pd.DataFrame({'cn':load_boston()['feature_names'],'auc':w_auc,'logit':mdl_logit.coef_.flatten()})) auc_mu = np.vstack(holder_auc).mean(axis=0) print('AUC from cAUROC: %0.2f%%\nAUC for LogisticRegression: %0.2f%%' % (auc_mu[0], auc_mu[1])) """ Explanation: In the example simulations below the Boston dataset will be used where the binary outcome is whether a house price is in the 90th percentile or higher (i.e. the top 10% of prices in the distribution). End of explanation """ enc = StandardScaler().fit(X) idx0, idx1 = idx_I0I1(y) w_auc = minimize(fun=cAUROC,x0=winit,args=(enc.transform(X), idx0, idx1), method='L-BFGS-B',jac=dcAUROC).x eta_auc = enc.transform(enc.transform(X)).dot(w_auc) eta_logit = LogisticRegression(max_iter=1e3).fit(enc.transform(enc.transform(X)), y).predict_log_proba(enc.transform(X))[:,1] tmp = pd.DataFrame({'y':y,'Logistic':eta_logit,'cAUROC':eta_auc}).melt('y') g = sns.FacetGrid(data=tmp,hue='y',col='variable',sharex=False,sharey=False,height=5) g.map(sns.distplot,'value') g.add_legend() """ Explanation: The AUC minimizer finds a linear combination of features that is has a significantly higher AUC. Because the logistic regression uses a simple logistic loss function, the model has an incentive in prioritizing predicting low probabilities because most of the labels are zero. In contrast, the AUC minimizer is independent of this class balance and therefore does not suffer from this bias. The figure below shows the relative overlap between the two distribitions generated by each linear model on the entire dataset. The cAUROC has a smoother relationship and is less prone to overfitting. End of explanation """ import seaborn as sns from matplotlib import pyplot as plt df_w = pd.concat(holder_w) #.groupby('cn').mean().reset_index() g = sns.FacetGrid(data=df_w,col='cn',col_wrap=5,hue='cn',sharex=False,sharey=False) g.map(plt.scatter, 'logit','auc') g.set_xlabels('Logistic coefficients') g.set_ylabels('cAUROC coefficients') plt.subplots_adjust(top=0.9) g.fig.suptitle('Figure: Comparison of LR and cAUROC cofficients per simulation',fontsize=18) """ Explanation: The figure below shows while the coefficients between the AUC model are highly correlated, their slight differences account for the meaningful performance gain for out-of-sample values. End of explanation """ from sklearn.datasets import fetch_california_housing np.random.seed(1234) data = fetch_california_housing(download_if_missing=True) cn_cali = data.feature_names X_cali = data.data y_cali = data.target y_cali += np.random.randn(y_cali.shape[0])*(y_cali.std()) y_cali = np.where(y_cali > np.quantile(y_cali,0.95),1,0) y_cali_train, y_cali_test, X_cali_train, X_cali_test = \ train_test_split(y_cali, X_cali, test_size=0.2, random_state=1234, stratify=y_cali) enc = StandardScaler().fit(X_cali_train) """ Explanation: (2) AUC minimization with PyTorch To optimize a neural network in PyTorch with the goal of minimizing the cAUROC we will draw a given $i,j$ pair where $i \in I_1$ and $j \in I_0$. While other mini-batch approaches are possible (including the full-batch approach used for the gradient functions above), using a mini-batch of two will have the smallest memory overhead. The stochastic gradient for our network $f_\theta$ will now be: $$ \begin{align} \Bigg[\frac{\partial f_\theta}{\partial \theta}\Bigg]{i,j} &= \frac{\partial}{\partial \theta} \log \sigma [ f\theta(\bx_i) - f_\theta(\bx_j) ] \end{align} $$ Where $f(\cdot)$ is the output from the neural network and $\theta$ are the network parameters. The gradient of this deep neural network will be calculated by PyTorch's automatic differention backend. The example dataset will be the California housing price dataset. To make the prediction task more challenging, house prices will first be partially scrambled with noise, and then the outcome will binarized by labelling only the top 5% of housing prices as the positive class. End of explanation """ import torch import torch.nn as nn import torch.nn.functional as F class ffnet(nn.Module): def __init__(self,num_features): super(ffnet, self).__init__() p = num_features self.fc1 = nn.Linear(p, 36) self.fc2 = nn.Linear(36, 12) self.fc3 = nn.Linear(12, 6) self.fc4 = nn.Linear(6,1) def forward(self,x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) x = self.fc4(x) return(x) # Binary loss function criterion = nn.BCEWithLogitsLoss() # Seed the network torch.manual_seed(1234) nnet = ffnet(num_features=X_cali.shape[1]) optimizer = torch.optim.Adam(params=nnet.parameters(),lr=0.001) """ Explanation: In the next code block below, we will define the neural network class, the optimizer, and the loss function. End of explanation """ np.random.seed(1234) y_cali_R, y_cali_V, X_cali_R, X_cali_V = \ train_test_split(y_cali_train, X_cali_train, test_size=0.2, random_state=1234, stratify=y_cali_train) enc = StandardScaler().fit(X_cali_R) idx0_R, idx1_R = idx_I0I1(y_cali_R) nepochs = 100 auc_holder = [] for kk in range(nepochs): print('Epoch %i of %i' % (kk+1, nepochs)) # Sample class 0 pairs idx0_kk = np.random.choice(idx0_R,len(idx1_R),replace=False) for i,j in zip(idx1_R, idx0_kk): optimizer.zero_grad() # clear gradient dlogit = nnet(torch.Tensor(enc.transform(X_cali_R[[i]]))) - \ nnet(torch.Tensor(enc.transform(X_cali_R[[j]]))) # calculate log-odd differences loss = criterion(dlogit.flatten(), torch.Tensor([1])) loss.backward() # backprop optimizer.step() # gradient-step # Calculate AUC on held-out validation auc_k = roc_auc_score(y_cali_V, nnet(torch.Tensor(enc.transform(X_cali_V))).detach().flatten().numpy()) if auc_k > 0.9: print('AUC > 90% achieved') break # Compare performance on final test set auc_nnet_cali = roc_auc_score(y_cali_test, nnet(torch.Tensor(enc.transform(X_cali_test))).detach().flatten().numpy()) # Fit a benchmark model logit_cali = LogisticRegression(penalty='none',solver='lbfgs',max_iter=1000) logit_cali.fit(enc.transform(X_cali_train), y_cali_train) auc_logit_cali = roc_auc_score(y_cali_test,logit_cali.predict_proba(enc.transform(X_cali_test))[:,1]) print('nnet-AUC: %0.3f, logit: %0.3f' % (auc_nnet_cali, auc_logit_cali)) """ Explanation: In the next code block, we'll set up the sampling strategy and train the network until the AUC exceeds 90% on the validation set. End of explanation """
ARM-software/bart
docs/notebooks/thermal/Thermal.ipynb
apache-2.0
import trappy import numpy config = {} # TRAPpy Events config["THERMAL"] = trappy.thermal.Thermal config["OUT"] = trappy.cpu_power.CpuOutPower config["IN"] = trappy.cpu_power.CpuInPower config["PID"] = trappy.pid_controller.PIDController config["GOVERNOR"] = trappy.thermal.ThermalGovernor # Control Temperature config["CONTROL_TEMP"] = 77000 # A temperature margin of 2.5 degrees Celsius config["TEMP_MARGIN"] = 2500 # The Sustainable power at the control Temperature config["SUSTAINABLE_POWER"] = 2500 # Expected percentile of CONTROL_TEMP + TEMP_MARGIN config["EXPECTED_TEMP_QRT"] = 95 # Maximum expected Standard Deviation as a percentage # of mean temperature config["EXPECTED_STD_PCT"] = 5 """ Explanation: Configuration End of explanation """ import urllib import os TRACE_DIR = "example_trace_dat_thermal" TRACE_FILE = os.path.join(TRACE_DIR, 'bart_thermal_trace.dat') TRACE_URL = 'http://cdn.rawgit.com/sinkap/4e0a69cbff732b57e36f/raw/7dd0ed74bfc17a34a3bd5ea6b9eb3a75a42ddbae/bart_thermal_trace.dat' if not os.path.isdir(TRACE_DIR): os.mkdir(TRACE_DIR) if not os.path.isfile(TRACE_FILE): print "Fetching trace file.." urllib.urlretrieve(TRACE_URL, filename=TRACE_FILE) """ Explanation: Get the Trace End of explanation """ # Create a Trace object ftrace = trappy.FTrace(TRACE_FILE, "SomeBenchMark") """ Explanation: FTrace Object End of explanation """ # Create an Assertion Object from bart.common.Analyzer import Analyzer t = Analyzer(ftrace, config) BIG = '000000f0' LITTLE = '0000000f' """ Explanation: Assertions End of explanation """ result = t.getStatement("((IN:load0 + IN:load1 + IN:load2 + IN:load3) == 0) \ & (IN:dynamic_power > 0)",reference=True, select=BIG) if len(result): print "FAIL: Dynamic Power is NOT Zero when load is Zero for the BIG cluster" else: print "PASS: Dynamic Power is Zero when load is Zero for the BIG cluster" result = t.getStatement("((IN:load0 + IN:load1 + IN:load2 + IN:load3) == 0) \ & (IN:dynamic_power > 0)",reference=True, select=LITTLE) if len(result): print "FAIL: Dynamic Power is NOT Zero when load is Zero for the LITTLE cluster" else: print "PASS: Dynamic Power is Zero when load is Zero for the LITTLE cluster" """ Explanation: Assertion: Load and Dynamic Power <html> This assertion makes sure that the dynamic power for the each cluster is zero when the sum of the "loads" of each CPU is 0 $$\forall\ t\ |\ Load(t) = \sum\limits_{i=0}^{cpus} Load_i(t) = 0 \implies dynamic\ power(t)=0 $$ </html> End of explanation """ result = t.getStatement("(GOVERNOR:current_temperature > CONTROL_TEMP) &\ (PID:output > SUSTAINABLE_POWER)", reference=True, select=0) if len(result): print "FAIL: The Governor is allocating power > sustainable when T > CONTROL_TEMP" else: print "PASS: The Governor is allocating power <= sustainable when T > CONTROL_TEMP" """ Explanation: Assertion: Control Temperature and Sustainable Power <html> When the temperature is greater than the control temperature, the total power granted to all cooling devices should be less than sustainable_power $$\forall\ t\ |\ Temperature(t) > control_temp \implies Total\ Granted\ Power(t) < sustainable_power$$ <html/> End of explanation """ t.assertStatement("numpy.percentile(THERMAL:temp, 95) < (CONTROL_TEMP + TEMP_MARGIN)") """ Explanation: Statistics Check if 95% of the temperature readings are below CONTROL_TEMP + MARGIN End of explanation """ t.assertStatement("numpy.mean(THERMAL:temp) <= CONTROL_TEMP", select=0) """ Explanation: Check if the mean temperauture is less than CONTROL_TEMP End of explanation """ t.getStatement("(numpy.std(THERMAL:temp) * 100.0) / numpy.mean(THERMAL:temp)", select=0) """ Explanation: We can also use getStatement to get the absolute values. Here we are getting the standard deviation expressed as a percentage of the mean End of explanation """ from bart.thermal.ThermalAssert import ThermalAssert t_assert = ThermalAssert(ftrace) end = ftrace.get_duration() LOW = 0 HIGH = 78000 # The thermal residency gives the percentage (or absolute time) spent in the # specified temperature range. result = t_assert.getThermalResidency(temp_range=(0, 78000), window=(0, end), percent=True) for tz_id in result: print "Thermal Zone: {} spends {:.2f}% time in the temperature range [{}, {}]".format(tz_id, result[tz_id], LOW/1000, HIGH/1000) pct_temp = numpy.percentile(t.getStatement("THERMAL:temp")[tz_id], result[tz_id]) print "The {:.2f}th percentile temperature is {:.2f}".format(result[tz_id], pct_temp / 1000.0) """ Explanation: Thermal Residency End of explanation """
mldbai/mldb
container_files/demos/Predicting Titanic Survival.ipynb
apache-2.0
from pymldb import Connection mldb = Connection("http://localhost") #we'll need these also later! import numpy as np import pandas as pd, matplotlib.pyplot as plt, seaborn, ipywidgets %matplotlib inline """ Explanation: Predicting Titanic Survival From the description of a Kaggle Machine Learning Challenge at https://www.kaggle.com/c/titanic The sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships. One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class. In this challenge, we ask you to complete the analysis of what sorts of people were likely to survive. In particular, we ask you to apply the tools of machine learning to predict which passengers survived the tragedy. In this demo we will use MLDB to train a classifier to predict whether a passenger would have survived the Titanic disaster. Initializing pymldb and other imports In this demo, we will use pymldb to interact with the REST API: see the Using pymldb Tutorial for more details. End of explanation """ mldb.put('/v1/procedures/import_titanic_raw', { "type": "import.text", "params": { "dataFileUrl": "file://mldb/mldb_test_data/titanic_train.csv", "outputDataset": "titanic_raw", "runOnCreation": True } }) """ Explanation: Checking out the Titanic dataset From https://www.kaggle.com/c/titanic Load up the data See the Loading Data Tutorial guide for more details on how to get data into MLDB. End of explanation """ mldb.query("select * from titanic_raw limit 5") """ Explanation: Let's look at the data See the Query API documentation for more details on SQL queries. End of explanation """ print mldb.post("/v1/procedures", { "type": "summary.statistics", "params": { "inputData": "SELECT * FROM titanic_raw", "outputDataset": "titanic_summary_stats", "runOnCreation": True } }) """ Explanation: As a first step in the modelling process, it is often very useful to look at summary statistics to get a sense of the data. To do so, we will create a Procedure of type summary.statistics and store the results in a new dataset called titanic_summary_stats: End of explanation """ mldb.query(""" SELECT * EXCLUDING(value.most_frequent_items*) FROM titanic_summary_stats WHERE value.data_type='number' """).transpose() """ Explanation: We can take a look at numerical columns: End of explanation """ result = mldb.put('/v1/procedures/titanic_train_scorer', { "type": "classifier.experiment", "params": { "experimentName": "titanic", "inputData": """ select {Sex, Age, Fare, Embarked, Parch, SibSp, Pclass} as features, label from titanic_raw """, "configuration": { "type": "bagging", "num_bags": 10, "validation_split": 0, "weak_learner": { "type": "decision_tree", "max_depth": 10, "random_feature_propn": 0.3 } }, "kfold": 3, "modelFileUrlPattern": "file://models/titanic.cls", "keepArtifacts": True, "outputAccuracyDataset": True, "runOnCreation": True } }) auc = np.mean([x["resultsTest"]["auc"] for x in result.json()["status"]["firstRun"]["status"]["folds"]]) print "\nArea under ROC curve = %0.4f\n" % auc """ Explanation: Training a classifier We will create another Procedure of type classifier.experiment. The configuration parameter defines a Random Forest algorithm. End of explanation """ @ipywidgets.interact def score( Age=[0,80],Embarked=["C", "Q", "S"], Fare=[1,100], Parch=[0,8], Pclass=[1,3], Sex=["male", "female"], SibSp=[0,8]): return mldb.get('/v1/functions/titanic_scorer_0/application', input={"features": locals()}) """ Explanation: We automatically get a REST API for predictions The procedure above created for us a Function of type classifier. End of explanation """ test_results = mldb.query("select * from titanic_results_0 order by score desc") test_results.head() """ Explanation: What's in a score? Scores aren't probabilities, but they can be used to create binary classifiers by applying a cutoff threshold. MLDB's classifier.experiment procedure outputs a dataset which you can use to figure out where you want to set that threshold. End of explanation """ @ipywidgets.interact def test_results_plot( threshold_index=[0,len(test_results)-1]): row = test_results.iloc[threshold_index] cols = ["trueNegatives","falsePositives","falseNegatives","truePositives",] f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5)) test_results.plot(ax=ax1, x="falsePositiveRate", y="truePositiveRate", legend=False, title="ROC Curve, threshold=%.4f" % row.score).set_ylabel('truePositiveRate') ax1.plot(row.falsePositiveRate, row.truePositiveRate, 'gs') ax2.pie(row[cols], labels=cols, autopct='%1.1f%%', startangle = 90, colors=['lightskyblue','lightcoral','lightcoral', 'lightskyblue']) ax2.axis('equal') f.subplots_adjust(hspace=.75) plt.show() """ Explanation: Here's an interactive way to graphically explore the tradeoffs between the True Positive Rate and the False Positive Rate, using what's called a ROC curve. NOTE: the interactive part of this demo only works if you're running this Notebook live, not if you're looking at a static copy on http://docs.mldb.ai. See the documentation for Running MLDB. End of explanation """ mldb.put('/v1/functions/titanic_explainer', { "id": "titanic_explainer", "type": "classifier.explain", "params": { "modelFileUrl": "file://models/titanic.cls" } }) """ Explanation: But what is the model doing under the hood? Let's create a function of type classifier.explain to help us understand what's happening here. End of explanation """ @ipywidgets.interact def sliders( Age=[0,80],Embarked=["C", "Q", "S"], Fare=[1,100], Parch=[0,8], Pclass=[1,3], Sex=["male", "female"], SibSp=[0,8]): features = locals() x = mldb.get('/v1/functions/titanic_explainer/application', input={"features": features, "label": 1}).json()["output"] df = pd.DataFrame( {"%s=%s" % (feat, str(features[feat])): val for (feat, (val, ts)) in x["explanation"]}, index=["val"]).transpose().cumsum() pd.DataFrame( {"cumulative score": [x["bias"]]+list(df.val)+[df.val[-1]]}, index=['bias'] + list(df.index) + ['final'] ).plot(kind='line', drawstyle='steps-post', legend=False, figsize=(15, 5), ylim=(-1, 1), title="Score = %.4f" % df.val[-1]).set_ylabel('Cumulative Score') plt.show() """ Explanation: Exploring the impact of features for a single example NOTE: the interactive part of this demo only works if you're running this Notebook live, not if you're looking at a static copy on http://docs.mldb.ai. See the documentation for Running MLDB. End of explanation """ df = mldb.query(""" select label, sum( titanic_explainer({ label: label, features: {Sex, Age, Fare, Embarked, Parch, SibSp, Pclass} })[explanation] ) as * from titanic_raw group by label """) df.set_index("label").transpose().plot(kind='bar', title="Feature Importance", figsize=(15, 5)) plt.xticks(rotation=0) plt.show() """ Explanation: Summing up explanation values to get overall feature importance When we sum up the explanation values in the context of the correct label, we can get an indication of how important each feature was to making a correct classification. End of explanation """ mldb.put('/v1/plugins/pytanic', { "type":"python", "params": {"address": "git://github.com/datacratic/mldb-pytanic-plugin"} }) """ Explanation: We can also load up a custom UI for this End of explanation """
miykael/nipype_tutorial
notebooks/advanced_spmmcr.ipynb
bsd-3-clause
from nipype.interfaces import spm matlab_cmd = '/opt/spm12-r7219/run_spm12.sh /opt/matlabmcr-2010a/v713/ script' spm.SPMCommand.set_mlab_paths(matlab_cmd=matlab_cmd, use_mcr=True) """ Explanation: Using SPM with MATLAB Common Runtime (MCR) In order to use the standalone MCR version of spm, you need to ensure that the following commands are executed at the beginning of your script: End of explanation """ spm.SPMCommand().version """ Explanation: You can test it by calling: End of explanation """
bismayan/MaterialsMachineLearning
notebooks/old_ICSD_Notebooks/Exploring Ternaries.ipynb
mit
# Print periodic table to orient ourselves Element.print_periodic_table() # Generate list of non-radioactive elements (noble gases omitted) def desired_element(elem): omit = ['Po', 'At', 'Rn', 'Fr', 'Ra'] return not e.is_noble_gas and not e.is_actinoid and not e.symbol in omit element_universe = [e for e in Element if desired_element(e)] omitted_elements = [e for e in Element if e not in element_universe] print("Number of included elements =", len(element_universe)) print("Omitted elements:", " ".join(sorted([e.symbol for e in omitted_elements]))) """ Explanation: Exploring the Space of Ternaries How do we organize the space of compound data? Types of Data Materials project contains both: - Experimentally-observed compounds (has ICSD number) - Theoretically-proposed compounds (lacks ICSD number) Can be disguished by presence of 'icsd_id' field. Uniqueness What uniqueless defines a material for our purposes? - Composition - Structure (need to compare to create uniqueness) End of explanation """ # How many crystal structures for elements exist? with MPRester() as m: elements = m.query(criteria = {"nelements": 1}, properties = ['icsd_ids', 'pretty_formula']) # Basic analysis print("#(Materials Project records) =", len(elements)) print("#(ICSD records) =", sum([len(c['icsd_ids']) for c in elements])) # How are ICSD entries grouped into Materials Project entries? entry_multiplicities = [len(e['icsd_ids']) for e in elements] plt.hist(entry_multiplicities, bins = max(entry_multiplicities)) plt.xlabel('Multiplicity') plt.ylabel('Number of occurences') plt.title('Multiplicities of ICSD entries') # Allotropes from collections import defaultdict element_multiplicities = [e['pretty_formula'] for e in elements] allotropes = defaultdict(int, [(e, element_multiplicities.count(e)) for e in set(element_multiplicities)]) elements_sorted = [e.symbol for e in sorted(Element, key = lambda elem: elem.Z)] xx = range(len(elements_sorted)) yy = [allotropes[elem] for elem in elements_sorted] plt.bar(xx, yy) plt.xlabel('Atomic number') plt.ylabel('Allotropes') # Omitted elements because their elemental form is molecular omitted_allotropes = [e for e in allotropes.keys() if e not in elements_sorted] for k in omitted_allotropes: print(k, allotropes[k]) """ Explanation: How complete is the Materials Project database? Get intuition from crystal structure of elements, binaries and ternaries. Elements ICSD reports 2030 entries. Elements have allotropes. Each allotrope can be represented by multiple entries corresponding to the group of publications determining the structure of that allotrope. How are the ICSD entries grouped in the Materials Project? End of explanation """ # Query all ternaries with MPRester() as m: ternaries1 = m.query(criteria = {"nelements": 3}, properties = ['icsd_ids', 'pretty_formula']) # Basic analysis print("#(Materials Project records) =", len(ternaries1)) print("#(ICSD records) =", sum([len(c['icsd_ids']) for c in ternaries1])) print("#(MP with ICSD records) =", len([c for c in ternaries1 if len(c['icsd_ids']) > 0])) print("#(Unique ternaries) =", len(set([c['pretty_formula'] for c in ternaries1 if len(c['icsd_ids']) > 0]))) # Alternate way of querying ternaries with MPRester() as m: ternaries2 = m.query(criteria = {"nelements": 3}, properties = ['icsd_id', 'pretty_formula']) print("#(Materials Project records) =", len(ternaries2)) print("#(MP with ICSD records) =", len([c for c in ternaries2 if c['icsd_id'] is not None])) print("#(Unique ternaries) =", len(set([c['pretty_formula'] for c in ternaries2 if c['icsd_id']]))) """ Explanation: Ternaries ICSD reports 67000 ternaries. End of explanation """ # Number of unique compositions in both querying methods uniq_ternaries1 = set([c['pretty_formula'] for c in ternaries1]) uniq_ternaries2 = set([c['pretty_formula'] for c in ternaries2]) print("#(Unique ternaries, method 1) = ", len(uniq_ternaries1)) print("#(Unique ternaries, method 2) = ", len(uniq_ternaries2)) print("Are the sets equal?", uniq_ternaries2 == uniq_ternaries1) icsd_ternaries1 = set([c['pretty_formula'] for c in ternaries1 if len(c['icsd_ids']) > 0]) icsd_ternaries2 = set([c['pretty_formula'] for c in ternaries2 if c['icsd_id']]) print("|T2-T1| = ", len(icsd_ternaries2 - icsd_ternaries1)) print("|T1-T2| = ", len(icsd_ternaries1 - icsd_ternaries2)) pretty_formula = (icsd_ternaries2 - icsd_ternaries1).pop() print("Example compound in |T2 - T1| =", pretty_formula) print([c for c in ternaries1 if c['pretty_formula'] == pretty_formula]) print([c for c in ternaries2 if c['pretty_formula'] == pretty_formula]) pretty_formula = (icsd_ternaries1 - icsd_ternaries2).pop() print("Example compound in |T1 - T2| =", pretty_formula) print([c for c in ternaries1 if c['pretty_formula'] == pretty_formula]) print([c for c in ternaries2 if c['pretty_formula'] == pretty_formula]) """ Explanation: Why is there a discrepancy between the number of unique ternaries of the two querying methods? End of explanation """ # filter by elements that I care care about -- remove radioactive elements all_ternaries = list(icsd_ternaries1 | icsd_ternaries2) omitted_Elements = [Element(e) for e in omitted_elements] omitted_ternaries = [c for c in all_ternaries if any((e in omitted_Elements) for e in Composition(c))] icsd_ternaries = [c for c in all_ternaries if c not in omitted_ternaries] print("Number of omitted ternaries =", len(omitted_ternaries)) print("Examples:", omitted_ternaries[:5]) len(icsd_ternaries) """ Explanation: Conclusion: some elements are missing icsd_id tag, and others the icsd_ids tag. Take elements which have EITHER tag as being physical. End of explanation """ from collections import Counter def composition_to_tuple(name): return tuple(sorted([e.symbol for e in Composition(name)])) def phasediag_distribution(compounds, N_universe): counts = Counter([composition_to_tuple(c) for c in compounds]) hist = Counter(counts.values()) hist[0] = N_universe - len(counts) # add point corresponding to universe return hist from scipy.misc import comb N_ternary_diagrams = int(comb(len(element_universe), 3)) # N choose 3 = number of ternary phase diagrams hist = phasediag_distribution(icsd_ternaries, N_ternary_diagrams) xx, yy = np.array(hist.items()).T plt.semilogy(xx, yy, 'o-') plt.xlim(-0.5, len(xx) - 0.5) plt.xlabel("Number of ternaries in system") plt.ylabel("N(Number of ternaries in system)") plt.title("Distribution of all known ternaries") """ Explanation: Exploratory Analysis Get basic intuition about space of ternaries End of explanation """ def filter_one_element(symbol, universe): return [c for c in universe if Element(symbol) in Composition(c)] N_diagrams = int(comb(len(element_universe)-1, 2)) anions = ["O", "S", "Se", "F", "Cl", "Br", "I", "N", "P", "C"] grouped = [filter_one_element(X, icsd_ternaries) for X in anions] hists = [phasediag_distribution(compounds, N_diagrams) for compounds in grouped] plt.figure(figsize = (8,5)) for i,hist in enumerate(hists): plt.semilogy(hist.keys(), hist.values(), 'o-', label = anions[i], color = plt.cm.viridis(i/(len(anions)-1)), alpha = 0.7) plt.xlim(-0.5, 14.5) plt.ylim(0.5, None) plt.legend(loc = "best") plt.xlabel("Number of ternaries in system") plt.ylabel("N(Number of ternaries in system)") plt.title("Distribution of known ionic ternary systems") """ Explanation: Distribution by Anion Turns out oxygen is an outlier -- it follows a strict exponential distribution while others families do not. End of explanation """ Element.print_periodic_table() def filter_in_set(compound, universe): return all((e in universe) for e in Composition(compound)) transition_metals = [e for e in Element if e.is_transition_metal] tm_ternaries = [c for c in icsd_ternaries if filter_in_set(c, transition_metals)] print("The Materials Project doesn't have intermetallics:", len(tm_ternaries)) """ Explanation: Intermetallics Hypothesis is that well-explored families follow exponential distributions while less-explored familes deviate. End of explanation """ electronegativities = np.array([sorted([e.X for e in Composition(name).elements], reverse = True) for name in icsd_ternaries]) np.savetxt("ternary.electronegativities", electronegativities) from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter( electronegativities[:,2], electronegativities[:,1], electronegativities[:,0] ) ax.set_xlabel('X Most elecneg.') ax.set_ylabel('Y') ax.set_zlabel('Z least elecneg.') plt.show() # write data to file for Louis-Francois with open("ternaries.dat", 'w') as f: for formula in icsd_ternaries: c = Composition(formula) symbols = [] ratios = [] for k,v in c.iteritems(): symbols.append(k) ratios.append(int(v)) line = "{:15} {:2} {:2} {:2} {:2} {:2} {:2}\n".format(formula, *(symbols + ratios)) f.write(line) data = {} for e in Element: data[e.symbol] = e.data with open("elements.dat", 'w') as f: f.write(str(data)) """ Explanation: Electronegativity Scatter plot of ternaries against electronegativities of constituent elements. End of explanation """
pauliacomi/pyGAPS
docs/examples/dr_da_plots.ipynb
mit
# import isotherms %run import.ipynb # import the characterisation module import pygaps.characterisation as pgc """ Explanation: Dubinin-Radushkevich and Dubinin-Astakov plots The Dubinin-Radushkevich (DR) and Dubinin-Astakov (DA) plots are often used to determine the pore volume and the characteristic adsorption potential of adsorbent materials, in particular those of carbonaceous materials, such as activated carbons, carbon black or carbon nanotubes. It is also sometimes used for solution adsorption isotherms. In pyGAPS, both the DR and DA plots are available with the dr_plot and da_plot functions. First we import the example isotherms. End of explanation """ isotherm = next(i for i in isotherms_n2_77k if i.material=='Takeda 5A') results = pgc.dr_plot(isotherm, verbose=True) """ Explanation: Then we'll select the Takeda 5A isotherm to examine. We will perform a DR plot, with increased verbosity to observe the resulting linear fit. The function returns a dictionary with the calculated pore volume and adsorption potential. End of explanation """ results = pgc.dr_plot(isotherm, p_limits=[0, 0.1], verbose=True) """ Explanation: We can specify the pressure limits for the DR plot, to select only the points at low pressure for a better fit. End of explanation """ results = pgc.da_plot(isotherm, p_limits=[0,0.1], exp=2.3, verbose=True) """ Explanation: An extension of the DR model is the Dubinin-Astakov (DA) model. In the DA equation, the exponent can vary, and is usually chosen between 1 (for surfaces) and 3 (for micropores). For an explanation of the theory, check the function reference. We then use the da_plot function and specify the exponent to be 2.3 (larger than the standard DR exponent of 2) End of explanation """ result = pgc.da_plot(isotherm, p_limits=[0, 0.1], exp=None, verbose=True) """ Explanation: The DA plot can also automatically test which exponent gives the best fit between 1 and 3, if the parameter is left blank. The calculated exponent is returned in the result dictionary. End of explanation """
oasis-open/cti-python-stix2
docs/guide/filesystem.ipynb
bsd-3-clause
from stix2 import FileSystemStore # create FileSystemStore fs = FileSystemStore("/tmp/stix2_store") # retrieve STIX2 content from FileSystemStore ap = fs.get("attack-pattern--0a3ead4e-6d47-4ccb-854c-a6a4f9d96b22") mal = fs.get("malware--92ec0cbd-2c30-44a2-b270-73f4ec949841") # for visual purposes print(mal.serialize(pretty=True)) from stix2 import ThreatActor, Indicator # create new STIX threat-actor ta = ThreatActor(name="Adjective Bear", sophistication="innovator", resource_level="government", goals=[ "compromising media outlets", "water-hole attacks geared towards political, military targets", "intelligence collection" ]) # create new indicators ind = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") ind1 = Indicator(description="Crusades C2 implant 2", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '64c7e05e40a59511743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") # add STIX object (threat-actor) to FileSystemStore fs.add(ta) # can also add multiple STIX objects to FileSystemStore in one call fs.add([ind, ind1]) """ Explanation: FileSystem The FileSystem suite contains FileSystemStore, FileSystemSource and FileSystemSink. Under the hood, all FileSystem objects point to a file directory (on disk) that contains STIX 2 content. The directory and file structure of the intended STIX 2 content should be: stix2_content/ STIX2 Domain Object type/ STIX2 Domain Object ID/ 'modified' timestamp.json 'modified' timestamp.json STIX2 Domain Object ID/ 'modified' timestamp.json . . STIX2 Domain Object type/ STIX2 Domain Object ID/ 'modified' timestamp.json . . . . . . STIX2 Domain Object type/ The master STIX 2 content directory contains subdirectories, each of which aligns to a STIX 2 domain object type (i.e. "attack-pattern", "campaign", "malware", etc.). Within each STIX 2 domain object type's subdirectory are further subdirectories containing JSON files that are STIX 2 domain objects of the specified type; the name of each of these subdirectories is the ID of the associated STIX 2 domain object. Inside each of these subdirectories are JSON files, the names of which correspond to the modified timestamp of the STIX 2 domain object found within that file. A real example of the FileSystem directory structure: stix2_content/ /attack-pattern /attack-pattern--00d0b012-8a03-410e-95de-5826bf542de6 20201211035036648071.json /attack-pattern--0a3ead4e-6d47-4ccb-854c-a6a4f9d96b22 20201210035036648071.json /attack-pattern--1b7ba276-eedc-4951-a762-0ceea2c030ec 20201111035036648071.json /campaign /course-of-action /course-of-action--2a8de25c-f743-4348-b101-3ee33ab5871b 20201011035036648071.json /course-of-action--2c3ce852-06a2-40ee-8fe6-086f6402a739 20201010035036648071.json /identity /identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5 20201215035036648071.json /indicator /intrusion-set /malware /malware--1d808f62-cf63-4063-9727-ff6132514c22 20201211045036648071.json /malware--2eb9b131-d333-4a48-9eb4-d8dec46c19ee 20201211035036648072.json /observed-data /report /threat-actor /vulnerability FileSystemStore is intended for use cases where STIX 2 content is retrieved and pushed to the same file directory. As FileSystemStore is just a wrapper around a paired FileSystemSource and FileSystemSink that point the same file directory. For use cases where STIX 2 content will only be retrieved or pushed, then a FileSystemSource and FileSystemSink can be used individually. They can also be used individually when STIX 2 content will be retrieved from one distinct file directory and pushed to another. FileSystem API A note on get(), all_versions(), and query(): The format of the STIX2 content targeted by the FileSystem suite is JSON files. When the FileSystemStore retrieves STIX 2 content (in JSON) from disk, it will attempt to parse the content into full-featured python-stix2 objects and returned as such. A note on add(): When STIX content is added (pushed) to the file system, the STIX content can be supplied in the following forms: Python STIX objects, Python dictionaries (of valid STIX objects or Bundles), JSON-encoded strings (of valid STIX objects or Bundles), or a (Python) list of any of the previously listed types. Any of the previous STIX content forms will be converted to a STIX JSON object (in a STIX Bundle) and written to disk. FileSystem Examples FileSystemStore Use the FileSystemStore when you want to both retrieve STIX content from the file system and push STIX content to it, too. End of explanation """ from stix2 import FileSystemSource # create FileSystemSource fs_source = FileSystemSource("/tmp/stix2_source") # retrieve STIX 2 objects ap = fs_source.get("attack-pattern--0a3ead4e-6d47-4ccb-854c-a6a4f9d96b22") # for visual purposes print(ap) from stix2 import Filter # create filter for type=malware query = [Filter("type", "=", "malware")] # query on the filter mals = fs_source.query(query) for mal in mals: print(mal.id) # add more filters to the query query.append(Filter("modified", ">" , "2017-05-31T21:33:10.772474Z")) mals = fs_source.query(query) # for visual purposes for mal in mals: print(mal.id) """ Explanation: FileSystemSource Use the FileSystemSource when you only want to retrieve STIX content from the file system. End of explanation """ from stix2 import FileSystemSink, Campaign, Indicator # create FileSystemSink fs_sink = FileSystemSink("/tmp/stix2_sink") # create STIX objects and add to sink camp = Campaign(name="The Crusades", objective="Infiltrating Israeli, Iranian and Palestinian digital infrastructure and government systems.", aliases=["Desert Moon"]) ind = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") ind1 = Indicator(description="Crusades C2 implant", pattern_type="stix", pattern="[file:hashes.'SHA-256' = '54b7e05e39a59428743635242e4a867c932140a999f52a1e54fa7ee6a440c73b']") # add Campaign object to FileSystemSink fs_sink.add(camp) # can also add STIX objects to FileSystemSink in one call fs_sink.add([ind, ind1]) """ Explanation: FileSystemSink Use the FileSystemSink when you only want to push STIX content to the file system. End of explanation """
eblur/clarsach
notebooks/TestAthenaXIFU.ipynb
gpl-3.0
%matplotlib notebook import matplotlib.pyplot as plt try: import seaborn as sns except ImportError: print("Seaborn not installed. Oh well.") import numpy as np import astropy.io.fits as fits import sherpa.astro.ui as ui from clarsach.respond import RMF, ARF """ Explanation: Test Whether Clàrsach Works With Athena X-IFU Simulations Let's test whether I can make it work on Athena X-IFU simulations. This will be complicated by the fact that sherpa doesn't seem to read the RMF file: End of explanation """ datadir = "../data/athena/" data_file = "26.pha" rmf_file = "athena_xifu_rmf_highres_v20150609.rmf" arf_file = "athena_xifu_sixte_1469_onaxis_v20150402.arf" """ Explanation: Let's load some data: End of explanation """ hdulist = fits.open(datadir+data_file) hdulist.info() s = hdulist["SPECTRUM"] s.columns channel = s.data.field("CHANNEL") counts = s.data.field("COUNTS") plt.figure(figsize=(10,5)) plt.plot(channel, counts) """ Explanation: Let's load the data using Clàrsach: End of explanation """ arf = ARF(datadir+arf_file) rmf = RMF(datadir+rmf_file) """ Explanation: Let's also load the ARF and RMF: End of explanation """ resp_model = np.ones_like(counts) m_arf = arf.apply_arf(resp_model) m_rmf = rmf.apply_rmf(m_arf) c_deconv = counts/m_rmf plt.figure(figsize=(10, 5)) plt.plot(channel, c_deconv) plt.xscale("log") """ Explanation: Let's make an empty model to divide out the responses: End of explanation """ ui.load_data("26", datadir+data_file) d = ui.get_data("26") arf_s = d.get_arf() rmf_s = d.get_rmf() """ Explanation: This seems to be working not badly. Let's try the same with sherpa: End of explanation """ print("ARF: " + str(arf_s)) print("RMF: " + str(rmf_s)) """ Explanation: Do the ARF and RMF exist? End of explanation """ assert np.all(arf_s.specresp == arf.specresp), "Clarsach ARF is different from Sherpa ARF" """ Explanation: There's no RMF, because the RMF for Athena does not seem to be a variable length field and is thus not read in. Oh well. Let's check whether at least the ARF is the same: End of explanation """ ui.set_source("26", ui.polynom1d.truespec) c_deconv_s = ui.get_ratio_plot("26").y e_deconv_s = ui.get_ratio_plot("26").x plt.figure(figsize=(10,5)) plt.plot(e_deconv_s, c_deconv, label="Clarsach Deconvolution") plt.plot(e_deconv_s, c_deconv_s, label="Sherpa Deconvolution") plt.legend() plt.yscale('log') np.allclose(c_deconv, c_deconv_s) """ Explanation: Looks like this worked. Let's do the deconvolution with sherpa and look at the results: End of explanation """ import astropy.modeling.models as models from astropy.modeling.fitting import _fitter_to_model_params from scipy.special import gammaln as scipy_gammaln pl = models.PowerLaw1D() """ Explanation: Well, I didn't actually expect them to be the same, so all right. This might also be due to the fact that I don't understand everything about what ratio_plot is doing; at some point I need to talk to Victoria about that. Modeling the Spectrum I can't actually model the full spectrum right now, because I don't have the XSPEC models, thus I don't have the galactic absorption model. This'll have to wait to later. Let's take the second half of the spectrum and fit a model to it. For now, let's ignore the lines and just fit a basic power law: End of explanation """ pl.x_0.fixed = True """ Explanation: We'll need to fix the x_0 parameter of the power law model to continue: End of explanation """ class PoissonLikelihood(object): def __init__(self, x, y, model, arf=None, rmf=None, bounds=None): self.x = x self.y = y self.model = model self.arf = arf self.rmf = rmf if bounds is None: bounds = [self.x[0], self.x[-1]] min_idx = self.x.searchsorted(bounds[0]) max_idx = self.x.searchsorted(bounds[1]) self.idx = [min_idx, max_idx] def evaluate(self, pars): # store the new parameters in the model _fitter_to_model_params(self.model, pars) # evaluate the model at the positions x mean_model = self.model(self.x) # run the ARF and RMF calculations if arf is not None and rmf is not None: m_arf = arf.apply_arf(mean_model) ymodel = rmf.apply_rmf(m_arf) else: ymodel = mean_model # cut out the part of the spectrum that's of interest y = self.y[self.idx[0]:self.idx[1]] ymodel = ymodel[self.idx[0]:self.idx[1]] # compute the log-likelihood loglike = np.sum(-ymodel + y*np.log(ymodel) \ - scipy_gammaln(y + 1.)) if np.isfinite(loglike): return loglike else: return -1.e16 def __call__(self, pars): l = -self.evaluate(pars) #print(l) return l """ Explanation: Let's define a Poisson log-likelihood: End of explanation """ loglike = PoissonLikelihood(e_deconv_s, counts, pl, arf=arf, rmf=rmf, bounds=[1.0, 6.0]) loglike([1.0, 2.0]) """ Explanation: Ok, cool, let's make a PoissonLikelihood object to use: End of explanation """ from scipy.optimize import minimize opt = minimize(loglike, [1.0, 1.0]) opt """ Explanation: Let's fit this with a minimization algorithm: End of explanation """ _fitter_to_model_params(pl, opt.x) mean_model = pl(loglike.x) m_arf = arf.apply_arf(mean_model) ymodel = rmf.apply_rmf(m_arf) ymodel_small = ymodel[loglike.idx[0]:loglike.idx[1]] y_small = loglike.y[loglike.idx[0]:loglike.idx[1]] e_deconv_small = e_deconv_s[loglike.idx[0]:loglike.idx[1]] print(np.mean(y_small-ymodel_small)) plt.figure() plt.plot(e_deconv_small, y_small, label="Data") plt.plot(e_deconv_small, ymodel_small, label="Model") plt.legend() """ Explanation: Looks like it has accurately found the photon index of 2. Let's make a best-fit example model and plot the raw spectra: End of explanation """ plt.figure(figsize=(10,5)) plt.plot(e_deconv_small, c_deconv[loglike.idx[0]:loglike.idx[1]], label="Data") plt.plot(e_deconv_small, mean_model[loglike.idx[0]:loglike.idx[1]], label="Best-fit model") plt.xlim(1.0, 6.0) plt.legend() """ Explanation: Let's also plot the deconvolved version for fun: End of explanation """
owlas/magpy
docs/source/notebooks/single-particle-equilibrium.ipynb
bsd-3-clause
import numpy as np # anisotropy energy of the system def anisotropy_e(theta, sigma): return -sigma*np.cos(theta)**2 # numerator of the Boltzmann distribution # (i.e. without the partition function Z) def p_unorm(theta, sigma): return np.sin(theta)*np.exp(-anisotropy_e(theta, sigma)) """ Explanation: Thermal equilibrium of a single particle In a large ensemble of identical systems each member will have a different state due to thermal fluctuations, even if all the systems were initialised in the same initial state. As we integrate the dynamics of the ensemble we will have a distribution of states (i.e. the states of each member of the system). However, as the ensemble evolves, the distribution over the states eventually reaches a stationary distribution: the Boltzmann distribution. Even though the state of each member in the ensemble contitues to fluctuate, the ensemble as a whole is in a stastistical equilibrium (thermal equilibrium). For an ensemble of single particles, we can compute the Boltzmann distribution by hand. In this example, we compare the analytical solution with the result of simulating an ensemble with Magpy. Problem setup A single particle has a uniaxial anisotropy axis $K$ and a magnetic moment of three components (x,y,z components). The angle $\theta$ is the angle between the magnetic moment and the anisotropy axis. Boltzmann distribution The Boltzmann distribution represents of states over the ensemble; here the state is the solid angle $\phi=\sin(\theta)$ (i.e. the distribution over the surface of the sphere). The distribution is parameterised by the temperature of the system and the energy landscape of the problem. $$p(\theta) = \frac{\sin(\theta)e^{-E(\theta)/(K_BT)}}{Z}$$ where $Z$ is called the partition function: $$Z=\int_\theta \sin(\theta)e^{-E(\theta)/(K_BT)}\mathrm{d}\theta$$ Stoner-Wohlfarth model The energy function for a single domain magnetic nanoparticle is given by the Stoner-Wohlfarth equation: $$\frac{E\left(\theta\right)}{K_BT}=-\sigma\cos^2\theta$$ where $\sigma$ is called the normalised anisotropy strength: $$\sigma=\frac{KV}{K_BT}$$ Functions for analytic solution End of explanation """ from scipy.integrate import quad # The analytic Boltzmann distribution def boltzmann(thetas, sigma): Z = quad(lambda t: p_unorm(t, sigma), 0, thetas[-1])[0] distribution = np.array([ p_unorm(t, sigma) / Z for t in thetas ]) return distribution """ Explanation: We use the quadrature rule to numerically evaluate the partition function $Z$. End of explanation """ import matplotlib.pyplot as plt %matplotlib inline thetas = np.linspace(0, np.pi, 1000) sigmas = [1, 3, 5, 7] e_landscape = [anisotropy_e(thetas, s) for s in sigmas] for s, e in zip(sigmas, e_landscape): plt.plot(thetas, e, label='$\sigma={}$'.format(s)) plt.legend(); plt.xlabel('Angle (radians)'); plt.ylabel('Energy') plt.title('Energy landscape for a single particle'); """ Explanation: Energy landscape We can plot the energy landscape (energy as a function of the system variables) End of explanation """ p_dist = [boltzmann(thetas, s) for s in sigmas] for s, p in zip(sigmas, p_dist): plt.plot(thetas, p, label='$\sigma={}$'.format(s)) plt.legend(); plt.xlabel('Angle (radians)') plt.ylabel('Probability of angle') plt.title('Probability distribution of angle'); """ Explanation: We observe that: - The energy of the system has two minima: one alongside each direction of the anisotropy axis. - The minima are separated by a maxima: perpendicular to the anisotropy axis. - Stronger anisotropy increases the size of the energy barrier between the two minima. Equilibrium distribution (Boltzmann) We can also plot the equilibrium distribution of the system, which is the probability distribution over the system states in a large ensemble of systems. End of explanation """ import magpy as mp # These parameters will determine the distribution K = 1e5 r = 7e-9 T = 300 kdir = [0., 0., 1.] # These parameters affect the dynamics but # have no effect on the equilibrium Ms = 400e3 location = [0., 0., 0.] alpha=1.0 initial_direction = [0., 0., 1.] # Normalised anisotropy strength KV/KB/T V = 4./3 * np.pi * r**3 kb = mp.core.get_KB() sigma = K * V / kb / T print(sigma) import magpy as mp single_particle = mp.Model( anisotropy=[K], anisotropy_axis=[kdir], damping=alpha, location=[location], magnetisation=Ms, magnetisation_direction=[initial_direction], radius=[r], temperature=T ) """ Explanation: What does this mean? If we had an ensemble of single particles, the distribution of the states of those particles varies greatly depending on $\sigma$. Remember we can decrease $\sigma$ by reducing the anisotropy strength or particle size or by increasing the temperature. - When $\sigma$ is high, most of the particles in the ensemble will be found closely aligned with the anisotropy axis. - When $\sigma$ is low, the states of the particles are more evenly distributed. Magpy equilibrium Using Magpy, we can simulate the dynamics of the state of a single nanoparticle. If we simulate a large ensemble of these systems for 'long enough', the distribution of states will reach equilibrium. If Magpy is implemented correctly, we should recover the analytical distribution from above. Set up the model Select the parameters for the single particle End of explanation """ particle_ensemble = mp.EnsembleModel( base_model=single_particle, N=10000 ) """ Explanation: Create an ensemble From the single particle we create an ensemble of 10,000 identical particles. End of explanation """ res = particle_ensemble.simulate( end_time=1e-9, time_step=1e-12, max_samples=50, random_state=1001, implicit_solve=True ) """ Explanation: Simulate Now we simulate! We don't need to simulate for very long because $\sigma$ is very high and the system will reach equilibrium quickly. End of explanation """ plt.plot(res.time, res.ensemble_magnetisation()) plt.title('10,000 single particles - ensemble magnetisation') plt.xlabel('Time'); plt.ylabel('Magnetisation'); """ Explanation: Check that we have equilibriated End of explanation """ M_z = np.array([state['z'][0] for state in res.final_state()]) m_z = M_z / Ms simulated_thetas = np.arccos(m_z) """ Explanation: We can see that the system has reached a local minima. We could let the simulation run until the ensemble relaxes into both minima but it would take a very long time because the energy barrier is so high in this example. Compute theta The results of the simulation are x,y,z coordinates of the magnetisation of each particle in the ensemble. We need to convert these into angles. End of explanation """ theta_grid = np.linspace(0.0, simulated_thetas.max(), 100) analytical_probability = boltzmann(theta_grid, sigma) plt.hist(simulated_thetas, normed=True, bins=80, label='Simulated'); plt.plot(theta_grid, analytical_probability, label='Analytical') plt.title('Simulated and analytical distributions') plt.xlabel('Angle (radians)'); plt.ylabel('Probability of angle'); """ Explanation: Compare to analytical solution Now we compare our empirical distribution of states to the analytical distribution that we computed above. End of explanation """
seifip/udacity-deep-learning-nanodegree
batch-norm/Batch_Normalization_Lesson.ipynb
mit
# Import necessary packages import tensorflow as tf import tqdm import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import MNIST data so we have something for our experiments from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) """ Explanation: Batch Normalization – Lesson What is it? What are it's benefits? How do we add it to a network? Let's see it work! What are you hiding? What is Batch Normalization?<a id='theory'></a> Batch normalization was introduced in Sergey Ioffe's and Christian Szegedy's 2015 paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. The idea is that, instead of just normalizing the inputs to the network, we normalize the inputs to layers within the network. It's called "batch" normalization because during training, we normalize each layer's inputs by using the mean and variance of the values in the current mini-batch. Why might this help? Well, we know that normalizing the inputs to a network helps the network learn. But a network is a series of layers, where the output of one layer becomes the input to another. That means we can think of any layer in a neural network as the first layer of a smaller network. For example, imagine a 3 layer network. Instead of just thinking of it as a single network with inputs, layers, and outputs, think of the output of layer 1 as the input to a two layer network. This two layer network would consist of layers 2 and 3 in our original network. Likewise, the output of layer 2 can be thought of as the input to a single layer network, consisting only of layer 3. When you think of it like that - as a series of neural networks feeding into each other - then it's easy to imagine how normalizing the inputs to each layer would help. It's just like normalizing the inputs to any other neural network, but you're doing it at every layer (sub-network). Beyond the intuitive reasons, there are good mathematical reasons why it helps the network learn better, too. It helps combat what the authors call internal covariate shift. This discussion is best handled in the paper and in Deep Learning a book you can read online written by Ian Goodfellow, Yoshua Bengio, and Aaron Courville. Specifically, check out the batch normalization section of Chapter 8: Optimization for Training Deep Models. Benefits of Batch Normalization<a id="benefits"></a> Batch normalization optimizes network training. It has been shown to have several benefits: 1. Networks train faster – Each training iteration will actually be slower because of the extra calculations during the forward pass and the additional hyperparameters to train during back propagation. However, it should converge much more quickly, so training should be faster overall. 2. Allows higher learning rates – Gradient descent usually requires small learning rates for the network to converge. And as networks get deeper, their gradients get smaller during back propagation so they require even more iterations. Using batch normalization allows us to use much higher learning rates, which further increases the speed at which networks train. 3. Makes weights easier to initialize – Weight initialization can be difficult, and it's even more difficult when creating deeper networks. Batch normalization seems to allow us to be much less careful about choosing our initial starting weights. 4. Makes more activation functions viable – Some activation functions do not work well in some situations. Sigmoids lose their gradient pretty quickly, which means they can't be used in deep networks. And ReLUs often die out during training, where they stop learning completely, so we need to be careful about the range of values fed into them. Because batch normalization regulates the values going into each activation function, non-linearlities that don't seem to work well in deep networks actually become viable again. 5. Simplifies the creation of deeper networks – Because of the first 4 items listed above, it is easier to build and faster to train deeper neural networks when using batch normalization. And it's been shown that deeper networks generally produce better results, so that's great. 6. Provides a bit of regularlization – Batch normalization adds a little noise to your network. In some cases, such as in Inception modules, batch normalization has been shown to work as well as dropout. But in general, consider batch normalization as a bit of extra regularization, possibly allowing you to reduce some of the dropout you might add to a network. 7. May give better results overall – Some tests seem to show batch normalization actually improves the training results. However, it's really an optimization to help train faster, so you shouldn't think of it as a way to make your network better. But since it lets you train networks faster, that means you can iterate over more designs more quickly. It also lets you build deeper networks, which are usually better. So when you factor in everything, you're probably going to end up with better results if you build your networks with batch normalization. Batch Normalization in TensorFlow<a id="implementation_1"></a> This section of the notebook shows you one way to add batch normalization to a neural network built in TensorFlow. The following cell imports the packages we need in the notebook and loads the MNIST dataset to use in our experiments. However, the tensorflow package contains all the code you'll actually need for batch normalization. End of explanation """ class NeuralNet: def __init__(self, initial_weights, activation_fn, use_batch_norm): """ Initializes this object, creating a TensorFlow graph using the given parameters. :param initial_weights: list of NumPy arrays or Tensors Initial values for the weights for every layer in the network. We pass these in so we can create multiple networks with the same starting weights to eliminate training differences caused by random initialization differences. The number of items in the list defines the number of layers in the network, and the shapes of the items in the list define the number of nodes in each layer. e.g. Passing in 3 matrices of shape (784, 256), (256, 100), and (100, 10) would create a network with 784 inputs going into a hidden layer with 256 nodes, followed by a hidden layer with 100 nodes, followed by an output layer with 10 nodes. :param activation_fn: Callable The function used for the output of each hidden layer. The network will use the same activation function on every hidden layer and no activate function on the output layer. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. :param use_batch_norm: bool Pass True to create a network that uses batch normalization; False otherwise Note: this network will not use batch normalization on layers that do not have an activation function. """ # Keep track of whether or not this network uses batch normalization. self.use_batch_norm = use_batch_norm self.name = "With Batch Norm" if use_batch_norm else "Without Batch Norm" # Batch normalization needs to do different calculations during training and inference, # so we use this placeholder to tell the graph which behavior to use. self.is_training = tf.placeholder(tf.bool, name="is_training") # This list is just for keeping track of data we want to plot later. # It doesn't actually have anything to do with neural nets or batch normalization. self.training_accuracies = [] # Create the network graph, but it will not actually have any real values until after you # call train or test self.build_network(initial_weights, activation_fn) def build_network(self, initial_weights, activation_fn): """ Build the graph. The graph still needs to be trained via the `train` method. :param initial_weights: list of NumPy arrays or Tensors See __init__ for description. :param activation_fn: Callable See __init__ for description. """ self.input_layer = tf.placeholder(tf.float32, [None, initial_weights[0].shape[0]]) layer_in = self.input_layer for weights in initial_weights[:-1]: layer_in = self.fully_connected(layer_in, weights, activation_fn) self.output_layer = self.fully_connected(layer_in, initial_weights[-1]) def fully_connected(self, layer_in, initial_weights, activation_fn=None): """ Creates a standard, fully connected layer. Its number of inputs and outputs will be defined by the shape of `initial_weights`, and its starting weight values will be taken directly from that same parameter. If `self.use_batch_norm` is True, this layer will include batch normalization, otherwise it will not. :param layer_in: Tensor The Tensor that feeds into this layer. It's either the input to the network or the output of a previous layer. :param initial_weights: NumPy array or Tensor Initial values for this layer's weights. The shape defines the number of nodes in the layer. e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 outputs. :param activation_fn: Callable or None (default None) The non-linearity used for the output of the layer. If None, this layer will not include batch normalization, regardless of the value of `self.use_batch_norm`. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. """ # Since this class supports both options, only use batch normalization when # requested. However, do not use it on the final layer, which we identify # by its lack of an activation function. if self.use_batch_norm and activation_fn: # Batch normalization uses weights as usual, but does NOT add a bias term. This is because # its calculations include gamma and beta variables that make the bias term unnecessary. # (See later in the notebook for more details.) weights = tf.Variable(initial_weights) linear_output = tf.matmul(layer_in, weights) # Apply batch normalization to the linear combination of the inputs and weights batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) # Now apply the activation function, *after* the normalization. return activation_fn(batch_normalized_output) else: # When not using batch normalization, create a standard layer that multiplies # the inputs and weights, adds a bias, and optionally passes the result # through an activation function. weights = tf.Variable(initial_weights) biases = tf.Variable(tf.zeros([initial_weights.shape[-1]])) linear_output = tf.add(tf.matmul(layer_in, weights), biases) return linear_output if not activation_fn else activation_fn(linear_output) def train(self, session, learning_rate, training_batches, batches_per_sample, save_model_as=None): """ Trains the model on the MNIST training dataset. :param session: Session Used to run training graph operations. :param learning_rate: float Learning rate used during gradient descent. :param training_batches: int Number of batches to train. :param batches_per_sample: int How many batches to train before sampling the validation accuracy. :param save_model_as: string or None (default None) Name to use if you want to save the trained model. """ # This placeholder will store the target labels for each mini batch labels = tf.placeholder(tf.float32, [None, 10]) # Define loss and optimizer cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=self.output_layer)) # Define operations for testing correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) if self.use_batch_norm: # If we don't include the update ops as dependencies on the train step, the # tf.layers.batch_normalization layers won't update their population statistics, # which will cause the model to fail at inference time with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) else: train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) # Train for the appropriate number of batches. (tqdm is only for a nice timing display) for i in tqdm.tqdm(range(training_batches)): # We use batches of 60 just because the original paper did. You can use any size batch you like. batch_xs, batch_ys = mnist.train.next_batch(60) session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) # Periodically test accuracy against the 5k validation images and store it for plotting later. if i % batches_per_sample == 0: test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images, labels: mnist.validation.labels, self.is_training: False}) self.training_accuracies.append(test_accuracy) # After training, report accuracy against test data test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.validation.images, labels: mnist.validation.labels, self.is_training: False}) print('{}: After training, final accuracy on validation set = {}'.format(self.name, test_accuracy)) # If you want to use this model later for inference instead of having to retrain it, # just construct it with the same parameters and then pass this file to the 'test' function if save_model_as: tf.train.Saver().save(session, save_model_as) def test(self, session, test_training_accuracy=False, include_individual_predictions=False, restore_from=None): """ Trains a trained model on the MNIST testing dataset. :param session: Session Used to run the testing graph operations. :param test_training_accuracy: bool (default False) If True, perform inference with batch normalization using batch mean and variance; if False, perform inference with batch normalization using estimated population mean and variance. Note: in real life, *always* perform inference using the population mean and variance. This parameter exists just to support demonstrating what happens if you don't. :param include_individual_predictions: bool (default True) This function always performs an accuracy test against the entire test set. But if this parameter is True, it performs an extra test, doing 200 predictions one at a time, and displays the results and accuracy. :param restore_from: string or None (default None) Name of a saved model if you want to test with previously saved weights. """ # This placeholder will store the true labels for each mini batch labels = tf.placeholder(tf.float32, [None, 10]) # Define operations for testing correct_prediction = tf.equal(tf.argmax(self.output_layer, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # If provided, restore from a previously saved model if restore_from: tf.train.Saver().restore(session, restore_from) # Test against all of the MNIST test data test_accuracy = session.run(accuracy, feed_dict={self.input_layer: mnist.test.images, labels: mnist.test.labels, self.is_training: test_training_accuracy}) print('-'*75) print('{}: Accuracy on full test set = {}'.format(self.name, test_accuracy)) # If requested, perform tests predicting individual values rather than batches if include_individual_predictions: predictions = [] correct = 0 # Do 200 predictions, 1 at a time for i in range(200): # This is a normal prediction using an individual test case. However, notice # we pass `test_training_accuracy` to `feed_dict` as the value for `self.is_training`. # Remember that will tell it whether it should use the batch mean & variance or # the population estimates that were calucated while training the model. pred, corr = session.run([tf.arg_max(self.output_layer,1), accuracy], feed_dict={self.input_layer: [mnist.test.images[i]], labels: [mnist.test.labels[i]], self.is_training: test_training_accuracy}) correct += corr predictions.append(pred[0]) print("200 Predictions:", predictions) print("Accuracy on 200 samples:", correct/200) """ Explanation: Neural network classes for testing The following class, NeuralNet, allows us to create identical neural networks with and without batch normalization. The code is heavily documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the notebook, but the comments within the code blocks may answer some of your questions. About the code: This class is not meant to represent TensorFlow best practices – the design choices made here are to support the discussion related to batch normalization. It's also important to note that we use the well-known MNIST data for these examples, but the networks we create are not meant to be good for performing handwritten character recognition. We chose this network architecture because it is similar to the one used in the original paper, which is complex enough to demonstrate some of the benefits of batch normalization while still being fast to train. End of explanation """ def plot_training_accuracies(*args, **kwargs): """ Displays a plot of the accuracies calculated during training to demonstrate how many iterations it took for the model(s) to converge. :param args: One or more NeuralNet objects You can supply any number of NeuralNet objects as unnamed arguments and this will display their training accuracies. Be sure to call `train` the NeuralNets before calling this function. :param kwargs: You can supply any named parameters here, but `batches_per_sample` is the only one we look for. It should match the `batches_per_sample` value you passed to the `train` function. """ fig, ax = plt.subplots() batches_per_sample = kwargs['batches_per_sample'] for nn in args: ax.plot(range(0,len(nn.training_accuracies)*batches_per_sample,batches_per_sample), nn.training_accuracies, label=nn.name) ax.set_xlabel('Training steps') ax.set_ylabel('Accuracy') ax.set_title('Validation Accuracy During Training') ax.legend(loc=4) ax.set_ylim([0,1]) plt.yticks(np.arange(0, 1.1, 0.1)) plt.grid(True) plt.show() def train_and_test(use_bad_weights, learning_rate, activation_fn, training_batches=50000, batches_per_sample=500): """ Creates two networks, one with and one without batch normalization, then trains them with identical starting weights, layers, batches, etc. Finally tests and plots their accuracies. :param use_bad_weights: bool If True, initialize the weights of both networks to wildly inappropriate weights; if False, use reasonable starting weights. :param learning_rate: float Learning rate used during gradient descent. :param activation_fn: Callable The function used for the output of each hidden layer. The network will use the same activation function on every hidden layer and no activate function on the output layer. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. :param training_batches: (default 50000) Number of batches to train. :param batches_per_sample: (default 500) How many batches to train before sampling the validation accuracy. """ # Use identical starting weights for each network to eliminate differences in # weight initialization as a cause for differences seen in training performance # # Note: The networks will use these weights to define the number of and shapes of # its layers. The original batch normalization paper used 3 hidden layers # with 100 nodes in each, followed by a 10 node output layer. These values # build such a network, but feel free to experiment with different choices. # However, the input size should always be 784 and the final output should be 10. if use_bad_weights: # These weights should be horrible because they have such a large standard deviation weights = [np.random.normal(size=(784,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,100), scale=5.0).astype(np.float32), np.random.normal(size=(100,10), scale=5.0).astype(np.float32) ] else: # These weights should be good because they have such a small standard deviation weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,10), scale=0.05).astype(np.float32) ] # Just to make sure the TensorFlow's default graph is empty before we start another # test, because we don't bother using different graphs or scoping and naming # elements carefully in this sample code. tf.reset_default_graph() # build two versions of same network, 1 without and 1 with batch normalization nn = NeuralNet(weights, activation_fn, False) bn = NeuralNet(weights, activation_fn, True) # train and test the two models with tf.Session() as sess: tf.global_variables_initializer().run() nn.train(sess, learning_rate, training_batches, batches_per_sample) bn.train(sess, learning_rate, training_batches, batches_per_sample) nn.test(sess) bn.test(sess) # Display a graph of how validation accuracies changed during training # so we can compare how the models trained and when they converged plot_training_accuracies(nn, bn, batches_per_sample=batches_per_sample) """ Explanation: There are quite a few comments in the code, so those should answer most of your questions. However, let's take a look at the most important lines. We add batch normalization to layers inside the fully_connected function. Here are some important points about that code: 1. Layers with batch normalization do not include a bias term. 2. We use TensorFlow's tf.layers.batch_normalization function to handle the math. (We show lower-level ways to do this later in the notebook.) 3. We tell tf.layers.batch_normalization whether or not the network is training. This is an important step we'll talk about later. 4. We add the normalization before calling the activation function. In addition to that code, the training step is wrapped in the following with statement: python with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): This line actually works in conjunction with the training parameter we pass to tf.layers.batch_normalization. Without it, TensorFlow's batch normalization layer will not operate correctly during inference. Finally, whenever we train the network or perform inference, we use the feed_dict to set self.is_training to True or False, respectively, like in the following line: python session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) We'll go into more details later, but next we want to show some experiments that use this code and test networks with and without batch normalization. Batch Normalization Demos<a id='demos'></a> This section of the notebook trains various networks with and without batch normalization to demonstrate some of the benefits mentioned earlier. We'd like to thank the author of this blog post Implementing Batch Normalization in TensorFlow. That post provided the idea of - and some of the code for - plotting the differences in accuracy during training, along with the idea for comparing multiple networks using the same initial weights. Code to support testing The following two functions support the demos we run in the notebook. The first function, plot_training_accuracies, simply plots the values found in the training_accuracies lists of the NeuralNet objects passed to it. If you look at the train function in NeuralNet, you'll see it that while it's training the network, it periodically measures validation accuracy and stores the results in that list. It does that just to support these plots. The second function, train_and_test, creates two neural nets - one with and one without batch normalization. It then trains them both and tests them, calling plot_training_accuracies to plot how their accuracies changed over the course of training. The really imporant thing about this function is that it initializes the starting weights for the networks outside of the networks and then passes them in. This lets it train both networks from the exact same starting weights, which eliminates performance differences that might result from (un)lucky initial weights. End of explanation """ train_and_test(False, 0.01, tf.nn.relu) """ Explanation: Comparisons between identical networks, with and without batch normalization The next series of cells train networks with various settings to show the differences with and without batch normalization. They are meant to clearly demonstrate the effects of batch normalization. We include a deeper discussion of batch normalization later in the notebook. The following creates two networks using a ReLU activation function, a learning rate of 0.01, and reasonable starting weights. End of explanation """ train_and_test(False, 0.01, tf.nn.relu, 2000, 50) """ Explanation: As expected, both networks train well and eventually reach similar test accuracies. However, notice that the model with batch normalization converges slightly faster than the other network, reaching accuracies over 90% almost immediately and nearing its max acuracy in 10 or 15 thousand iterations. The other network takes about 3 thousand iterations to reach 90% and doesn't near its best accuracy until 30 thousand or more iterations. If you look at the raw speed, you can see that without batch normalization we were computing over 1100 batches per second, whereas with batch normalization that goes down to just over 500. However, batch normalization allows us to perform fewer iterations and converge in less time over all. (We only trained for 50 thousand batches here so we could plot the comparison.) The following creates two networks with the same hyperparameters used in the previous example, but only trains for 2000 iterations. End of explanation """ train_and_test(False, 0.01, tf.nn.sigmoid) """ Explanation: As you can see, using batch normalization produces a model with over 95% accuracy in only 2000 batches, and it was above 90% at somewhere around 500 batches. Without batch normalization, the model takes 1750 iterations just to hit 80% – the network with batch normalization hits that mark after around 200 iterations! (Note: if you run the code yourself, you'll see slightly different results each time because the starting weights - while the same for each model - are different for each run.) In the above example, you should also notice that the networks trained fewer batches per second then what you saw in the previous example. That's because much of the time we're tracking is actually spent periodically performing inference to collect data for the plots. In this example we perform that inference every 50 batches instead of every 500, so generating the plot for this example requires 10 times the overhead for the same 2000 iterations. The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.relu) """ Explanation: With the number of layers we're using and this small learning rate, using a sigmoid activation function takes a long time to start learning. It eventually starts making progress, but it took over 45 thousand batches just to get over 80% accuracy. Using batch normalization gets to 90% in around one thousand batches. The following creates two networks using a ReLU activation function, a learning rate of 1, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.relu) """ Explanation: Now we're using ReLUs again, but with a larger learning rate. The plot shows how training started out pretty normally, with the network with batch normalization starting out faster than the other. But the higher learning rate bounces the accuracy around a bit more, and at some point the accuracy in the network without batch normalization just completely crashes. It's likely that too many ReLUs died off at this point because of the high learning rate. The next cell shows the same test again. The network with batch normalization performs the same way, and the other suffers from the same problem again, but it manages to train longer before it happens. End of explanation """ train_and_test(False, 1, tf.nn.sigmoid) """ Explanation: In both of the previous examples, the network with batch normalization manages to gets over 98% accuracy, and get near that result almost immediately. The higher learning rate allows the network to train extremely fast. The following creates two networks using a sigmoid activation function, a learning rate of 1, and reasonable starting weights. End of explanation """ train_and_test(False, 1, tf.nn.sigmoid, 2000, 50) """ Explanation: In this example, we switched to a sigmoid activation function. It appears to hande the higher learning rate well, with both networks achieving high accuracy. The cell below shows a similar pair of networks trained for only 2000 iterations. End of explanation """ train_and_test(False, 2, tf.nn.relu) """ Explanation: As you can see, even though these parameters work well for both networks, the one with batch normalization gets over 90% in 400 or so batches, whereas the other takes over 1700. When training larger networks, these sorts of differences become more pronounced. The following creates two networks using a ReLU activation function, a learning rate of 2, and reasonable starting weights. End of explanation """ train_and_test(False, 2, tf.nn.sigmoid) """ Explanation: With this very large learning rate, the network with batch normalization trains fine and almost immediately manages 98% accuracy. However, the network without normalization doesn't learn at all. The following creates two networks using a sigmoid activation function, a learning rate of 2, and reasonable starting weights. End of explanation """ train_and_test(False, 2, tf.nn.sigmoid, 2000, 50) """ Explanation: Once again, using a sigmoid activation function with the larger learning rate works well both with and without batch normalization. However, look at the plot below where we train models with the same parameters but only 2000 iterations. As usual, batch normalization lets it train faster. End of explanation """ train_and_test(True, 0.01, tf.nn.relu) """ Explanation: In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose random values with a standard deviation of 5. If you were really training a neural network, you would not want to do this. But these examples demonstrate how batch normalization makes your network much more resilient. The following creates two networks using a ReLU activation function, a learning rate of 0.01, and bad starting weights. End of explanation """ train_and_test(True, 0.01, tf.nn.sigmoid) """ Explanation: As the plot shows, without batch normalization the network never learns anything at all. But with batch normalization, it actually learns pretty well and gets to almost 80% accuracy. The starting weights obviously hurt the network, but you can see how well batch normalization does in overcoming them. The following creates two networks using a sigmoid activation function, a learning rate of 0.01, and bad starting weights. End of explanation """ train_and_test(True, 1, tf.nn.relu) """ Explanation: Using a sigmoid activation function works better than the ReLU in the previous example, but without batch normalization it would take a tremendously long time to train the network, if it ever trained at all. The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights.<a id="successful_example_lr_1"></a> End of explanation """ train_and_test(True, 1, tf.nn.sigmoid) """ Explanation: The higher learning rate used here allows the network with batch normalization to surpass 90% in about 30 thousand batches. The network without it never gets anywhere. The following creates two networks using a sigmoid activation function, a learning rate of 1, and bad starting weights. End of explanation """ train_and_test(True, 2, tf.nn.relu) """ Explanation: Using sigmoid works better than ReLUs for this higher learning rate. However, you can see that without batch normalization, the network takes a long time tro train, bounces around a lot, and spends a long time stuck at 90%. The network with batch normalization trains much more quickly, seems to be more stable, and achieves a higher accuracy. The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights.<a id="successful_example_lr_2"></a> End of explanation """ train_and_test(True, 2, tf.nn.sigmoid) """ Explanation: We've already seen that ReLUs do not do as well as sigmoids with higher learning rates, and here we are using an extremely high rate. As expected, without batch normalization the network doesn't learn at all. But with batch normalization, it eventually achieves 90% accuracy. Notice, though, how its accuracy bounces around wildly during training - that's because the learning rate is really much too high, so the fact that this worked at all is a bit of luck. The following creates two networks using a sigmoid activation function, a learning rate of 2, and bad starting weights. End of explanation """ train_and_test(True, 1, tf.nn.relu) """ Explanation: In this case, the network with batch normalization trained faster and reached a higher accuracy. Meanwhile, the high learning rate makes the network without normalization bounce around erratically and have trouble getting past 90%. Full Disclosure: Batch Normalization Doesn't Fix Everything Batch normalization isn't magic and it doesn't work every time. Weights are still randomly initialized and batches are chosen at random during training, so you never know exactly how training will go. Even for these tests, where we use the same initial weights for both networks, we still get different weights each time we run. This section includes two examples that show runs when batch normalization did not help at all. The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting weights. End of explanation """ train_and_test(True, 2, tf.nn.relu) """ Explanation: When we used these same parameters earlier, we saw the network with batch normalization reach 92% validation accuracy. This time we used different starting weights, initialized using the same standard deviation as before, and the network doesn't learn at all. (Remember, an accuracy around 10% is what the network gets if it just guesses the same value all the time.) The following creates two networks using a ReLU activation function, a learning rate of 2, and bad starting weights. End of explanation """ def fully_connected(self, layer_in, initial_weights, activation_fn=None): """ Creates a standard, fully connected layer. Its number of inputs and outputs will be defined by the shape of `initial_weights`, and its starting weight values will be taken directly from that same parameter. If `self.use_batch_norm` is True, this layer will include batch normalization, otherwise it will not. :param layer_in: Tensor The Tensor that feeds into this layer. It's either the input to the network or the output of a previous layer. :param initial_weights: NumPy array or Tensor Initial values for this layer's weights. The shape defines the number of nodes in the layer. e.g. Passing in 3 matrix of shape (784, 256) would create a layer with 784 inputs and 256 outputs. :param activation_fn: Callable or None (default None) The non-linearity used for the output of the layer. If None, this layer will not include batch normalization, regardless of the value of `self.use_batch_norm`. e.g. Pass tf.nn.relu to use ReLU activations on your hidden layers. """ if self.use_batch_norm and activation_fn: # Batch normalization uses weights as usual, but does NOT add a bias term. This is because # its calculations include gamma and beta variables that make the bias term unnecessary. weights = tf.Variable(initial_weights) linear_output = tf.matmul(layer_in, weights) num_out_nodes = initial_weights.shape[-1] # Batch normalization adds additional trainable variables: # gamma (for scaling) and beta (for shifting). gamma = tf.Variable(tf.ones([num_out_nodes])) beta = tf.Variable(tf.zeros([num_out_nodes])) # These variables will store the mean and variance for this layer over the entire training set, # which we assume represents the general population distribution. # By setting `trainable=False`, we tell TensorFlow not to modify these variables during # back propagation. Instead, we will assign values to these variables ourselves. pop_mean = tf.Variable(tf.zeros([num_out_nodes]), trainable=False) pop_variance = tf.Variable(tf.ones([num_out_nodes]), trainable=False) # Batch normalization requires a small constant epsilon, used to ensure we don't divide by zero. # This is the default value TensorFlow uses. epsilon = 1e-3 def batch_norm_training(): # Calculate the mean and variance for the data coming out of this layer's linear-combination step. # The [0] defines an array of axes to calculate over. batch_mean, batch_variance = tf.nn.moments(linear_output, [0]) # Calculate a moving average of the training data's mean and variance while training. # These will be used during inference. # Decay should be some number less than 1. tf.layers.batch_normalization uses the parameter # "momentum" to accomplish this and defaults it to 0.99 decay = 0.99 train_mean = tf.assign(pop_mean, pop_mean * decay + batch_mean * (1 - decay)) train_variance = tf.assign(pop_variance, pop_variance * decay + batch_variance * (1 - decay)) # The 'tf.control_dependencies' context tells TensorFlow it must calculate 'train_mean' # and 'train_variance' before it calculates the 'tf.nn.batch_normalization' layer. # This is necessary because the those two operations are not actually in the graph # connecting the linear_output and batch_normalization layers, # so TensorFlow would otherwise just skip them. with tf.control_dependencies([train_mean, train_variance]): return tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon) def batch_norm_inference(): # During inference, use the our estimated population mean and variance to normalize the layer return tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon) # Use `tf.cond` as a sort of if-check. When self.is_training is True, TensorFlow will execute # the operation returned from `batch_norm_training`; otherwise it will execute the graph # operation returned from `batch_norm_inference`. batch_normalized_output = tf.cond(self.is_training, batch_norm_training, batch_norm_inference) # Pass the batch-normalized layer output through the activation function. # The literature states there may be cases where you want to perform the batch normalization *after* # the activation function, but it is difficult to find any uses of that in practice. return activation_fn(batch_normalized_output) else: # When not using batch normalization, create a standard layer that multiplies # the inputs and weights, adds a bias, and optionally passes the result # through an activation function. weights = tf.Variable(initial_weights) biases = tf.Variable(tf.zeros([initial_weights.shape[-1]])) linear_output = tf.add(tf.matmul(layer_in, weights), biases) return linear_output if not activation_fn else activation_fn(linear_output) """ Explanation: When we trained with these parameters and batch normalization earlier, we reached 90% validation accuracy. However, this time the network almost starts to make some progress in the beginning, but it quickly breaks down and stops learning. Note: Both of the above examples use extremely bad starting weights, along with learning rates that are too high. While we've shown batch normalization can overcome bad values, we don't mean to encourage actually using them. The examples in this notebook are meant to show that batch normalization can help your networks train better. But these last two examples should remind you that you still want to try to use good network design choices and reasonable starting weights. It should also remind you that the results of each attempt to train a network are a bit random, even when using otherwise identical architectures. Batch Normalization: A Detailed Look<a id='implementation_2'></a> The layer created by tf.layers.batch_normalization handles all the details of implementing batch normalization. Many students will be fine just using that and won't care about what's happening at the lower levels. However, some students may want to explore the details, so here is a short explanation of what's really happening, starting with the equations you're likely to come across if you ever read about batch normalization. In order to normalize the values, we first need to find the average value for the batch. If you look at the code, you can see that this is not the average value of the batch inputs, but the average value coming out of any particular layer before we pass it through its non-linear activation function and then feed it as an input to the next layer. We represent the average as $\mu_B$, which is simply the sum of all of the values $x_i$ divided by the number of values, $m$ $$ \mu_B \leftarrow \frac{1}{m}\sum_{i=1}^m x_i $$ We then need to calculate the variance, or mean squared deviation, represented as $\sigma_{B}^{2}$. If you aren't familiar with statistics, that simply means for each value $x_i$, we subtract the average value (calculated earlier as $\mu_B$), which gives us what's called the "deviation" for that value. We square the result to get the squared deviation. Sum up the results of doing that for each of the values, then divide by the number of values, again $m$, to get the average, or mean, squared deviation. $$ \sigma_{B}^{2} \leftarrow \frac{1}{m}\sum_{i=1}^m (x_i - \mu_B)^2 $$ Once we have the mean and variance, we can use them to normalize the values with the following equation. For each value, it subtracts the mean and divides by the (almost) standard deviation. (You've probably heard of standard deviation many times, but if you have not studied statistics you might not know that the standard deviation is actually the square root of the mean squared deviation.) $$ \hat{x_i} \leftarrow \frac{x_i - \mu_B}{\sqrt{\sigma_{B}^{2} + \epsilon}} $$ Above, we said "(almost) standard deviation". That's because the real standard deviation for the batch is calculated by $\sqrt{\sigma_{B}^{2}}$, but the above formula adds the term epsilon, $\epsilon$, before taking the square root. The epsilon can be any small, positive constant - in our code we use the value 0.001. It is there partially to make sure we don't try to divide by zero, but it also acts to increase the variance slightly for each batch. Why increase the variance? Statistically, this makes sense because even though we are normalizing one batch at a time, we are also trying to estimate the population distribution – the total training set, which itself an estimate of the larger population of inputs your network wants to handle. The variance of a population is higher than the variance for any sample taken from that population, so increasing the variance a little bit for each batch helps take that into account. At this point, we have a normalized value, represented as $\hat{x_i}$. But rather than use it directly, we multiply it by a gamma value, $\gamma$, and then add a beta value, $\beta$. Both $\gamma$ and $\beta$ are learnable parameters of the network and serve to scale and shift the normalized value, respectively. Because they are learnable just like weights, they give your network some extra knobs to tweak during training to help it learn the function it is trying to approximate. $$ y_i \leftarrow \gamma \hat{x_i} + \beta $$ We now have the final batch-normalized output of our layer, which we would then pass to a non-linear activation function like sigmoid, tanh, ReLU, Leaky ReLU, etc. In the original batch normalization paper (linked in the beginning of this notebook), they mention that there might be cases when you'd want to perform the batch normalization after the non-linearity instead of before, but it is difficult to find any uses like that in practice. In NeuralNet's implementation of fully_connected, all of this math is hidden inside the following line, where linear_output serves as the $x_i$ from the equations: python batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) The next section shows you how to implement the math directly. Batch normalization without the tf.layers package Our implementation of batch normalization in NeuralNet uses the high-level abstraction tf.layers.batch_normalization, found in TensorFlow's tf.layers package. However, if you would like to implement batch normalization at a lower level, the following code shows you how. It uses tf.nn.batch_normalization from TensorFlow's neural net (nn) package. 1) You can replace the fully_connected function in the NeuralNet class with the below code and everything in NeuralNet will still work like it did before. End of explanation """ def batch_norm_test(test_training_accuracy): """ :param test_training_accuracy: bool If True, perform inference with batch normalization using batch mean and variance; if False, perform inference with batch normalization using estimated population mean and variance. """ weights = [np.random.normal(size=(784,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,100), scale=0.05).astype(np.float32), np.random.normal(size=(100,10), scale=0.05).astype(np.float32) ] tf.reset_default_graph() # Train the model bn = NeuralNet(weights, tf.nn.relu, True) # First train the network with tf.Session() as sess: tf.global_variables_initializer().run() bn.train(sess, 0.01, 2000, 2000) bn.test(sess, test_training_accuracy=test_training_accuracy, include_individual_predictions=True) """ Explanation: This version of fully_connected is much longer than the original, but once again has extensive comments to help you understand it. Here are some important points: It explicitly creates variables to store gamma, beta, and the population mean and variance. These were all handled for us in the previous version of the function. It initializes gamma to one and beta to zero, so they start out having no effect in this calculation: $y_i \leftarrow \gamma \hat{x_i} + \beta$. However, during training the network learns the best values for these variables using back propagation, just like networks normally do with weights. Unlike gamma and beta, the variables for population mean and variance are marked as untrainable. That tells TensorFlow not to modify them during back propagation. Instead, the lines that call tf.assign are used to update these variables directly. TensorFlow won't automatically run the tf.assign operations during training because it only evaluates operations that are required based on the connections it finds in the graph. To get around that, we add this line: with tf.control_dependencies([train_mean, train_variance]): before we run the normalization operation. This tells TensorFlow it needs to run those operations before running anything inside the with block. The actual normalization math is still mostly hidden from us, this time using tf.nn.batch_normalization. tf.nn.batch_normalization does not have a training parameter like tf.layers.batch_normalization did. However, we still need to handle training and inference differently, so we run different code in each case using the tf.cond operation. We use the tf.nn.moments function to calculate the batch mean and variance. 2) The current version of the train function in NeuralNet will work fine with this new version of fully_connected. However, it uses these lines to ensure population statistics are updated when using batch normalization: python if self.use_batch_norm: with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) else: train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) Our new version of fully_connected handles updating the population statistics directly. That means you can also simplify your code by replacing the above if/else condition with just this line: python train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) 3) And just in case you want to implement every detail from scratch, you can replace this line in batch_norm_training: python return tf.nn.batch_normalization(linear_output, batch_mean, batch_variance, beta, gamma, epsilon) with these lines: python normalized_linear_output = (linear_output - batch_mean) / tf.sqrt(batch_variance + epsilon) return gamma * normalized_linear_output + beta And replace this line in batch_norm_inference: python return tf.nn.batch_normalization(linear_output, pop_mean, pop_variance, beta, gamma, epsilon) with these lines: python normalized_linear_output = (linear_output - pop_mean) / tf.sqrt(pop_variance + epsilon) return gamma * normalized_linear_output + beta As you can see in each of the above substitutions, the two lines of replacement code simply implement the following two equations directly. The first line calculates the following equation, with linear_output representing $x_i$ and normalized_linear_output representing $\hat{x_i}$: $$ \hat{x_i} \leftarrow \frac{x_i - \mu_B}{\sqrt{\sigma_{B}^{2} + \epsilon}} $$ And the second line is a direct translation of the following equation: $$ y_i \leftarrow \gamma \hat{x_i} + \beta $$ We still use the tf.nn.moments operation to implement the other two equations from earlier – the ones that calculate the batch mean and variance used in the normalization step. If you really wanted to do everything from scratch, you could replace that line, too, but we'll leave that to you. Why the difference between training and inference? In the original function that uses tf.layers.batch_normalization, we tell the layer whether or not the network is training by passing a value for its training parameter, like so: python batch_normalized_output = tf.layers.batch_normalization(linear_output, training=self.is_training) And that forces us to provide a value for self.is_training in our feed_dict, like we do in this example from NeuralNet's train function: python session.run(train_step, feed_dict={self.input_layer: batch_xs, labels: batch_ys, self.is_training: True}) If you looked at the low level implementation, you probably noticed that, just like with tf.layers.batch_normalization, we need to do slightly different things during training and inference. But why is that? First, let's look at what happens when we don't. The following function is similar to train_and_test from earlier, but this time we are only testing one network and instead of plotting its accuracy, we perform 200 predictions on test inputs, 1 input at at time. We can use the test_training_accuracy parameter to test the network in training or inference modes (the equivalent of passing True or False to the feed_dict for is_training). End of explanation """ batch_norm_test(True) """ Explanation: In the following cell, we pass True for test_training_accuracy, which performs the same batch normalization that we normally perform during training. End of explanation """ batch_norm_test(False) """ Explanation: As you can see, the network guessed the same value every time! But why? Because during training, a network with batch normalization adjusts the values at each layer based on the mean and variance of that batch. The "batches" we are using for these predictions have a single input each time, so their values are the means, and their variances will always be 0. That means the network will normalize the values at any layer to zero. (Review the equations from before to see why a value that is equal to the mean would always normalize to zero.) So we end up with the same result for every input we give the network, because its the value the network produces when it applies its learned weights to zeros at every layer. Note: If you re-run that cell, you might get a different value from what we showed. That's because the specific weights the network learns will be different every time. But whatever value it is, it should be the same for all 200 predictions. To overcome this problem, the network does not just normalize the batch at each layer. It also maintains an estimate of the mean and variance for the entire population. So when we perform inference, instead of letting it "normalize" all the values using their own means and variance, it uses the estimates of the population mean and variance that it calculated while training. So in the following example, we pass False for test_training_accuracy, which tells the network that we it want to perform inference with the population statistics it calculates during training. End of explanation """
kunaltyagi/SDES
notes/python/p_norvig/algo/ProbabilityParadox.ipynb
gpl-3.0
from fractions import Fraction class ProbDist(dict): "A Probability Distribution; an {outcome: probability} mapping." def __init__(self, mapping=(), **kwargs): self.update(mapping, **kwargs) # Make probabilities sum to 1.0; assert no negative probabilities total = sum(self.values()) for outcome in self: self[outcome] = self[outcome] / total assert self[outcome] >= 0 def P(event, space): """The probability of an event, given a sample space of equiprobable outcomes. event: a collection of outcomes, or a predicate that is true of outcomes in the event. space: a set of outcomes or a probability distribution of {outcome: frequency}.""" if is_predicate(event): event = such_that(event, space) if isinstance(space, ProbDist): return sum(space[o] for o in space if o in event) else: return Fraction(len(event & space), len(space)) def such_that(predicate, space): """The outcomes in the sample space for which the predicate is true. If space is a set, return a subset {outcome,...}; if space is a ProbDist, return a ProbDist {outcome: frequency,...}; in both cases only with outcomes where predicate(element) is true.""" if isinstance(space, ProbDist): return ProbDist({o:space[o] for o in space if predicate(o)}) else: return {o for o in space if predicate(o)} is_predicate = callable def cross(A, B): "The set of ways of concatenating one item from collection A with one from B." return {a + b for a in A for b in B} def joint(A, B, sep=''): """The joint distribution of two independent probability distributions. Result is all entries of the form {a+sep+b: P(a)*P(b)}""" return ProbDist({a + sep + b: A[a] * B[b] for a in A for b in B}) """ Explanation: <div style="text-align: right">Peter Norvig, 3 Oct 2015, revised Oct-Feb 2016</div> Probability, Paradox, and the Reasonable Person Principle In another notebook, I introduced the basics of probability theory. I'll duplicate the code we developed there: End of explanation """ S = {'BG', 'BB', 'GB', 'GG'} """ Explanation: In this notebook we use this code to show how to solve some particularly perplexing paradoxical probability problems. Child Paradoxes In 1959, Martin Gardner posed these two problems: Child Problem 1. Mr. Jones has two children. The older child is a boy. What is the probability that both children are boys? Child Problem 2. Mr. Smith has two children. At least one of them is a boy. What is the probability that both children are boys? Then in 2006, Mike & Tom Starbird came up with a variant, which Gary Foshee introduced to Gardner fans in 2010: Child Problem 3. I have two children. At least one of them is a boy born on Tuesday. What is the probability that both children are boys? Problems 2 and 3 are considered paradoxes because they have surprising answers that people argue about. (Assume the probability of a boy is exactly 1/2, and is independent of any siblings.) <center>Martin Gardner</center> Child Problem 1: Older child is a boy. What is the probability both are boys? We use 'BG' to denote the outcome in which the older child is a boy and the younger a girl. The sample space, S, of equi-probable outcomes is: End of explanation """ def two_boys(outcome): return outcome.count('B') == 2 def older_is_a_boy(outcome): return outcome.startswith('B') """ Explanation: Let's define predicates for the conditions of having two boys, and of the older child being a boy: End of explanation """ P(two_boys, such_that(older_is_a_boy, S)) """ Explanation: Now we can answer Problem 1: End of explanation """ def at_least_one_boy(outcome): return 'B' in outcome P(two_boys, such_that(at_least_one_boy, S)) """ Explanation: You're probably thinking that was a lot of mechanism just to get the obvious answer. But in the next problems, what is obvious becomes less obvious. Child Problem 2: At least one is a boy. What is the probability both are boys? Implementing this problem and finding the answer is easy: End of explanation """ such_that(at_least_one_boy, S) """ Explanation: Understanding the answer is tougher. Some people think the answer should be 1/2. Can we justify the answer 1/3? We can see there are three equiprobable outcomes in which there is at least one boy: End of explanation """ S2b = {'BB/b?', 'BB/?b', 'BG/b?', 'BG/?g', 'GB/g?', 'GB/?b', 'GG/g?', 'GG/?g'} """ Explanation: Of those three outcomes, only one has two boys, so the answer of 1/3 is indeed justified. But some people still think the answer should be 1/2. Their reasoning is "If one child is a boy, then there are two equiprobable outcomes for the other child, so the probability that the other child is a boy, and thus that there are two boys, is 1/2." When two methods of reasoning give two different answers, we have a paradox. Here are three responses to a paradox: The very fundamentals of mathematics must be incomplete, and this problem reveals it!!! I'm right, and anyone who disagrees with me is an idiot!!! I have the right answer for one interpretation of the problem, and you have the right answer for a different interpretation of the problem. If you're Bertrand Russell or Georg Cantor, you might very well uncover a fundamental flaw in mathematics; for the rest of us, I recommend Response 3. When I believe the answer is 1/3, and I hear someone say the answer is 1/2, my response is not "You're wrong!", rather it is "How interesting! You must have a different interpretation of the problem; I should try to discover what your interpretation is, and why your answer is correct for your interpretation." The first step is to be more precise in my wording of the experiment: Child Experiment 2a. Mr. Smith is chosen at random from families with two children. He is asked if at least one of his children is a boy. He replies "yes." The next step is to envision another possible interpretation of the experiment: Child Experiment 2b. Mr. Smith is chosen at random from families with two children. He is observed at a time when he is accompanied by one of his children, chosen at random. The child is observed to be a boy. Experiment 2b needs a different sample space, which we will call S2b. It consists of 8 outcomes, not just 4; for each of the 4 outcomes in S, we have a choice of observing either the older child or the younger child. We will use the notation 'GB/g?' to mean that the older child is a girl, the younger a boy, the older child was observed to be a girl, and the younger was not observed. The sample space is therefore: End of explanation """ def observed_boy(outcome): return 'b' in outcome such_that(observed_boy, S2b) """ Explanation: Now we can figure out the subset of this sample space in which we observe Mr. Smith with a boy: End of explanation """ P(two_boys, such_that(observed_boy, S2b)) """ Explanation: And finally we can determine the probability that he has two boys, given that we observed him with a boy: End of explanation """ sexesdays = cross('BG', '1234567') S3 = cross(sexesdays, sexesdays) len(S3) """ Explanation: The paradox is resolved. Two reasonable people can have different interpretations of the problem, and can each reason flawlessly to reach different conclusions, 1/3 or 1/2. Which interpretation of the problem is "better?" We could debate that, or we could just agree to use unambiguous wording (that is, use the language of Experiment 2a or Experiment 2b, not the ambiguous language of Problem 2). The Reasonable Person Principle It is an unfortunate fact of human nature that we often assume the other person is an idiot. As George Carlin puts it "Have you ever noticed when you're driving that anybody driving slower than you is an idiot, and anyone going faster than you is a maniac?" <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Jesus_is_coming.._Look_Busy_%28George_Carlin%29.jpg/192px-Jesus_is_coming.._Look_Busy_%28George_Carlin%29.jpg"> <center>George Carlin</center> The opposite assumption&mdash;that other people are more likely to be reasonable rather than idiots is known as the reasonable person principle. It is a guiding principle at Carnegie Mellon University's School of Computer Science, and is a principle I try to live by as well. Now let's return to an even more paradoxical problem. Child Problem 3. One is a boy born on Tuesday. What's the probability both are boys? Most people can not imagine how the boy's birth-day-of-week could be relevant, and feel the answer should be the same as Problem 2. But to be sure, we need to clearly describe the experiment, define the sample space, and calculate. First: Child Experiment 3a. A parent is chosen at random from families with two children. She is asked if at least one of her children is a boy born on Tuesday. She replies "yes." Next we'll define a sample space. We'll use the notation "G1B3" to mean the older child is a girl born on the first day of the week (Sunday) and the younger a boy born on the third day of the week (Tuesday). We'll call the resulting sample space S3. End of explanation """ import random random.sample(S3, 8) """ Explanation: That's too many to print, but we can sample them: End of explanation """ P(at_least_one_boy, S3) P(at_least_one_boy, S) """ Explanation: We determine below that the probability of having at least one boy is 3/4, both in S3 (where we keep track of the birth day of week) and in S (where we don't): End of explanation """ P(two_boys, S3) P(two_boys, S) """ Explanation: The probability of two boys is 1/4 in either sample space: End of explanation """ P(two_boys, such_that(at_least_one_boy, S3)) P(two_boys, such_that(at_least_one_boy, S)) """ Explanation: And the probability of two boys given at least one boy is 1/3 in either sample space: End of explanation """ def at_least_one_boy_tues(outcome): return 'B3' in outcome """ Explanation: We will define a predicate for the event of at least one boy born on Tuesday: End of explanation """ P(two_boys, such_that(at_least_one_boy_tues, S3)) """ Explanation: We are now ready to answer Problem 3: End of explanation """ def observed_boy_tues(outcome): return 'b3' in outcome S3b = {children + '/' + observation for children in S3 for observation in (children[:2].lower()+'??', '??'+children[-2:].lower())} random.sample(S3b, 5) """ Explanation: 13/27? How many saw that coming? 13/27 is quite different from 1/3, but rather close to 1/2. So "at least one boy born on Tuesday" is quite different from "at least one boy." Are you surprised? Do you accept the answer, or do you think we did something wrong? Are there other interpretations of the experiment that lead to other answers? Here is one alternative interpretation: Child Experiment 3b. A parent is chosen at random from families with two children. She is observed at a time when she is accompanied by one of her children, chosen at random. The child is observed to be a boy who reports that his birth day is Tuesday. We can represent outcomes in this sample space with the notation G1B3/??b3, meaning the older child is a girl born on Sunday, the younger a boy born on Tuesday, the older was not observed, and the younger was. End of explanation """ P(two_boys, such_that(observed_boy_tues, S3b)) """ Explanation: Now we can answer this version of Child Problem 3: End of explanation """ from IPython.display import HTML def Pgrid(space, n, event, condition): """Display sample space in a grid, color-coded: green if event and condition is true; yellow if only condition is true; white otherwise.""" # n is the number of characters that make up the older child. olders = sorted(set(outcome[:n] for outcome in space)) return HTML('<table>' + cat(row(older, space, event, condition) for older in olders) + '</table>' + '<tt>P({} | {}) = {}</tt>'.format( event.__name__, condition.__name__, P(event, such_that(condition, space)))) def row(older, space, event, condition): "Display a row where an older child is paired with each of the possible younger children." thisrow = sorted(outcome for outcome in space if outcome.startswith(older)) return '<tr>' + cat(cell(outcome, event, condition) for outcome in thisrow) + '</tr>' def cell(outcome, event, condition): "Display outcome in appropriate color." color = ('lightgreen' if event(outcome) and condition(outcome) else 'yellow' if condition(outcome) else 'white') return '<td style="background-color: {}">{}</td>'.format(color, outcome) cat = ''.join """ Explanation: So with the wording of Child Experiment 3b, the answer is the same as 2b. Still confused? Let's build a visualization tool to make things more concrete. Visualization We'll display the results as a two dimensional grid of outcomes. An outcome will be colored white if it does not satisfy the condition stated in the problem; green if the outcome contains two boys; and yellow if it does satisfy the condition, but does not have two boys. Every cell in a row has the same older child, and every cell in a column has the same younger child. Here's the code to display a table: End of explanation """ # Child Problem 1 Pgrid(S, 1, two_boys, older_is_a_boy) """ Explanation: We can use this visualization tool to see that in Child Problem 1, there is one outcome with two boys (green) out of a total of two outcomes where the older is a boy (green and yellow) so the probability of two boys given that the older is a boy is 1/2. End of explanation """ # Child Problem 2 Pgrid(S, 1, two_boys, at_least_one_boy) """ Explanation: For Child Problem 2, we see the probability of two boys (green) given at least one boy (green and yellow) is 1/3. End of explanation """ # Child Problem 2, with days of week enumerated Pgrid(S3, 2, two_boys, at_least_one_boy) """ Explanation: The answer is still 1/3 when we consider the day of the week of each birth. End of explanation """ # Child Problem 3 Pgrid(S3, 2, two_boys, at_least_one_boy_tues) """ Explanation: Now for the paradox of Child Problem 3: End of explanation """ B = {'heads/Monday/interviewed', 'heads/Tuesday/sleep', 'tails/Monday/interviewed', 'tails/Tuesday/interviewed'} """ Explanation: We see there are 27 relevant outcomes, of which 13 are green. So 13/27 really does seem to be the right answer. This picture also gives us a way to think about why the answer is not 1/3. Think of the yellow-plus-green area as a horizontal stripe and a vertical stripe, with an overlap. Each stripe is half yellow and half green, so if there were no overlap at all, the probability of green would be 1/2. When each stripe takes up half the sample space and the overlap is maximal, the probability is 1/3. And in the Problem 3 table, where the overlap is small, the probability is close to 1/2 (but slightly smaller). One way to look at it is that if I tell you very specific information (such as a boy born on Tuesday), it is unlikely that this applies to both children, so we have smaller overlap and a probability closer to 1/2, but if I give you broad information (a boy), this is more likely to apply to either child, resulting in a larger overlap, and a probability closer to 1/3. You can read some more discussions of the problem by (in alphabetical order) Alex Bellos, Alexander Bogomolny, Andrew Gelman, David Bigelow, Julie Rehmeyer, Keith Devlin, Peter Lynch, Tanya Khovanova, and Wendy Taylor &amp; Kaye Stacey. The Sleeping Beauty Paradox The Sleeping Beauty Paradox is another tricky one: Sleeping Beauty volunteers to undergo the following experiment and is told all of the following details: On Sunday she will be put to sleep. Then a fair coin will be tossed, to determine which experimental procedure to undertake: - Heads: Beauty will be awakened and interviewed on Monday only. - Tails: Beauty will be awakened and interviewed on Monday and Tuesday only. In all cases she is put back to sleep with an amnesia-inducing drug that makes her forget that awakening and sleep until the next one. In any case, she will be awakened on Wednesday without interview and the experiment ends. Any time Beauty is awakened and interviewed, she is asked, "What is your belief now for the proposition that the coin landed heads?" What should Sleeping Beauty say when she is interviewed? First, she should define the sample space. She could use the notation 'heads/Monday/interviewed' to mean the outcome where the coin flip was heads, it is Monday, and she is interviewed. So there are 4 equiprobable outcomes: End of explanation """ def T(property): "Return a predicate that is true of all outcomes that have 'property' as a substring." return lambda outcome: property in outcome """ Explanation: At this point, you're probably expecting me to define predicates, like this: def heads(outcome): return 'heads' in outcome def interviewed(outcome): return 'interviewed' in outcome We've seen a lot of predicates like this. I think it is time to heed the "don't repeat yourself" principle, so I will define a predicate-defining function, T. Think of "T" for "it is true that": End of explanation """ heads = T("heads") interviewed = T("interviewed") P(heads, such_that(interviewed, B)) """ Explanation: Now we can get the answer: End of explanation """ P(heads, B) """ Explanation: Note: I could have done that in one line: P(T("heads"), such_that(T("interviewed"), B)) This problem is considered a paradox because there are people who argue that the answer should be 1/2, not 1/3. I admit I'm having difficulty coming up with a sample space that supports the "halfer" position. I do know of a question that has the answer 1/2: End of explanation """ M = {'Car1/Lo/Pick1/Open2', 'Car1/Hi/Pick1/Open3', 'Car2/Lo/Pick1/Open3', 'Car2/Hi/Pick1/Open3', 'Car3/Lo/Pick1/Open2', 'Car3/Hi/Pick1/Open2'} """ Explanation: But that seems like the wrong question; we want the probability of heads given that Sleeping Beauty was interviewed, not the unconditional probability of heads. The "halfers" argue that before Sleeping Beauty goes to sleep, her unconditional probability for heads should be 1/2. When she is interviewed, she doesn't know anything more than before she went to sleep, so nothing has changed, so the probability of heads should still be 1/2. I find two flaws with this argument. First, if you want to convince me, show me a sample space; don't just make philosophical arguments. (Although a philosophical argument can be employed to help you define the right sample space.) Second, while I agree that before she goes to sleep, Beauty's unconditional probability for heads should be 1/2, I would say that both before she goes to sleep and when she is awakened, her conditional probability of heads given that she is being interviewed should be 1/3, as shown by the sample space. The Monty Hall Paradox This is one of the most famous probability paradoxes. It can be stated as follows: Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to switch your choice to door No. 2?" Is it to your advantage to switch your choice? <img src="http://retrothing.typepad.com/.a/6a00d83452989a69e20120a4cb10a2970b-800wi"> <center>Monty Hall</center> Much has been written about this problem, but to solve it all we have to do is be careful about how we understand the problem, and about defining our sample space. I will define outcomes of the form 'Car1/Lo/Pick1/Open2', which means: * Car1: The producers of the show randomly placed the car behind door 1. * Lo: The host randomly commits to the strategy of opening the lowest-numbered allowable door. A door is allowable if it does not contain the car and was not picked by the contestant. Alternatively, the host could have chosen to open the highest-numbered allowable door (Hi). * Pick1: The contestant picks door 1. Our sample space will only consider cases where the contestant picks door 1, but by symmetry, the same arguments could be used if the contestant picked door 2 or 3. * Open2: After hearing the contestant's choice, and following the strategy, the host opens a door; in this case door 2. We can see that the sample space has 6 equiprobable outcomes involving Pick1: End of explanation """ such_that(T("Open3"), M) P(T("Car1"), such_that(T("Open3"), M)) P(T("Car2"), such_that(T("Open3"), M)) """ Explanation: Now, assuming the contestant picks door 1 and the host opens door 3, we can ask: - What are the possible outcomes remaining? - What is the probability that the car is behind door 1? - Or door 2? End of explanation """ M2 = {'Car1/Pick1/Open2/Goat', 'Car1/Pick1/Open3/Goat', 'Car2/Pick1/Open2/Car', 'Car2/Pick1/Open3/Goat', 'Car3/Pick1/Open2/Goat', 'Car3/Pick1/Open3/Car'} """ Explanation: We see that the strategy of switching from door 1 to door 2 will win the car 2/3 of the time, whereas the strategy of sticking with the original pick wins the car only 1/3 of the time. So if you like cars more than goats, you should switch. But don't feel bad if you got this one wrong; it turns out that Monty Hall himself, who opened many doors while hosting Let's Make a Deal for 13 years, didn't know the answer either, as revealed in this letter from Monty to Prof. Lawrence Denenberg, when Denenberg asked for permission to use the problem in his textbook: <img src="http://norvig.com/monty-hall-letter.jpg"> If you were Denenberg, how would you answer Monty, in non-mathematical terms? I would try something like this: When the contestant makes her initial pick, she has 1/3 chance of picking the car, and there is a 2/3 chance the car is behind one of the other doors. That's still true after you open a door, but now the 2/3 chance for either other door becomes concentrated as 2/3 behind one other door, so the contestant should switch. But that type of argument was not persuasive to everyone. Marilyn vos Savant reports that many of her readers (including, she is pleased to point out, many Ph.D.s) still insist the answer is that it doesn't matter if the contestant switches; the odds are 1/2 either way. Let's try to discover what problem and what sample space those people are dealing with. Perhaps they are reasoning like this: They define outcomes of the form 'Car1/Pick1/Open2/Goat', which means: * Car1: First the car is randomly placed behind door 1. * Pick1: The contestant picks door 1. * Open2: The host opens one of the two other doors at random (so the host might open the door with the car). * Goat: We observe there is a goat behind the opened door. Under this interpretation, the sample space of all outcomes involving Pick1 is: End of explanation """ P(T("Car1"), such_that(T("Open3/Goat"), M2)) P(T("Car2"), such_that(T("Open3/Goat"), M2)) P(T("Car3"), such_that(T("Open3/Goat"), M2)) """ Explanation: And we can calculate the probability of the car being behind each door, given that the contestant picks door 1 and the host opens door 3 to reveal a goat: End of explanation """ import random def monty(strategy): """Simulate this sequence of events: 1. The host randomly chooses a door for the 'car' 2. The contestant randomly makes a 'pick' of one of the doors 3. The host randomly selects a non-car, non-pick door to be 'opened.' 4. If strategy == 'switch', contestant changes 'pick' to the other unopened door 5. Return true if the pick is the door with the car.""" doors = (1, 2, 3) car = random.choice(doors) pick = random.choice(doors) opened = random.choice([d for d in doors if d != car and d != pick]) if strategy == 'switch': pick = next(d for d in doors if d != pick and d != opened) return (pick == car) """ Explanation: So we see that under this interpretation it doesn't matter if you switch or not. Is this a valid interpretation? I agree that the wording of the problem can be seen as being ambiguous. However, this interpretation has a serious problem: in all the history of Let's Make a Deal, it was never the case that the host opened up a door with the grand prize. This strongly suggests (but does not prove) that M is the correct sample space, not M2 Simulating the Monty Hall Problem Some people might be more convinced by a simulation than by a probability argument. Here is code for a simulation: End of explanation """ from collections import Counter Counter(monty('switch') for _ in range(10 ** 5)) Counter(monty('stick') for _ in range(10 ** 5)) """ Explanation: We can confirm that the contestant wins about 2/3 of the time with the switch strategy, and only wins about 1/3 of the time with the stick strategy: End of explanation """ DK = ProbDist(GG=121801, GB=126840, BG=127123, BB=135138) DK """ Explanation: Reasoning with Probability Distributions So far, we have made the assumption that every outcome in a sample space is equally likely. In real life, the probability of a child being a girl is not exactly 1/2. As mentioned in the previous notebook, an article gives the following counts for two-child families in Denmark: GG: 121801 GB: 126840 BG: 127123 BB: 135138 Let's implement that: End of explanation """ # Child Problem 1 in DK P(two_boys, such_that(older_is_a_boy, DK)) # Child Problem 2 in DK P(two_boys, such_that(at_least_one_boy, DK)) """ Explanation: Now let's try the first two Child Problems with the probability distribution DK. Since boys are slightly more probable than girls, we expect a little over 1/2 for Problem 1, and a little over 1/3 for problem 2: End of explanation """ sexes = ProbDist(B=51.5, G=48.5) # Probability distribution over sexes days = ProbDist(L=1, N=4*365) # Probability distribution over Leap days and Non-leap days child = joint(sexes, days) # Probability distribution for one child family S4 = joint(child, child) # Probability distribution for two-child family """ Explanation: It all looks good. Now let's leave Denmark behind and try a new problem: Child Problem 4. One is a boy born on Feb. 29. What is the probability both are boys? Child Problem 4. I have two children. At least one of them is a boy born on leap day, February 29. What is the probability that both children are boys? Assume that 51.5% of births are boys and that birth days are distributed evenly across the 4&times;365 + 1 days in a 4-year cycle. We will use the notation GLBN to mean an older girl born on leap day (L) and a younger boy born on a non-leap day (N). End of explanation """ child S4 """ Explanation: Let's check out these last two probability distributions: End of explanation """ # Child Problem 4 boy_born_on_leap_day = T("BL") P(two_boys, such_that(boy_born_on_leap_day, S4)) """ Explanation: Now we can solve the problem. Since "boy born on a leap day" applies to so few children, we expect the probability of two boys to be just ever so slightly below the baseline rate for boys, 51.5%. End of explanation """ def st_pete(limit): "Return the probability distribution for the St. Petersburg Paradox with a limited bank." P = {} # The probability distribution pot = 2 # Amount of money in the pot pr = 1/2. # Probability that you end up with the amount in pot while pot < limit: P[pot] = pr pot = pot * 2 pr = pr / 2 P[limit] = pr * 2 # pr * 2 because you get limit for heads or tails return ProbDist(P) """ Explanation: The St. Petersburg Paradox The St. Petersburg paradox from 1713, named for the home town of the Bernoullis, and introduced by Daniel Bernoulli, the nephew of Jacob Bernoulli (the urn guy): A casino offers a game of chance for a single player in which a fair coin is tossed at each stage. The pot starts at 2 dollars and is doubled every time a head appears. The first time a tail appears, the game ends and the player wins whatever is in the pot. Thus the player wins 2 dollars if a tail appears on the first toss, 4 dollars if a head appears on the first toss and a tail on the second, etc. What is the expected value of this game to the player? To calculate the expected value, we see there is a 1/2 chance of a tail on the first toss (yielding a pot of \$2) and if not that, a 1/2 &times; 1/2 = 1/4 chance of a tail on the second toss (yielding a pot of \$4), and so on. So in total, the expected value is: $$\frac{1}{2}\cdot 2 + \frac{1}{4}\cdot 4 + \frac{1}{8}\cdot 8 + \frac{1}{16} \cdot 16 + \cdots = 1 + 1 + 1 + 1 + \cdots = \infty$$ The expected value is infinite! But anyone playing the game would not expect to win an infinite amount; thus the paradox. Response 1: Limited Resources The first major response to the paradox is that the casino's resources are limited. Once you break their bank, they can't pay out any more, and thus the expected return is finite. Let's consider the case where the bank has a limit to their resources, and create a probability distribution for the problem. We keep doubling the pot and halving the probability of winning the amount in the pot (half because you get the pot on a tail but not a head), until we reach the limit. End of explanation """ StP = st_pete(limit=10**8) StP """ Explanation: Let's try with the casino limited to 100 million dollars: End of explanation """ def EV(P): "The expected value of a probability distribution." return sum(P[v] * v for v in P) EV(StP) """ Explanation: Now we define the function EV to compute the expected value of a probability distribution: End of explanation """ def util(dollars, enough=1000): "The value of money: only half as valuable after you already have enough." if dollars < enough: return dollars else: additional = dollars-enough return enough + util(additional / 2, enough * 2) """ Explanation: This says that for a casino with a bankroll of 100 million dollars, if you want to maximize your expected value, you should be willing to pay up to \$27.49 to play the game. Would you pay that much? I wouldn't, and neither would Daniel Bernoulli. Response 2: Value of Money Daniel Bernoulli came up with a second response to the paradox based on the idea that if you have a lot of money, then additional money becomes less valuable to you. If I had nothing, and I won \$1000, I would be very happy. But if I already had a million dollars and I won \$1000, it would be less valuable. How much less valuable? Bernoulli proposed, and experiments confirm, that the value of money is roughly logarithmic. That is, rational bettors don't try to maximize their expected monetary value, they try to maximize their expected utility: the amount of "happiness" that the money is worth. I'll write the function util to describe what a dollar amount is worth to a hypothetical gambler. util says that a dollar is worth a dollar, until the amount is "enough" money. After that point, each additional dollar is worth half as much (only brings half as much happiness). Value keeps accumulating at this rate until we reach the next threshold of "enough," when the utility of additional dollars is halfed again. The exact details of util are not critical; what matters is that overall money becomes less valuable after we have won a lot of it. End of explanation """ for d in range(2, 10): m = 10 ** d print('{:15,d} $ = {:10,d} util'.format(m, int(util(m)))) %matplotlib inline import matplotlib.pyplot as plt plt.plot([util(x) for x in range(1000, 10000000, 1000)]) print('Y axis is util(x); x axis is in thousands of dollars.') """ Explanation: A table and a plot will give a feel for the util function. Notice the characterisitc concave-down shape of the plot. End of explanation """ def EU(P, U): "The expected utility of a probability distribution, given a utility function." return sum(P[e] * U(e) for e in P) EU(StP, util) """ Explanation: Now I will define the function EU, which computes the expected utility of the game: End of explanation """ def flip(): return random.choice(('head', 'tail')) def simulate_st_pete(limit=10**9): "Simulate one round of the St. Petersburg game, and return the payoff." pot = 2 while flip() == 'head': pot = pot * 2 if pot > limit: return limit return pot """ Explanation: That says we should pay up to \$13.10 to play the game, which sounds more reasonable than \$27.49. Understanding St. Petersburg through Simulation Before I plunk down my \$13, I'd like to understand the game better. I'll write a simulation of the game: End of explanation """ random.seed(123456) results = ProbDist(Counter(simulate_st_pete() for _ in range(100000))) results """ Explanation: I will run the simulation 100,000 times (with a random seed specified for reproducability) and make the results into a probability distribution: End of explanation """ EU(results, util), EV(results) """ Explanation: The results are about what you would expect: about half the pots are 2, a quarter are 4, an eighth are 8, and higher pots are more and more unlikely. Let's check expected utility and expected value: End of explanation """ def running_averages(iterable): "For each element in the iterable, yield the mean of all elements seen so far." total, n = 0, 0 for x in iterable: total, n = total + x, n + 1 yield total / n def plot_running_averages(fn, n): "Plot the running average of calling the function n times." plt.plot(list(running_averages(fn() for _ in range(n)))) """ Explanation: These are not too far off from the theoretial values. To see better how things unfold, I will define a function to plot the running average of repeated rounds: End of explanation """ random.seed('running') for i in range(10): plot_running_averages(simulate_st_pete, 100000); """ Explanation: Let's do ten repetitions of plotting the running averages of 100,000 rounds: End of explanation """ def ellsburg(): show('R', 'r') show('B', 'k') show('RY', 'r--') show('BY', 'k--') plt.xlabel('Number of black balls') plt.ylabel('Expected value of each gamble') blacks = list(range(68)) urns = [Counter(R=33, B=b, Y=67-b) for b in blacks] def show(colors, line): scores = [score(colors, urn) for urn in urns] plt.plot(blacks, scores, line) def score(colors, urn): return sum(urn[c] for c in colors) ellsburg() """ Explanation: What can we see from this? Nine of the 10 repetitions have a final expected value payoff (after 100,000 rounds) between 10 and 35. So a price around \$13 still seems reasonable. One outlier has an average payoff just over 100, so if you are feeling lucky you might be willing to pay more than \$13. The Ellsburg Paradox The Ellsburg Paradox has it all: an urn problem; a paradox; a conclusion that can only be resolved through psychology, not mathematics alone; and a colorful history with an inventor, Daniel Ellsburg, who went on to become the releaser of the Pentagon Papers. The paradox is as follows: An urn contains 33 red balls and 66 other balls that are either black or yellow. You don't know the mix of black and yellow, just that they total 66. A single ball is drawn at random. You are given a choice between these two gambles: - R: Win \$100 for a red ball. - B: Win \$100 for a black ball. You are also given a choice between these two gambles: - RY: Win \$100 for a red or yellow ball. - BY: Win \$100 for a black or yellow ball. Many people reason as follows: - R: I win 1/3 of the time - B: I win somewhere between 0 and 2/3 of the time, but I'm not sure of the probability. - RY: I win at least 1/3 of the time and maybe up to 100% of the time; I'm not sure. - BY: I win 2/3 of the time. - Overall, I prefer the relative certainty of R over B and of BY over RY. The paradox is that, from an expected utility point of view, that reasoning is inconsistent, no matter what the mix of black and yellow balls is (or no matter what you believe the mix might be). RY and BY are just the same gambles as R and B, but with an additional \$100 for a yellow ball. So if you prefer R over B, you should prefer RY over BY (and if you prefer B over R you should prefer BY over RY), for any possible mix of black and yellow balls. Let's demonstrate. For each possible number of black balls (on the x axis), we'll plot the expected value of each of the four gambles; R as a solid red line, B as a solid black line, RY as a dashed red line, and BY as a dashed black line: End of explanation """ def avgscore(colors, urns): return sum(score(colors, urn) for urn in urns) / len(urns) def compare(urns): for colors in ('R', 'B', 'RY', 'BY'): print(colors.ljust(2), avgscore(colors, urns)) compare(urns) """ Explanation: We see that for any number of black balls up to 33, the solid red line is above the solid black line, which means R is better than B. The two gambles are equal with 33 black balls, and from there on, B is better than R. Similarly, up to 33 black balls, the dashed red line is above the dashed black line, so RY is better than BY. They are equal at 33, and after that, BY is better than RY. So in summary, R > B if and only if RY > BY. It is pretty clear that this hold for every possible mix of black and yellow balls, taken one at a time. But what if you believe that the mix might be one of several possibilities? We'll define avgscore to give the score for a gamble (as specified by the colors in it), averaged over a collection of possible urns, each with a different black/yellow mix. Then we'll define compare to compare the four gambles on the collection of possible urns: End of explanation """ compare(urns[:33] + 2 * urns[33:]) """ Explanation: The above says that if you think any number of black balls is possible and they are all equally equally likely, then you should slightly prefer B > R and BY > RY. Now imagine that for some reason you believe that any mix is possible, but that a majority of black balls is more likely (i.e. the urns in the second half of the list of urns are twice as likely as those in the first half). Then we will see that the same preferences hold, but more strongly: End of explanation """ compare(2 * urns[:33] + urns[33:]) """ Explanation: If we believe the first half of the list (with fewer black balls) is twice as likely, we get this: End of explanation """ def ellsburg2(): show2('R', 'r') show2('B', 'k') show2('RY', 'r--') show2('BY', 'k--') plt.xlabel('Different combinations of two urns') plt.ylabel('Expected value of each gamble') def show2(colors, line): urnpairs = [(u1, u2) for u1 in urns for u2 in urns] urnpairs.sort(key=lambda urns: avgscore('B', urns)) X = list(range(len(urnpairs))) plt.plot(X, [avgscore(colors, urns) for urns in urnpairs], line) ellsburg2() """ Explanation: This time the preferences are reversed for both gambles, R > B and RY > BY. Now let's try another approach. Imagine there are two urns, each as described before, and the ball will be drawn from one or the other. We will plot the expected value of each of the four gambles, over all possible pairs of two different urns (sorted by the number of black balls in the pair): End of explanation """ # Good and bad outcomes for kidney stone reatments A and B, # each in two cases: [small_stones, large_stones] A = [Counter(good=81, bad=6), Counter(good=192, bad=71)] B = [Counter(good=234, bad=36), Counter(good=55, bad=25)] def success(case): return ProbDist(case)['good'] """ Explanation: The curves are different, but the results are the same: R > B if and only if RY > BY. So why do many people prefer R > B and BY > RY. One explanation is risk aversion; it feels safer to take a definite 1/3 chance of winning, rather than a gamble that might be as good as 2/3, but might be as bad as 0. This is irrational thinking (in the sense that those who follow this strategy will win less), but people are sometimes irrational. Simpson's Paradox This has nothing to do with the TV show. D'oh! In 1951, statistician Edward Simpson (who worked with Alan Turing at Bletchley Park during World War II), noted that it is possible to take a sample space in which A is better than B, and split it into two groups, such that B is better than A in both groups. For example, here is data from trials of two treatments for kidney stones, A and B, separated into two subgroups or cases: first, for small kidney stones, and second for large ones. In all cases we record the number of good and bad outcomes of the treatment: End of explanation """ [success(case) for case in A] [success(case) for case in B] """ Explanation: Let's compare probabilities of success: End of explanation """ success(A[0] + A[1]) success(B[0] + B[1]) """ Explanation: We see that for small stones, A is better, 93% to 87%, and for large stones, A is also better, 75% to 69%. So A is better no matter what, right? Not so fast. We can add up Counters to get the overall success rate for A and B, over all cases: End of explanation """ Jeter = [Counter(hit=12, out=36), Counter(hit=183, out=399)] Justice = [Counter(hit=104, out=307), Counter(hit=45, out=95)] def BA(case): "Batting average"; return ProbDist(case)['hit'] [BA(year) for year in Jeter] [BA(year) for year in Justice] """ Explanation: Overall, B is more successful, 83% to 78%, even though A is better in both cases. So if you had kidney stones, and you want the highest chance of success, which treatment would you prefer? If you knew you had small stones (or large stones), the evidence supports A. But if the size was unknown, does that mean you should prefer B? Analysts agree that the answer is no, you should stick with A. The only reason why B has a higher overall success rate is that doctors choose to do B more often on the easier, small stone cases, and reserve A for the harder, large stone cases. B is better, but it has a lower overall percentage because it is given the difficult patients. Here's another example, showing the batting averages for two baseball players, Derek jeter and David Justice, for the years 1995 and 1996: End of explanation """ BA(Jeter[0] + Jeter[1]) BA(Justice[0] + Justice[1]) """ Explanation: So Justice had a higher batting average than Jeter for both 1995 and 1996. Let's check overall: End of explanation """
CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
Chapter2_MorePyMC/Ch2_MorePyMC_PyMC2.ipynb
mit
import pymc as pm parameter = pm.Exponential("poisson_param", 1) data_generator = pm.Poisson("data_generator", parameter) data_plus_one = data_generator + 1 """ Explanation: Chapter 2 This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian perspective. It also contains tips and data visualization techniques for assessing goodness-of-fit for your Bayesian model. A little more on PyMC Parent and Child relationships To assist with describing Bayesian relationships, and to be consistent with PyMC's documentation, we introduce parent and child variables. parent variables are variables that influence another variable. child variable are variables that are affected by other variables, i.e. are the subject of parent variables. A variable can be both a parent and child. For example, consider the PyMC code below. End of explanation """ print("Children of `parameter`: ") print(parameter.children) print("\nParents of `data_generator`: ") print(data_generator.parents) print("\nChildren of `data_generator`: ") print(data_generator.children) """ Explanation: parameter controls the parameter of data_generator, hence influences its values. The former is a parent of the latter. By symmetry, data_generator is a child of parameter. Likewise, data_generator is a parent to the variable data_plus_one (hence making data_generator both a parent and child variable). Although it does not look like one, data_plus_one should be treated as a PyMC variable as it is a function of another PyMC variable, hence is a child variable to data_generator. This nomenclature is introduced to help us describe relationships in PyMC modeling. You can access a variable's children and parent variables using the children and parents attributes attached to variables. End of explanation """ print("parameter.value =", parameter.value) print("data_generator.value =", data_generator.value) print("data_plus_one.value =", data_plus_one.value) """ Explanation: Of course a child can have more than one parent, and a parent can have many children. PyMC Variables All PyMC variables also expose a value attribute. This method produces the current (possibly random) internal value of the variable. If the variable is a child variable, its value changes given the variable's parents' values. Using the same variables from before: End of explanation """ lambda_1 = pm.Exponential("lambda_1", 1) # prior on first behaviour lambda_2 = pm.Exponential("lambda_2", 1) # prior on second behaviour tau = pm.DiscreteUniform("tau", lower=0, upper=10) # prior on behaviour change print("lambda_1.value = %.3f" % lambda_1.value) print("lambda_2.value = %.3f" % lambda_2.value) print("tau.value = %.3f" % tau.value, "\n") lambda_1.random(), lambda_2.random(), tau.random() print("After calling random() on the variables...") print("lambda_1.value = %.3f" % lambda_1.value) print("lambda_2.value = %.3f" % lambda_2.value) print("tau.value = %.3f" % tau.value) """ Explanation: PyMC is concerned with two types of programming variables: stochastic and deterministic. stochastic variables are variables that are not deterministic, i.e., even if you knew all the values of the variables' parents (if it even has any parents), it would still be random. Included in this category are instances of classes Poisson, DiscreteUniform, and Exponential. deterministic variables are variables that are not random if the variables' parents were known. This might be confusing at first: a quick mental check is if I knew all of variable foo's parent variables, I could determine what foo's value is. We will detail each below. Initializing Stochastic variables Initializing a stochastic variable requires a name argument, plus additional parameters that are class specific. For example: some_variable = pm.DiscreteUniform("discrete_uni_var", 0, 4) where 0, 4 are the DiscreteUniform-specific lower and upper bound on the random variable. The PyMC docs contain the specific parameters for stochastic variables. (Or use object??, for example pm.DiscreteUniform?? if you are using IPython!) The name attribute is used to retrieve the posterior distribution later in the analysis, so it is best to use a descriptive name. Typically, I use the Python variable's name as the name. For multivariable problems, rather than creating a Python array of stochastic variables, addressing the size keyword in the call to a Stochastic variable creates multivariate array of (independent) stochastic variables. The array behaves like a Numpy array when used like one, and references to its value attribute return Numpy arrays. The size argument also solves the annoying case where you may have many variables $\beta_i, \; i = 1,...,N$ you wish to model. Instead of creating arbitrary names and variables for each one, like: beta_1 = pm.Uniform("beta_1", 0, 1) beta_2 = pm.Uniform("beta_2", 0, 1) ... we can instead wrap them into a single variable: betas = pm.Uniform("betas", 0, 1, size=N) Calling random() We can also call on a stochastic variable's random() method, which (given the parent values) will generate a new, random value. Below we demonstrate this using the texting example from the previous chapter. End of explanation """ type(lambda_1 + lambda_2) """ Explanation: The call to random stores a new value into the variable's value attribute. In fact, this new value is stored in the computer's cache for faster recall and efficiency. Warning: Don't update stochastic variables' values in-place. Straight from the PyMC docs, we quote [4]: Stochastic objects' values should not be updated in-place. This confuses PyMC's caching scheme... The only way a stochastic variable's value should be updated is using statements of the following form: A.value = new_value The following are in-place updates and should never be used: A.value += 3 A.value[2,1] = 5 A.value.attribute = new_attribute_value Deterministic variables Since most variables you will be modeling are stochastic, we distinguish deterministic variables with a pymc.deterministic wrapper. (If you are unfamiliar with Python wrappers (also called decorators), that's no problem. Just prepend the pymc.deterministic decorator before the variable declaration and you're good to go. No need to know more. ) The declaration of a deterministic variable uses a Python function: @pm.deterministic def some_deterministic_var(v1=v1,): #jelly goes here. For all purposes, we can treat the object some_deterministic_var as a variable and not a Python function. Prepending with the wrapper is the easiest way, but not the only way, to create deterministic variables: elementary operations, like addition, exponentials etc. implicitly create deterministic variables. For example, the following returns a deterministic variable: End of explanation """ import numpy as np n_data_points = 5 # in CH1 we had ~70 data points @pm.deterministic def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2): out = np.zeros(n_data_points) out[:tau] = lambda_1 # lambda before tau is lambda1 out[tau:] = lambda_2 # lambda after tau is lambda2 return out """ Explanation: The use of the deterministic wrapper was seen in the previous chapter's text-message example. Recall the model for $\lambda$ looked like: $$ \lambda = \begin{cases} \lambda_1 & \text{if } t \lt \tau \cr \lambda_2 & \text{if } t \ge \tau \end{cases} $$ And in PyMC code: End of explanation """ %matplotlib inline from IPython.core.pylabtools import figsize from matplotlib import pyplot as plt figsize(12.5, 4) samples = [lambda_1.random() for i in range(20000)] plt.hist(samples, bins=70, density=True, histtype="stepfilled") plt.title("Prior distribution for $\lambda_1$") plt.xlim(0, 8); """ Explanation: Clearly, if $\tau, \lambda_1$ and $\lambda_2$ are known, then $\lambda$ is known completely, hence it is a deterministic variable. Inside the deterministic decorator, the Stochastic variables passed in behave like scalars or Numpy arrays (if multivariable), and not like Stochastic variables. For example, running the following: @pm.deterministic def some_deterministic(stoch=some_stochastic_var): return stoch.value**2 will return an AttributeError detailing that stoch does not have a value attribute. It simply needs to be stoch**2. During the learning phase, it's the variable's value that is repeatedly passed in, not the actual variable. Notice in the creation of the deterministic function we added defaults to each variable used in the function. This is a necessary step, and all variables must have default values. Including observations in the Model At this point, it may not look like it, but we have fully specified our priors. For example, we can ask and answer questions like "What does my prior distribution of $\lambda_1$ look like?" End of explanation """ data = np.array([10, 5]) fixed_variable = pm.Poisson("fxd", 1, value=data, observed=True) print("value: ", fixed_variable.value) print("calling .random()") fixed_variable.random() print("value: ", fixed_variable.value) """ Explanation: To frame this in the notation of the first chapter, though this is a slight abuse of notation, we have specified $P(A)$. Our next goal is to include data/evidence/observations $X$ into our model. PyMC stochastic variables have a keyword argument observed which accepts a boolean (False by default). The keyword observed has a very simple role: fix the variable's current value, i.e. make value immutable. We have to specify an initial value in the variable's creation, equal to the observations we wish to include, typically an array (and it should be an Numpy array for speed). For example: End of explanation """ # We're using some fake data here data = np.array([10, 25, 15, 20, 35]) obs = pm.Poisson("obs", lambda_, value=data, observed=True) print(obs.value) """ Explanation: This is how we include data into our models: initializing a stochastic variable to have a fixed value. To complete our text message example, we fix the PyMC variable observations to the observed dataset. End of explanation """ model = pm.Model([obs, lambda_, lambda_1, lambda_2, tau]) """ Explanation: Finally... We wrap all the created variables into a pm.Model class. With this Model class, we can analyze the variables as a single unit. This is an optional step, as the fitting algorithms can be sent an array of the variables rather than a Model class. I may or may not use this class in future examples ;) End of explanation """ tau = pm.rdiscrete_uniform(0, 80) print(tau) """ Explanation: Modeling approaches A good starting point in Bayesian modeling is to think about how your data might have been generated. Put yourself in an omniscient position, and try to imagine how you would recreate the dataset. In the last chapter we investigated text message data. We begin by asking how our observations may have been generated: We started by thinking "what is the best random variable to describe this count data?" A Poisson random variable is a good candidate because it can represent count data. So we model the number of sms's received as sampled from a Poisson distribution. Next, we think, "Ok, assuming sms's are Poisson-distributed, what do I need for the Poisson distribution?" Well, the Poisson distribution has a parameter $\lambda$. Do we know $\lambda$? No. In fact, we have a suspicion that there are two $\lambda$ values, one for the earlier behaviour and one for the later behaviour. We don't know when the behaviour switches though, but call the switchpoint $\tau$. What is a good distribution for the two $\lambda$s? The exponential is good, as it assigns probabilities to positive real numbers. Well the exponential distribution has a parameter too, call it $\alpha$. Do we know what the parameter $\alpha$ might be? No. At this point, we could continue and assign a distribution to $\alpha$, but it's better to stop once we reach a set level of ignorance: whereas we have a prior belief about $\lambda$, ("it probably changes over time", "it's likely between 10 and 30", etc.), we don't really have any strong beliefs about $\alpha$. So it's best to stop here. What is a good value for $\alpha$ then? We think that the $\lambda$s are between 10-30, so if we set $\alpha$ really low (which corresponds to larger probability on high values) we are not reflecting our prior well. Similar, a too-high alpha misses our prior belief as well. A good idea for $\alpha$ as to reflect our belief is to set the value so that the mean of $\lambda$, given $\alpha$, is equal to our observed mean. This was shown in the last chapter. We have no expert opinion of when $\tau$ might have occurred. So we will suppose $\tau$ is from a discrete uniform distribution over the entire timespan. Below we give a graphical visualization of this, where arrows denote parent-child relationships. (provided by the Daft Python library ) <img src="http://i.imgur.com/7J30oCG.png" width = 700/> PyMC, and other probabilistic programming languages, have been designed to tell these data-generation stories. More generally, B. Cronin writes [5]: Probabilistic programming will unlock narrative explanations of data, one of the holy grails of business analytics and the unsung hero of scientific persuasion. People think in terms of stories - thus the unreasonable power of the anecdote to drive decision-making, well-founded or not. But existing analytics largely fails to provide this kind of story; instead, numbers seemingly appear out of thin air, with little of the causal context that humans prefer when weighing their options. Same story; different ending. Interestingly, we can create new datasets by retelling the story. For example, if we reverse the above steps, we can simulate a possible realization of the dataset. 1. Specify when the user's behaviour switches by sampling from $\text{DiscreteUniform}(0, 80)$: End of explanation """ alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print(lambda_1, lambda_2) """ Explanation: 2. Draw $\lambda_1$ and $\lambda_2$ from an $\text{Exp}(\alpha)$ distribution: End of explanation """ data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] """ Explanation: 3. For days before $\tau$, represent the user's received SMS count by sampling from $\text{Poi}(\lambda_1)$, and sample from $\text{Poi}(\lambda_2)$ for days after $\tau$. For example: End of explanation """ plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlabel("Time (days)") plt.ylabel("count of text-msgs received") plt.title("Artificial dataset") plt.xlim(0, 80) plt.legend(); """ Explanation: 4. Plot the artificial dataset: End of explanation """ def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) figsize(12.5, 5) plt.suptitle("More examples of artificial datasets", fontsize=14) for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() """ Explanation: It is okay that our fictional dataset does not look like our observed dataset: the probability is incredibly small it indeed would. PyMC's engine is designed to find good parameters, $\lambda_i, \tau$, that maximize this probability. The ability to generate artificial datasets is an interesting side effect of our modeling, and we will see that this ability is a very important method of Bayesian inference. We produce a few more datasets below: End of explanation """ import pymc as pm # The parameters are the bounds of the Uniform. p = pm.Uniform('p', lower=0, upper=1) """ Explanation: Later we will see how we use this to make predictions and test the appropriateness of our models. Example: Bayesian A/B testing A/B testing is a statistical design pattern for determining the difference of effectiveness between two different treatments. For example, a pharmaceutical company is interested in the effectiveness of drug A vs drug B. The company will test drug A on some fraction of their trials, and drug B on the other fraction (this fraction is often 1/2, but we will relax this assumption). After performing enough trials, the in-house statisticians sift through the data to determine which drug yielded better results. Similarly, front-end web developers are interested in which design of their website yields more sales or some other metric of interest. They will route some fraction of visitors to site A, and the other fraction to site B, and record if the visit yielded a sale or not. The data is recorded (in real-time), and analyzed afterwards. Often, the post-experiment analysis is done using something called a hypothesis test like difference of means test or difference of proportions test. This involves often misunderstood quantities like a "Z-score" and even more confusing "p-values" (please don't ask). If you have taken a statistics course, you have probably been taught this technique (though not necessarily learned this technique). And if you were like me, you may have felt uncomfortable with their derivation -- good: the Bayesian approach to this problem is much more natural. A Simple Case As this is a hacker book, we'll continue with the web-dev example. For the moment, we will focus on the analysis of site A only. Assume that there is some true $0 \lt p_A \lt 1$ probability that users who, upon shown site A, eventually purchase from the site. This is the true effectiveness of site A. Currently, this quantity is unknown to us. Suppose site A was shown to $N$ people, and $n$ people purchased from the site. One might conclude hastily that $p_A = \frac{n}{N}$. Unfortunately, the observed frequency $\frac{n}{N}$ does not necessarily equal $p_A$ -- there is a difference between the observed frequency and the true frequency of an event. The true frequency can be interpreted as the probability of an event occurring. For example, the true frequency of rolling a 1 on a 6-sided die is $\frac{1}{6}$. Knowing the true frequency of events like: fraction of users who make purchases, frequency of social attributes, percent of internet users with cats etc. are common requests we ask of Nature. Unfortunately, often Nature hides the true frequency from us and we must infer it from observed data. The observed frequency is then the frequency we observe: say rolling the die 100 times you may observe 20 rolls of 1. The observed frequency, 0.2, differs from the true frequency, $\frac{1}{6}$. We can use Bayesian statistics to infer probable values of the true frequency using an appropriate prior and observed data. With respect to our A/B example, we are interested in using what we know, $N$ (the total trials administered) and $n$ (the number of conversions), to estimate what $p_A$, the true frequency of buyers, might be. To set up a Bayesian model, we need to assign prior distributions to our unknown quantities. A priori, what do we think $p_A$ might be? For this example, we have no strong conviction about $p_A$, so for now, let's assume $p_A$ is uniform over [0,1]: End of explanation """ # set constants p_true = 0.05 # remember, this is unknown. N = 1500 # sample N Bernoulli random variables from Ber(0.05). # each random variable has a 0.05 chance of being a 1. # this is the data-generation step occurrences = pm.rbernoulli(p_true, N) print(occurrences) # Remember: Python treats True == 1, and False == 0 print(occurrences.sum()) """ Explanation: Had we had stronger beliefs, we could have expressed them in the prior above. For this example, consider $p_A = 0.05$, and $N = 1500$ users shown site A, and we will simulate whether the user made a purchase or not. To simulate this from $N$ trials, we will use a Bernoulli distribution: if $X\ \sim \text{Ber}(p)$, then $X$ is 1 with probability $p$ and 0 with probability $1 - p$. Of course, in practice we do not know $p_A$, but we will use it here to simulate the data. End of explanation """ # Occurrences.mean is equal to n/N. print("What is the observed frequency in Group A? %.4f" % occurrences.mean()) print("Does this equal the true frequency? %s" % (occurrences.mean() == p_true)) """ Explanation: The observed frequency is: End of explanation """ # include the observations, which are Bernoulli obs = pm.Bernoulli("obs", p, value=occurrences, observed=True) # To be explained in chapter 3 mcmc = pm.MCMC([p, obs]) mcmc.sample(18000, 1000) """ Explanation: We combine the observations into the PyMC observed variable, and run our inference algorithm: End of explanation """ figsize(12.5, 4) plt.title("Posterior distribution of $p_A$, the true effectiveness of site A") plt.vlines(p_true, 0, 90, linestyle="--", label="true $p_A$ (unknown)") plt.hist(mcmc.trace("p")[:], bins=25, histtype="stepfilled", density=True) plt.legend(); """ Explanation: We plot the posterior distribution of the unknown $p_A$ below: End of explanation """ import pymc as pm figsize(12, 4) # these two quantities are unknown to us. true_p_A = 0.05 true_p_B = 0.04 # notice the unequal sample sizes -- no problem in Bayesian analysis. N_A = 1500 N_B = 750 # generate some observations observations_A = pm.rbernoulli(true_p_A, N_A) observations_B = pm.rbernoulli(true_p_B, N_B) print("Obs from Site A: ", observations_A[:30].astype(int), "...") print("Obs from Site B: ", observations_B[:30].astype(int), "...") print(observations_A.mean()) print(observations_B.mean()) # Set up the pymc model. Again assume Uniform priors for p_A and p_B. p_A = pm.Uniform("p_A", 0, 1) p_B = pm.Uniform("p_B", 0, 1) # Define the deterministic delta function. This is our unknown of interest. @pm.deterministic def delta(p_A=p_A, p_B=p_B): return p_A - p_B # Set of observations, in this case we have two observation datasets. obs_A = pm.Bernoulli("obs_A", p_A, value=observations_A, observed=True) obs_B = pm.Bernoulli("obs_B", p_B, value=observations_B, observed=True) # To be explained in chapter 3. mcmc = pm.MCMC([p_A, p_B, delta, obs_A, obs_B]) mcmc.sample(20000, 1000) """ Explanation: Our posterior distribution puts most weight near the true value of $p_A$, but also some weights in the tails. This is a measure of how uncertain we should be, given our observations. Try changing the number of observations, N, and observe how the posterior distribution changes. A and B Together A similar analysis can be done for site B's response data to determine the analogous $p_B$. But what we are really interested in is the difference between $p_A$ and $p_B$. Let's infer $p_A$, $p_B$, and $\text{delta} = p_A - p_B$, all at once. We can do this using PyMC's deterministic variables. (We'll assume for this exercise that $p_B = 0.04$, so $\text{delta} = 0.01$, $N_B = 750$ (significantly less than $N_A$) and we will simulate site B's data like we did for site A's data ) End of explanation """ p_A_samples = mcmc.trace("p_A")[:] p_B_samples = mcmc.trace("p_B")[:] delta_samples = mcmc.trace("delta")[:] figsize(12.5, 10) # histogram of posteriors ax = plt.subplot(311) plt.xlim(0, .1) plt.hist(p_A_samples, histtype='stepfilled', bins=25, alpha=0.85, label="posterior of $p_A$", color="#A60628", density=True) plt.vlines(true_p_A, 0, 80, linestyle="--", label="true $p_A$ (unknown)") plt.legend(loc="upper right") plt.title("Posterior distributions of $p_A$, $p_B$, and delta unknowns") ax = plt.subplot(312) plt.xlim(0, .1) plt.hist(p_B_samples, histtype='stepfilled', bins=25, alpha=0.85, label="posterior of $p_B$", color="#467821", density=True) plt.vlines(true_p_B, 0, 80, linestyle="--", label="true $p_B$ (unknown)") plt.legend(loc="upper right") ax = plt.subplot(313) plt.hist(delta_samples, histtype='stepfilled', bins=30, alpha=0.85, label="posterior of delta", color="#7A68A6", density=True) plt.vlines(true_p_A - true_p_B, 0, 60, linestyle="--", label="true delta (unknown)") plt.vlines(0, 0, 60, color="black", alpha=0.2) plt.legend(loc="upper right"); """ Explanation: Below we plot the posterior distributions for the three unknowns: End of explanation """ # Count the number of samples less than 0, i.e. the area under the curve # before 0, represent the probability that site A is worse than site B. print("Probability site A is WORSE than site B: %.3f" % \ (delta_samples < 0).mean()) print("Probability site A is BETTER than site B: %.3f" % \ (delta_samples > 0).mean()) """ Explanation: Notice that as a result of N_B &lt; N_A, i.e. we have less data from site B, our posterior distribution of $p_B$ is fatter, implying we are less certain about the true value of $p_B$ than we are of $p_A$. With respect to the posterior distribution of $\text{delta}$, we can see that the majority of the distribution is above $\text{delta}=0$, implying there site A's response is likely better than site B's response. The probability this inference is incorrect is easily computable: End of explanation """ figsize(12.5, 4) import scipy.stats as stats binomial = stats.binom parameters = [(10, .4), (10, .9)] colors = ["#348ABD", "#A60628"] for i in range(2): N, p = parameters[i] _x = np.arange(N + 1) plt.bar(_x - 0.5, binomial.pmf(_x, N, p), color=colors[i], edgecolor=colors[i], alpha=0.6, label="$N$: %d, $p$: %.1f" % (N, p), linewidth=3) plt.legend(loc="upper left") plt.xlim(0, 10.5) plt.xlabel("$k$") plt.ylabel("$P(X = k)$") plt.title("Probability mass distributions of binomial random variables"); """ Explanation: If this probability is too high for comfortable decision-making, we can perform more trials on site B (as site B has less samples to begin with, each additional data point for site B contributes more inferential "power" than each additional data point for site A). Try playing with the parameters true_p_A, true_p_B, N_A, and N_B, to see what the posterior of $\text{delta}$ looks like. Notice in all this, the difference in sample sizes between site A and site B was never mentioned: it naturally fits into Bayesian analysis. I hope the readers feel this style of A/B testing is more natural than hypothesis testing, which has probably confused more than helped practitioners. Later in this book, we will see two extensions of this model: the first to help dynamically adjust for bad sites, and the second will improve the speed of this computation by reducing the analysis to a single equation. An algorithm for human deceit Social data has an additional layer of interest as people are not always honest with responses, which adds a further complication into inference. For example, simply asking individuals "Have you ever cheated on a test?" will surely contain some rate of dishonesty. What you can say for certain is that the true rate is less than your observed rate (assuming individuals lie only about not cheating; I cannot imagine one who would admit "Yes" to cheating when in fact they hadn't cheated). To present an elegant solution to circumventing this dishonesty problem, and to demonstrate Bayesian modeling, we first need to introduce the binomial distribution. The Binomial Distribution The binomial distribution is one of the most popular distributions, mostly because of its simplicity and usefulness. Unlike the other distributions we have encountered thus far in the book, the binomial distribution has 2 parameters: $N$, a positive integer representing $N$ trials or number of instances of potential events, and $p$, the probability of an event occurring in a single trial. Like the Poisson distribution, it is a discrete distribution, but unlike the Poisson distribution, it only weighs integers from $0$ to $N$. The mass distribution looks like: $$P( X = k ) = {{N}\choose{k}} p^k(1-p)^{N-k}$$ If $X$ is a binomial random variable with parameters $p$ and $N$, denoted $X \sim \text{Bin}(N,p)$, then $X$ is the number of events that occurred in the $N$ trials (obviously $0 \le X \le N$), and $p$ is the probability of a single event. The larger $p$ is (while still remaining between 0 and 1), the more events are likely to occur. The expected value of a binomial is equal to $Np$. Below we plot the mass probability distribution for varying parameters. End of explanation """ import pymc as pm N = 100 p = pm.Uniform("freq_cheating", 0, 1) """ Explanation: The special case when $N = 1$ corresponds to the Bernoulli distribution. There is another connection between Bernoulli and Binomial random variables. If we have $X_1, X_2, ... , X_N$ Bernoulli random variables with the same $p$, then $Z = X_1 + X_2 + ... + X_N \sim \text{Binomial}(N, p )$. The expected value of a Bernoulli random variable is $p$. This can be seen by noting the more general Binomial random variable has expected value $Np$ and setting $N=1$. Example: Cheating among students We will use the binomial distribution to determine the frequency of students cheating during an exam. If we let $N$ be the total number of students who took the exam, and assuming each student is interviewed post-exam (answering without consequence), we will receive integer $X$ "Yes I did cheat" answers. We then find the posterior distribution of $p$, given $N$, some specified prior on $p$, and observed data $X$. This is a completely absurd model. No student, even with a free-pass against punishment, would admit to cheating. What we need is a better algorithm to ask students if they had cheated. Ideally the algorithm should encourage individuals to be honest while preserving privacy. The following proposed algorithm is a solution I greatly admire for its ingenuity and effectiveness: In the interview process for each student, the student flips a coin, hidden from the interviewer. The student agrees to answer honestly if the coin comes up heads. Otherwise, if the coin comes up tails, the student (secretly) flips the coin again, and answers "Yes, I did cheat" if the coin flip lands heads, and "No, I did not cheat", if the coin flip lands tails. This way, the interviewer does not know if a "Yes" was the result of a guilty plea, or a Heads on a second coin toss. Thus privacy is preserved and the researchers receive honest answers. I call this the Privacy Algorithm. One could of course argue that the interviewers are still receiving false data since some Yes's are not confessions but instead randomness, but an alternative perspective is that the researchers are discarding approximately half of their original dataset since half of the responses will be noise. But they have gained a systematic data generation process that can be modeled. Furthermore, they do not have to incorporate (perhaps somewhat naively) the possibility of deceitful answers. We can use PyMC to dig through this noisy model, and find a posterior distribution for the true frequency of liars. Suppose 100 students are being surveyed for cheating, and we wish to find $p$, the proportion of cheaters. There are a few ways we can model this in PyMC. I'll demonstrate the most explicit way, and later show a simplified version. Both versions arrive at the same inference. In our data-generation model, we sample $p$, the true proportion of cheaters, from a prior. Since we are quite ignorant about $p$, we will assign it a $\text{Uniform}(0,1)$ prior. End of explanation """ true_answers = pm.Bernoulli("truths", p, size=N) """ Explanation: Again, thinking of our data-generation model, we assign Bernoulli random variables to the 100 students: 1 implies they cheated and 0 implies they did not. End of explanation """ first_coin_flips = pm.Bernoulli("first_flips", 0.5, size=N) print(first_coin_flips.value) """ Explanation: If we carry out the algorithm, the next step that occurs is the first coin-flip each student makes. This can be modeled again by sampling 100 Bernoulli random variables with $p=1/2$: denote a 1 as a Heads and 0 a Tails. End of explanation """ second_coin_flips = pm.Bernoulli("second_flips", 0.5, size=N) """ Explanation: Although not everyone flips a second time, we can still model the possible realization of second coin-flips: End of explanation """ @pm.deterministic def observed_proportion(t_a=true_answers, fc=first_coin_flips, sc=second_coin_flips): observed = fc * t_a + (1 - fc) * sc return observed.sum() / float(N) """ Explanation: Using these variables, we can return a possible realization of the observed proportion of "Yes" responses. We do this using a PyMC deterministic variable: End of explanation """ observed_proportion.value """ Explanation: The line fc*t_a + (1-fc)*sc contains the heart of the Privacy algorithm. Elements in this array are 1 if and only if i) the first toss is heads and the student cheated or ii) the first toss is tails, and the second is heads, and are 0 else. Finally, the last line sums this vector and divides by float(N), produces a proportion. End of explanation """ X = 35 observations = pm.Binomial("obs", N, observed_proportion, observed=True, value=X) """ Explanation: Next we need a dataset. After performing our coin-flipped interviews the researchers received 35 "Yes" responses. To put this into a relative perspective, if there truly were no cheaters, we should expect to see on average 1/4 of all responses being a "Yes" (half chance of having first coin land Tails, and another half chance of having second coin land Heads), so about 25 responses in a cheat-free world. On the other hand, if all students cheated, we should expect to see approximately 3/4 of all responses be "Yes". The researchers observe a Binomial random variable, with N = 100 and p = observed_proportion with value = 35: End of explanation """ model = pm.Model([p, true_answers, first_coin_flips, second_coin_flips, observed_proportion, observations]) # To be explained in Chapter 3! mcmc = pm.MCMC(model) mcmc.sample(40000, 15000) figsize(12.5, 3) p_trace = mcmc.trace("freq_cheating")[:] plt.hist(p_trace, histtype="stepfilled", density=True, alpha=0.85, bins=30, label="posterior distribution", color="#348ABD") plt.vlines([.05, .35], [0, 0], [5, 5], alpha=0.3) plt.xlim(0, 1) plt.legend(); """ Explanation: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. End of explanation """ p = pm.Uniform("freq_cheating", 0, 1) @pm.deterministic def p_skewed(p=p): return 0.5 * p + 0.25 """ Explanation: With regards to the above plot, we are still pretty uncertain about what the true frequency of cheaters might be, but we have narrowed it down to a range between 0.05 to 0.35 (marked by the solid lines). This is pretty good, as a priori we had no idea how many students might have cheated (hence the uniform distribution for our prior). On the other hand, it is also pretty bad since there is a .3 length window the true value most likely lives in. Have we even gained anything, or are we still too uncertain about the true frequency? I would argue, yes, we have discovered something. It is implausible, according to our posterior, that there are no cheaters, i.e. the posterior assigns low probability to $p=0$. Since we started with a uniform prior, treating all values of $p$ as equally plausible, but the data ruled out $p=0$ as a possibility, we can be confident that there were cheaters. This kind of algorithm can be used to gather private information from users and be reasonably confident that the data, though noisy, is truthful. Alternative PyMC Model Given a value for $p$ (which from our god-like position we know), we can find the probability the student will answer yes: \begin{align} P(\text{"Yes"}) &= P( \text{Heads on first coin} )P( \text{cheater} ) + P( \text{Tails on first coin} )P( \text{Heads on second coin} ) \\ & = \frac{1}{2}p + \frac{1}{2}\frac{1}{2}\\ & = \frac{p}{2} + \frac{1}{4} \end{align} Thus, knowing $p$ we know the probability a student will respond "Yes". In PyMC, we can create a deterministic function to evaluate the probability of responding "Yes", given $p$: End of explanation """ yes_responses = pm.Binomial("number_cheaters", 100, p_skewed, value=35, observed=True) """ Explanation: I could have typed p_skewed = 0.5*p + 0.25 instead for a one-liner, as the elementary operations of addition and scalar multiplication will implicitly create a deterministic variable, but I wanted to make the deterministic boilerplate explicit for clarity's sake. If we know the probability of respondents saying "Yes", which is p_skewed, and we have $N=100$ students, the number of "Yes" responses is a binomial random variable with parameters N and p_skewed. This is where we include our observed 35 "Yes" responses. In the declaration of the pm.Binomial, we include value = 35 and observed = True. End of explanation """ model = pm.Model([yes_responses, p_skewed, p]) # To Be Explained in Chapter 3! mcmc = pm.MCMC(model) mcmc.sample(25000, 2500) figsize(12.5, 3) p_trace = mcmc.trace("freq_cheating")[:] plt.hist(p_trace, histtype="stepfilled", density=True, alpha=0.85, bins=30, label="posterior distribution", color="#348ABD") plt.vlines([.05, .35], [0, 0], [5, 5], alpha=0.2) plt.xlim(0, 1) plt.legend(); """ Explanation: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. End of explanation """ N = 10 x = np.empty(N, dtype=object) for i in range(0, N): x[i] = pm.Exponential('x_%i' % i, (i + 1) ** 2) """ Explanation: More PyMC Tricks Protip: Lighter deterministic variables with Lambda class Sometimes writing a deterministic function using the @pm.deterministic decorator can seem like a chore, especially for a small function. I have already mentioned that elementary math operations can produce deterministic variables implicitly, but what about operations like indexing or slicing? Built-in Lambda functions can handle this with the elegance and simplicity required. For example, beta = pm.Normal("coefficients", 0, size=(N, 1)) x = np.random.randn((N, 1)) linear_combination = pm.Lambda(lambda x=x, beta=beta: np.dot(x.T, beta)) Protip: Arrays of PyMC variables There is no reason why we cannot store multiple heterogeneous PyMC variables in a Numpy array. Just remember to set the dtype of the array to object upon initialization. For example: End of explanation """ figsize(12.5, 3.5) np.set_printoptions(precision=3, suppress=True) challenger_data = np.genfromtxt("data/challenger_data.csv", skip_header=1, usecols=[1, 2], missing_values="NA", delimiter=",") # drop the NA values challenger_data = challenger_data[~np.isnan(challenger_data[:, 1])] # plot it, as a function of temperature (the first column) print("Temp (F), O-Ring failure?") print(challenger_data) plt.scatter(challenger_data[:, 0], challenger_data[:, 1], s=75, color="k", alpha=0.5) plt.yticks([0, 1]) plt.ylabel("Damage Incident?") plt.xlabel("Outside temperature (Fahrenheit)") plt.title("Defects of the Space Shuttle O-Rings vs temperature"); """ Explanation: The remainder of this chapter examines some practical examples of PyMC and PyMC modeling: Example: Challenger Space Shuttle Disaster <span id="challenger"/> On January 28, 1986, the twenty-fifth flight of the U.S. space shuttle program ended in disaster when one of the rocket boosters of the Shuttle Challenger exploded shortly after lift-off, killing all seven crew members. The presidential commission on the accident concluded that it was caused by the failure of an O-ring in a field joint on the rocket booster, and that this failure was due to a faulty design that made the O-ring unacceptably sensitive to a number of factors including outside temperature. Of the previous 24 flights, data were available on failures of O-rings on 23, (one was lost at sea), and these data were discussed on the evening preceding the Challenger launch, but unfortunately only the data corresponding to the 7 flights on which there was a damage incident were considered important and these were thought to show no obvious trend. The data are shown below (see [1]): End of explanation """ figsize(12, 3) def logistic(x, beta): return 1.0 / (1.0 + np.exp(beta * x)) x = np.linspace(-4, 4, 100) plt.plot(x, logistic(x, 1), label=r"$\beta = 1$") plt.plot(x, logistic(x, 3), label=r"$\beta = 3$") plt.plot(x, logistic(x, -5), label=r"$\beta = -5$") plt.title("Logistic functon plotted for several value of $\\beta$ parameter", fontsize=14) plt.legend(); """ Explanation: It looks clear that the probability of damage incidents occurring increases as the outside temperature decreases. We are interested in modeling the probability here because it does not look like there is a strict cutoff point between temperature and a damage incident occurring. The best we can do is ask "At temperature $t$, what is the probability of a damage incident?". The goal of this example is to answer that question. We need a function of temperature, call it $p(t)$, that is bounded between 0 and 1 (so as to model a probability) and changes from 1 to 0 as we increase temperature. There are actually many such functions, but the most popular choice is the logistic function. $$p(t) = \frac{1}{ 1 + e^{ \;\beta t } } $$ In this model, $\beta$ is the variable we are uncertain about. Below is the function plotted for $\beta = 1, 3, -5$. End of explanation """ def logistic(x, beta, alpha=0): return 1.0 / (1.0 + np.exp(np.dot(beta, x) + alpha)) x = np.linspace(-4, 4, 100) plt.plot(x, logistic(x, 1), label=r"$\beta = 1$", ls="--", lw=1) plt.plot(x, logistic(x, 3), label=r"$\beta = 3$", ls="--", lw=1) plt.plot(x, logistic(x, -5), label=r"$\beta = -5$", ls="--", lw=1) plt.plot(x, logistic(x, 1, 1), label=r"$\beta = 1, \alpha = 1$", color="#348ABD") plt.plot(x, logistic(x, 3, -2), label=r"$\beta = 3, \alpha = -2$", color="#A60628") plt.plot(x, logistic(x, -5, 7), label=r"$\beta = -5, \alpha = 7$", color="#7A68A6") plt.title("Logistic functon with bias, plotted for several value of $\\alpha$ bias parameter", fontsize=14) plt.legend(loc="lower left"); """ Explanation: But something is missing. In the plot of the logistic function, the probability changes only near zero, but in our data above the probability changes around 65 to 70. We need to add a bias term to our logistic function: $$p(t) = \frac{1}{ 1 + e^{ \;\beta t + \alpha } } $$ Some plots are below, with differing $\alpha$. End of explanation """ import scipy.stats as stats nor = stats.norm x = np.linspace(-8, 7, 150) mu = (-2, 0, 3) tau = (.7, 1, 2.8) colors = ["#348ABD", "#A60628", "#7A68A6"] parameters = zip(mu, tau, colors) for _mu, _tau, _color in parameters: plt.plot(x, nor.pdf(x, _mu, scale=1. / np.sqrt(_tau)), label="$\mu = %d,\;\\tau = %.1f$" % (_mu, _tau), color=_color) plt.fill_between(x, nor.pdf(x, _mu, scale=1. / np.sqrt(_tau)), color=_color, alpha=.33) plt.legend(loc="upper right") plt.xlabel("$x$") plt.ylabel("density function at $x$") plt.title("Probability distribution of three different Normal random \ variables"); """ Explanation: Adding a constant term $\alpha$ amounts to shifting the curve left or right (hence why it is called a bias). Let's start modeling this in PyMC. The $\beta, \alpha$ parameters have no reason to be positive, bounded or relatively large, so they are best modeled by a Normal random variable, introduced next. Normal distributions A Normal random variable, denoted $X \sim N(\mu, 1/\tau)$, has a distribution with two parameters: the mean, $\mu$, and the precision, $\tau$. Those familiar with the Normal distribution already have probably seen $\sigma^2$ instead of $\tau^{-1}$. They are in fact reciprocals of each other. The change was motivated by simpler mathematical analysis and is an artifact of older Bayesian methods. Just remember: the smaller $\tau$, the larger the spread of the distribution (i.e. we are more uncertain); the larger $\tau$, the tighter the distribution (i.e. we are more certain). Regardless, $\tau$ is always positive. The probability density function of a $N( \mu, 1/\tau)$ random variable is: $$ f(x | \mu, \tau) = \sqrt{\frac{\tau}{2\pi}} \exp\left( -\frac{\tau}{2} (x-\mu)^2 \right) $$ We plot some different density functions below. End of explanation """ import pymc as pm temperature = challenger_data[:, 0] D = challenger_data[:, 1] # defect or not? # notice the`value` here. We explain why below. beta = pm.Normal("beta", 0, 0.001, value=0) alpha = pm.Normal("alpha", 0, 0.001, value=0) @pm.deterministic def p(t=temperature, alpha=alpha, beta=beta): return 1.0 / (1. + np.exp(beta * t + alpha)) """ Explanation: A Normal random variable can be take on any real number, but the variable is very likely to be relatively close to $\mu$. In fact, the expected value of a Normal is equal to its $\mu$ parameter: $$ E[ X | \mu, \tau] = \mu$$ and its variance is equal to the inverse of $\tau$: $$Var( X | \mu, \tau ) = \frac{1}{\tau}$$ Below we continue our modeling of the Challenger space craft: End of explanation """ p.value # connect the probabilities in `p` with our observations through a # Bernoulli random variable. observed = pm.Bernoulli("bernoulli_obs", p, value=D, observed=True) model = pm.Model([observed, beta, alpha]) # Mysterious code to be explained in Chapter 3 map_ = pm.MAP(model) map_.fit() mcmc = pm.MCMC(model) mcmc.sample(120000, 100000, 2) """ Explanation: We have our probabilities, but how do we connect them to our observed data? A Bernoulli random variable with parameter $p$, denoted $\text{Ber}(p)$, is a random variable that takes value 1 with probability $p$, and 0 else. Thus, our model can look like: $$ \text{Defect Incident, $D_i$} \sim \text{Ber}( \;p(t_i)\; ), \;\; i=1..N$$ where $p(t)$ is our logistic function and $t_i$ are the temperatures we have observations about. Notice in the above code we had to set the values of beta and alpha to 0. The reason for this is that if beta and alpha are very large, they make p equal to 1 or 0. Unfortunately, pm.Bernoulli does not like probabilities of exactly 0 or 1, though they are mathematically well-defined probabilities. So by setting the coefficient values to 0, we set the variable p to be a reasonable starting value. This has no effect on our results, nor does it mean we are including any additional information in our prior. It is simply a computational caveat in PyMC. End of explanation """ alpha_samples = mcmc.trace('alpha')[:, None] # best to make them 1d beta_samples = mcmc.trace('beta')[:, None] figsize(12.5, 6) # histogram of the samples: plt.subplot(211) plt.title(r"Posterior distributions of the variables $\alpha, \beta$") plt.hist(beta_samples, histtype='stepfilled', bins=35, alpha=0.85, label=r"posterior of $\beta$", color="#7A68A6", density=True) plt.legend() plt.subplot(212) plt.hist(alpha_samples, histtype='stepfilled', bins=35, alpha=0.85, label=r"posterior of $\alpha$", color="#A60628", density=True) plt.legend(); """ Explanation: We have trained our model on the observed data, now we can sample values from the posterior. Let's look at the posterior distributions for $\alpha$ and $\beta$: End of explanation """ t = np.linspace(temperature.min() - 5, temperature.max() + 5, 50)[:, None] p_t = logistic(t.T, beta_samples, alpha_samples) mean_prob_t = p_t.mean(axis=0) figsize(12.5, 4) plt.plot(t, mean_prob_t, lw=3, label="average posterior \nprobability \ of defect") plt.plot(t, p_t[0, :], ls="--", label="realization from posterior") plt.plot(t, p_t[-2, :], ls="--", label="realization from posterior") plt.scatter(temperature, D, color="k", s=50, alpha=0.5) plt.title("Posterior expected value of probability of defect; \ plus realizations") plt.legend(loc="lower left") plt.ylim(-0.1, 1.1) plt.xlim(t.min(), t.max()) plt.ylabel("probability") plt.xlabel("temperature"); """ Explanation: All samples of $\beta$ are greater than 0. If instead the posterior was centered around 0, we may suspect that $\beta = 0$, implying that temperature has no effect on the probability of defect. Similarly, all $\alpha$ posterior values are negative and far away from 0, implying that it is correct to believe that $\alpha$ is significantly less than 0. Regarding the spread of the data, we are very uncertain about what the true parameters might be (though considering the low sample size and the large overlap of defects-to-nondefects this behaviour is perhaps expected). Next, let's look at the expected probability for a specific value of the temperature. That is, we average over all samples from the posterior to get a likely value for $p(t_i)$. End of explanation """ from scipy.stats.mstats import mquantiles # vectorized bottom and top 2.5% quantiles for "confidence interval" qs = mquantiles(p_t, [0.025, 0.975], axis=0) plt.fill_between(t[:, 0], *qs, alpha=0.7, color="#7A68A6") plt.plot(t[:, 0], qs[0], label="95% CI", color="#7A68A6", alpha=0.7) plt.plot(t, mean_prob_t, lw=1, ls="--", color="k", label="average posterior \nprobability of defect") plt.xlim(t.min(), t.max()) plt.ylim(-0.02, 1.02) plt.legend(loc="lower left") plt.scatter(temperature, D, color="k", s=50, alpha=0.5) plt.xlabel("temp, $t$") plt.ylabel("probability estimate") plt.title("Posterior probability estimates given temp. $t$"); """ Explanation: Above we also plotted two possible realizations of what the actual underlying system might be. Both are equally likely as any other draw. The blue line is what occurs when we average all the 20000 possible dotted lines together. An interesting question to ask is for what temperatures are we most uncertain about the defect-probability? Below we plot the expected value line and the associated 95% intervals for each temperature. End of explanation """ figsize(12.5, 2.5) prob_31 = logistic(31, beta_samples, alpha_samples) plt.xlim(0.995, 1) plt.hist(prob_31, bins=1000, density=True, histtype='stepfilled') plt.title("Posterior distribution of probability of defect, given $t = 31$") plt.xlabel("probability of defect occurring in O-ring"); """ Explanation: The 95% credible interval, or 95% CI, painted in purple, represents the interval, for each temperature, that contains 95% of the distribution. For example, at 65 degrees, we can be 95% sure that the probability of defect lies between 0.25 and 0.75. More generally, we can see that as the temperature nears 60 degrees, the CI's spread out over [0,1] quickly. As we pass 70 degrees, the CI's tighten again. This can give us insight about how to proceed next: we should probably test more O-rings around 60-65 temperature to get a better estimate of probabilities in that range. Similarly, when reporting to scientists your estimates, you should be very cautious about simply telling them the expected probability, as we can see this does not reflect how wide the posterior distribution is. What about the day of the Challenger disaster? On the day of the Challenger disaster, the outside temperature was 31 degrees Fahrenheit. What is the posterior distribution of a defect occurring, given this temperature? The distribution is plotted below. It looks almost guaranteed that the Challenger was going to be subject to defective O-rings. End of explanation """ simulated = pm.Bernoulli("bernoulli_sim", p) N = 10000 mcmc = pm.MCMC([simulated, alpha, beta, observed]) mcmc.sample(N) figsize(12.5, 5) simulations = mcmc.trace("bernoulli_sim")[:] print(simulations.shape) plt.title("Simulated dataset using posterior parameters") figsize(12.5, 6) for i in range(4): ax = plt.subplot(4, 1, i + 1) plt.scatter(temperature, simulations[1000 * i, :], color="k", s=50, alpha=0.6) """ Explanation: Is our model appropriate? The skeptical reader will say "You deliberately chose the logistic function for $p(t)$ and the specific priors. Perhaps other functions or priors will give different results. How do I know I have chosen a good model?" This is absolutely true. To consider an extreme situation, what if I had chosen the function $p(t) = 1,\; \forall t$, which guarantees a defect always occurring: I would have again predicted disaster on January 28th. Yet this is clearly a poorly chosen model. On the other hand, if I did choose the logistic function for $p(t)$, but specified all my priors to be very tight around 0, likely we would have very different posterior distributions. How do we know our model is an expression of the data? This encourages us to measure the model's goodness of fit. We can think: how can we test whether our model is a bad fit? An idea is to compare observed data (which if we recall is a fixed stochastic variable) with an artificial dataset which we can simulate. The rationale is that if the simulated dataset does not appear similar, statistically, to the observed dataset, then likely our model is not accurately represented the observed data. Previously in this Chapter, we simulated artificial datasets for the SMS example. To do this, we sampled values from the priors. We saw how varied the resulting datasets looked like, and rarely did they mimic our observed dataset. In the current example, we should sample from the posterior distributions to create very plausible datasets. Luckily, our Bayesian framework makes this very easy. We only need to create a new Stochastic variable, that is exactly the same as our variable that stored the observations, but minus the observations themselves. If you recall, our Stochastic variable that stored our observed data was: observed = pm.Bernoulli( "bernoulli_obs", p, value=D, observed=True) Hence we create: simulated_data = pm.Bernoulli("simulation_data", p) Let's simulate 10 000: End of explanation """ posterior_probability = simulations.mean(axis=0) print("posterior prob of defect | realized defect ") for i in range(len(D)): print("%.2f | %d" % (posterior_probability[i], D[i])) """ Explanation: Note that the above plots are different (if you can think of a cleaner way to present this, please send a pull request and answer here!). We wish to assess how good our model is. "Good" is a subjective term of course, so results must be relative to other models. We will be doing this graphically as well, which may seem like an even less objective method. The alternative is to use Bayesian p-values. These are still subjective, as the proper cutoff between good and bad is arbitrary. Gelman emphasises that the graphical tests are more illuminating [7] than p-value tests. We agree. The following graphical test is a novel data-viz approach to logistic regression. The plots are called separation plots[8]. For a suite of models we wish to compare, each model is plotted on an individual separation plot. I leave most of the technical details about separation plots to the very accessible original paper, but I'll summarize their use here. For each model, we calculate the proportion of times the posterior simulation proposed a value of 1 for a particular temperature, i.e. compute $P( \;\text{Defect} = 1 | t, \alpha, \beta )$ by averaging. This gives us the posterior probability of a defect at each data point in our dataset. For example, for the model we used above: End of explanation """ ix = np.argsort(posterior_probability) print("probb | defect ") for i in range(len(D)): print("%.2f | %d" % (posterior_probability[ix[i]], D[ix[i]])) """ Explanation: Next we sort each column by the posterior probabilities: End of explanation """ from separation_plot import separation_plot figsize(11., 1.5) separation_plot(posterior_probability, D) """ Explanation: We can present the above data better in a figure: I've wrapped this up into a separation_plot function. End of explanation """ figsize(11., 1.25) # Our temperature-dependent model separation_plot(posterior_probability, D) plt.title("Temperature-dependent model") # Perfect model # i.e. the probability of defect is equal to if a defect occurred or not. p = D separation_plot(p, D) plt.title("Perfect model") # random predictions p = np.random.rand(23) separation_plot(p, D) plt.title("Random model") # constant model constant_prob = 7. / 23 * np.ones(23) separation_plot(constant_prob, D) plt.title("Constant-prediction model"); """ Explanation: The snaking-line is the sorted probabilities, blue bars denote defects, and empty space (or grey bars for the optimistic readers) denote non-defects. As the probability rises, we see more and more defects occur. On the right hand side, the plot suggests that as the posterior probability is large (line close to 1), then more defects are realized. This is good behaviour. Ideally, all the blue bars should be close to the right-hand side, and deviations from this reflect missed predictions. The black vertical line is the expected number of defects we should observe, given this model. This allows the user to see how the total number of events predicted by the model compares to the actual number of events in the data. It is much more informative to compare this to separation plots for other models. Below we compare our model (top) versus three others: the perfect model, which predicts the posterior probability to be equal to 1 if a defect did occur. a completely random model, which predicts random probabilities regardless of temperature. a constant model: where $P(D = 1 \; | \; t) = c, \;\; \forall t$. The best choice for $c$ is the observed frequency of defects, in this case 7/23. End of explanation """ # type your code here. figsize(12.5, 4) plt.scatter(alpha_samples, beta_samples, alpha=0.1) plt.title("Why does the plot look like this?") plt.xlabel(r"$\alpha$") plt.ylabel(r"$\beta$"); """ Explanation: In the random model, we can see that as the probability increases there is no clustering of defects to the right-hand side. Similarly for the constant model. The perfect model, the probability line is not well shown, as it is stuck to the bottom and top of the figure. Of course the perfect model is only for demonstration, and we cannot infer any scientific inference from it. Exercises 1. Try putting in extreme values for our observations in the cheating example. What happens if we observe 25 affirmative responses? 10? 50? 2. Try plotting $\alpha$ samples versus $\beta$ samples. Why might the resulting plot look like this? End of explanation """ from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling() """ Explanation: References [1] Dalal, Fowlkes and Hoadley (1989),JASA, 84, 945-957. [2] German Rodriguez. Datasets. In WWS509. Retrieved 30/01/2013, from http://data.princeton.edu/wws509/datasets/#smoking. [3] McLeish, Don, and Cyntha Struthers. STATISTICS 450/850 Estimation and Hypothesis Testing. Winter 2012. Waterloo, Ontario: 2012. Print. [4] Fonnesbeck, Christopher. "Building Models." PyMC-Devs. N.p., n.d. Web. 26 Feb 2013. http://pymc-devs.github.com/pymc/modelbuilding.html. [5] Cronin, Beau. "Why Probabilistic Programming Matters." 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1. [6] S.P. Brooks, E.A. Catchpole, and B.J.T. Morgan. Bayesian animal survival estimation. Statistical Science, 15: 357–376, 2000 [7] Gelman, Andrew. "Philosophy and the practice of Bayesian statistics." British Journal of Mathematical and Statistical Psychology. (2012): n. page. Web. 2 Apr. 2013. [8] Greenhill, Brian, Michael D. Ward, and Audrey Sacks. "The Separation Plot: A New Visual Method for Evaluating the Fit of Binary Models." American Journal of Political Science. 55.No.4 (2011): n. page. Web. 2 Apr. 2013. End of explanation """
jlandmann/oggm
docs/notebooks/wgms_refmbdata.ipynb
gpl-3.0
import pandas as pd import os import numpy as np import matplotlib.pyplot as plt %matplotlib inline """ Explanation: <img src="https://raw.githubusercontent.com/OGGM/oggm/master/docs/_static/logo.png" width="40%" align="left"> Processing WGMS mass-balance data for OGGM In this notebook, we use the most recent lookup table provided by the WGMS to prepare the reference mass-balance data for the OGGM model. For this to work you'll need the latest lookup table (available through official channels soon), the latest WGMS FoG data (available here), and the latest RGI version (available here). End of explanation """ idir = '/home/mowglie/Downloads/Links/' df_links = pd.read_csv(os.path.join(idir, 'WGMS_FoG_GLACIER_ID_LUT_v2017-01-13.csv'), encoding='iso8859_15') df_mb_all = pd.read_csv(os.path.join(idir, 'WGMS-FoG-2016-08-EE-MASS-BALANCE.csv'), encoding='iso8859_15') 'Total number of links: {}'.format(len(df_links)) df_links = df_links.dropna(subset=['RGI_ID']) # keep the ones with a valid RGI ID 'Total number of RGI links: {}'.format(len(df_links)) """ Explanation: Read the WGMS files End of explanation """ df_mb = df_mb_all[df_mb_all.LOWER_BOUND.isin([9999])].copy() # remove the profiles gp_id = df_mb.groupby('WGMS_ID') ids_5 = [] ids_1 = [] for wgmsid, group in gp_id: if np.sum(np.isfinite(group.ANNUAL_BALANCE.values)) >= 5: ids_5.append(wgmsid) if np.sum(np.isfinite(group.ANNUAL_BALANCE.values)) >= 1: ids_1.append(wgmsid) print('Number of glaciers with more than 1 MB years: {}'.format(len(ids_1))) print('Number of glaciers with more than 5 MB years: {}'.format(len(ids_5))) """ Explanation: Select WGMS IDs with more than N years of mass-balance End of explanation """ 'Number of matches in the WGMS lookup-table: {}'.format(len(df_links.loc[df_links.WGMS_ID.isin(ids_5)])) # keep those df_links_sel = df_links.loc[df_links.WGMS_ID.isin(ids_5)] """ Explanation: Number of glaciers in the lookup table with at least 5 years of valid MB data End of explanation """ df_links_sel.loc[df_links_sel.duplicated('RGI_ID', keep=False)] """ Explanation: Duplicates? Yes: End of explanation """ # We keep CARESER as this is the longest before they split df_links_sel = df_links_sel.loc[~ df_links_sel.WGMS_ID.isin([3346, 3345])] """ Explanation: Careser is an Italian glacier which is now disintegrated in smaller parts. Here a screenshot from the WGMS exploration tool: <img src="https://dl.dropboxusercontent.com/u/20930277/do_not_delete/wgms_1.jpg" width="80%"> We keep the oldest MB series and discard the newer ones which are for the smaller glaciers (not represented in RGI). End of explanation """ df_mb.loc[df_mb.WGMS_ID.isin([3339])].set_index('YEAR').ANNUAL_BALANCE.plot() df_mb.loc[df_mb.WGMS_ID.isin([3343])].set_index('YEAR').ANNUAL_BALANCE.plot(); """ Explanation: The two norwegian glaciers are part of an ice cap: <img src="https://dl.dropboxusercontent.com/u/20930277/do_not_delete/wgms_2.jpg" width="80%"> The two mass-balance time series are very close to each other, unsurprisingly: End of explanation """ # The two nowegians glaciers are some part of an ice cap. I'll just remove them both df_links_sel = df_links_sel.loc[~ df_links_sel.WGMS_ID.isin([3339, 3343])] 'Final number of matches in the WGMS lookup-table: {}'.format(len(df_links_sel)) # add some simple stats df_links_sel['RGI_REG'] = [rid.split('-')[1].split('.')[0] for rid in df_links_sel.RGI_ID] df_links_sel['N_MB_YRS'] = [len(df_mb.loc[df_mb.WGMS_ID == wid]) for wid in df_links_sel.WGMS_ID] """ Explanation: Since there is no reason for picking one series over the other, we have to remove both from the list. End of explanation """ odir = '/home/mowglie/Downloads/WGMS' """ Explanation: Write out the mass-balance data End of explanation """ for rid, wid in zip(df_links_sel.RGI_ID, df_links_sel.WGMS_ID): df_mb_sel = df_mb.loc[df_mb.WGMS_ID == wid].copy() df_mb_sel = df_mb_sel[['YEAR', 'WGMS_ID', 'POLITICAL_UNIT', 'NAME', 'AREA', 'WINTER_BALANCE', 'SUMMER_BALANCE', 'ANNUAL_BALANCE', 'REMARKS']].set_index('YEAR') df_mb_sel['RGI_ID'] = rid df_mb_sel.to_csv(os.path.join(odir, 'mbdata', 'mbdata_WGMS-{:05d}.csv'.format(wid))) """ Explanation: Annual MB End of explanation """ for rid, wid in zip(df_links_sel.RGI_ID, df_links_sel.WGMS_ID): df_mb_sel = df_mb_all.loc[df_mb_all.WGMS_ID == wid].copy() df_mb_sel = df_mb_sel.loc[df_mb_sel.LOWER_BOUND != 9999] df_mb_sel = df_mb_sel.loc[df_mb_sel.UPPER_BOUND != 9999] if len(df_mb_sel) == 0: df_links_sel.loc[df_links_sel.RGI_ID == rid, 'HAS_PROFILE'] = False continue lb = set() for yr in df_mb_sel.YEAR.unique(): df_mb_sel_yr = df_mb_sel.loc[df_mb_sel.YEAR == yr] mids = df_mb_sel_yr.LOWER_BOUND.values*1. mids += df_mb_sel_yr.UPPER_BOUND.values[:len(mids)] mids *= 0.5 [lb.add(int(m)) for m in mids] prof = pd.DataFrame(columns=sorted(list(lb)), index=sorted(df_mb_sel.YEAR.unique())) for yr in df_mb_sel.YEAR.unique(): df_mb_sel_yr = df_mb_sel.loc[df_mb_sel.YEAR == yr] mids = df_mb_sel_yr.LOWER_BOUND.values*1. mids += df_mb_sel_yr.UPPER_BOUND.values[:len(mids)] mids *= 0.5 prof.loc[yr, mids.astype(int)] = df_mb_sel_yr.ANNUAL_BALANCE.values prof.to_csv(os.path.join(odir, 'profiles', 'profile_WGMS-{:05d}.csv'.format(wid))) df_links_sel.loc[df_links_sel.RGI_ID == rid, 'HAS_PROFILE'] = True """ Explanation: Profiles End of explanation """ # Handle various RGI versions df_links_sel.rename(columns = {'RGI_ID':'RGI50_ID'}, inplace = True) df_links_sel['RGI40_ID'] = df_links_sel['RGI50_ID'] df_links_sel['RGI40_ID'] = [rid.replace('RGI50', 'RGI40') for rid in df_links_sel['RGI40_ID']] # Get the RGI import geopandas as gpd import glob, os frgi = '/home/mowglie/Documents/rgi50_allglaciers.csv' if not os.path.exists(frgi): # one time action only fs = list(sorted(glob.glob("/home/mowglie/disk/Data/GIS/SHAPES/RGI/RGI_V5/*/*_rgi50_*.shp")))[2:] out = [] for f in fs: sh = gpd.read_file(f).set_index('RGIId') del sh['geometry'] del sh['GLIMSId'] del sh['Name'] out.append(sh) mdf = pd.concat(out) mdf.to_csv(frgi) mdf = pd.read_csv(frgi, index_col=0, converters={'GlacType': str, 'RGIFlag':str, 'BgnDate':str, 'O1Region': str, 'O2Region':str}) mdf['RGI_REG'] = [rid.split('-')[1].split('.')[0] for rid in mdf.index] # add region names sr = gpd.read_file('/home/mowglie/disk/Data/GIS/SHAPES/RGI/RGI_V5/00_rgi50_regions/00_rgi50_O1Regions.shp') sr = sr.drop_duplicates('Secondary_').set_index('Secondary_')[['Primary_ID']] sr['Primary_ID'] = [i + ': ' + s for i, s in sr.Primary_ID.iteritems()] mdf['RGI_REG_NAME'] = sr.loc[mdf.RGI_REG].Primary_ID.values # Read glacier attrs key1 = {'0': 'Glacier', '1': 'Ice cap', '2': 'Perennial snowfield', '3': 'Seasonal snowfield', '9': 'Not assigned', } key2 = {'0': 'Land-terminating', '1': 'Marine-terminating', '2': 'Lake-terminating', '3': 'Dry calving', '4': 'Regenerated', '5': 'Shelf-terminating', '9': 'Not assigned', } def is_tidewater(ttype): return mdf['GlacierType'] = [key1[gtype[0]] for gtype in mdf.GlacType] mdf['TerminusType'] = [key2[gtype[1]] for gtype in mdf.GlacType] mdf['IsTidewater'] = [ttype in ['Marine-terminating', 'Lake-terminating'] for ttype in mdf.TerminusType] # add lons and lats and other attrs to the WGMS ones smdf = mdf.loc[df_links_sel.RGI50_ID] df_links_sel['CenLon'] = smdf.CenLon.values df_links_sel['CenLat'] = smdf.CenLat.values df_links_sel['GlacierType'] = smdf.GlacierType.values df_links_sel['TerminusType'] = smdf.TerminusType.values df_links_sel['IsTidewater'] = smdf.IsTidewater.values df_links_sel['RGI_REG_NAME'] = smdf.RGI_REG_NAME.values df_links_sel = df_links_sel[['CenLon', 'CenLat', 'POLITICAL_UNIT', 'NAME', 'WGMS_ID', 'PSFG_ID', 'WGI_ID', 'GLIMS_ID', 'RGI40_ID', 'RGI50_ID', 'RGI_REG', 'RGI_REG_NAME', 'GlacierType', 'TerminusType', 'IsTidewater', 'N_MB_YRS', 'HAS_PROFILE', 'REMARKS']] df_links_sel.to_csv(os.path.join(odir, 'rgi_wgms_links_20170217_RGIV5.csv'.format(wid)), index=False) """ Explanation: Links: add some stats End of explanation """ import seaborn as sns sns.set_context('poster') sns.set_style('whitegrid') pdir = '/home/mowglie/Documents/git/fmaussion.github.io/images/blog/wgms-links' df_links_sel['N_MB_YRS'].plot(kind='hist', color='C2', bins=np.arange(21)*5); plt.xlim(5, 100); plt.ylabel('Number of glaciers') plt.xlabel('Length of the timeseries (years)'); plt.tight_layout(); plt.savefig(os.path.join(pdir, 'nglacier-hist.png'), dpi=150) import cartopy import cartopy.crs as ccrs f = plt.figure(figsize=(12, 7)) ax = plt.axes(projection=ccrs.Robinson()) # mark a known place to help us geo-locate ourselves ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree()) ax.stock_img() ax.add_feature(cartopy.feature.COASTLINE); s = df_links_sel.loc[df_links_sel.N_MB_YRS < 10] print(len(s)) ax.scatter(s.CenLon, s.CenLat, label='< 10 MB years', s=50, edgecolor='k', facecolor='C0', transform=ccrs.PlateCarree(), zorder=99) s = df_links_sel.loc[(df_links_sel.N_MB_YRS >= 10) & (df_links_sel.N_MB_YRS < 30)] print(len(s)) ax.scatter(s.CenLon, s.CenLat, label='$\geq$ 10 and < 30 MB years', s=50, edgecolor='k', facecolor='C1', transform=ccrs.PlateCarree(), zorder=99) s = df_links_sel.loc[df_links_sel.N_MB_YRS >= 30] print(len(s)) ax.scatter(s.CenLon, s.CenLat, label='$\geq$ 30 MB years', s=50, edgecolor='k', facecolor='C2', transform=ccrs.PlateCarree(), zorder=99) plt.title('WGMS glaciers with at least 5 years of mass-balance data') plt.legend(loc=4, frameon=True) plt.tight_layout(); plt.savefig(os.path.join(pdir, 'glacier-map.png'), dpi=150) df_links_sel.TerminusType.value_counts().to_frame() ax = sns.countplot(x='RGI_REG', hue="TerminusType", data=df_links_sel); md = pd.concat([mdf.GlacierType.value_counts().to_frame(name='RGI V5').T, df_links_sel.GlacierType.value_counts().to_frame(name='WGMS').T] ).T md md = pd.concat([mdf.TerminusType.value_counts().to_frame(name='RGI V5').T, df_links_sel.TerminusType.value_counts().to_frame(name='WGMS').T] ).T md area_per_reg = mdf[['Area', 'RGI_REG_NAME']].groupby('RGI_REG_NAME').sum() area_per_reg['N_WGMS'] = df_links_sel.RGI_REG_NAME.value_counts() area_per_reg = area_per_reg.reset_index() sns.barplot(x="Area", y="RGI_REG_NAME", data=area_per_reg); area_per_reg['N_WGMS_PER_UNIT'] = area_per_reg.N_WGMS / area_per_reg.Area * 1000 sns.barplot(x="N_WGMS", y="RGI_REG_NAME", data=area_per_reg); # , palette=sns.husl_palette(19, s=.7, l=.5) plt.ylabel('') plt.xlabel('') plt.title('Number of WGMS glaciers per RGI region'); plt.tight_layout(); plt.savefig(os.path.join(pdir, 'barplot-ng.png'), dpi=150) sns.barplot(x="N_WGMS_PER_UNIT", y="RGI_REG_NAME", data=area_per_reg); plt.ylabel('') plt.xlabel('') plt.title('Number of WGMS glaciers per 1,000 km$^2$ of ice, per RGI region'); plt.tight_layout(); plt.savefig(os.path.join(pdir, 'barplot-perice.png'), dpi=150) nmb_yrs = df_links_sel[["RGI_REG", 'N_MB_YRS']].groupby("RGI_REG").sum() i = [] for k, d in nmb_yrs.iterrows(): i.extend([k] * d.values[0]) df = pd.DataFrame() df["RGI_REG"] = i ax = sns.countplot(x="RGI_REG", data=df) """ Explanation: Some plots End of explanation """
bosscha/alma-calibrator
notebooks/2mass/15_allsky-with_gaia-Copy1.ipynb
gpl-2.0
cmd = "SELECT * FROM gaiadr2.gaia_source AS g, \ gaiadr2.tmass_best_neighbour AS tbest, \ gaiadr1.tmass_original_valid AS tmass \ WHERE g.source_id = tbest.source_id AND tbest.tmass_oid = tmass.tmass_oid \ AND pmra IS NOT NULL AND abs(pmra)<3 \ AND pmdec IS NOT NULL AND abs(pmdec)<3;" print(cmd) job1 = Gaia.launch_job_async(cmd, dump_to_file=True) print (job1) gaia_2mass = job1.get_results() print(len(gaia_2mass['source_id'])) print(gaia_2mass['ra', 'dec', 'ra_2', 'dec_2', 'phot_g_mean_mag', 'j_m']) """ Explanation: Get the data Try GAIA and 2MASS in gaiadr1 and gaiadr2 they also provide 2mass, allwise, sdss "best neigbour" pairs catalogs provided by GAIA: gaiadr1.gaiadr1.allwise_original_valid gaiadr1.gaiadr1.gsc23_original_valid gaiadr1.gaiadr1.ppmxl_original_valid gaiadr1.gaiadr1.sdssdr9_original_valid gaiadr1.gaiadr1.tmass_original_valid gaiadr1.gaiadr1.ucac4_original_valid gaiadr1.gaiadr1.urat1_original_valid End of explanation """ cmd = "SELECT * FROM gaiadr2.gaia_source AS g, \ gaiadr2.allwise_best_neighbour AS wbest, \ gaiadr1.allwise_original_valid AS allwise \ WHERE g.source_id = wbest.source_id AND wbest.allwise_oid = allwise.allwise_oid AND CONTAINS(POINT('ICRS',g.ra,g.dec),\ CIRCLE('ICRS'," + str(obj_ra) + "," + str(obj_dec) + "," + str(cone_radius) + "))=1;" print(cmd) job2 = Gaia.launch_job_async(cmd, dump_to_file=True) print(job2) gaia_wise = job2.get_results() print(len(gaia_wise['source_id'])) print(gaia_wise['ra', 'dec', 'ra_2', 'dec_2', 'phot_g_mean_mag']) """ Explanation: Try GAIA and WISE End of explanation """ sep_min = 1.0 * u.arcsec # minimum separation in arcsec # Using GAIA coord # ref_epoch: J2015.5 ra_2mass = gaia_2mass['ra'] dec_2mass = gaia_2mass['dec'] c_2mass = coordinates.SkyCoord(ra=ra_2mass, dec=dec_2mass, unit=(u.deg, u.deg), frame="icrs") ra_wise = gaia_wise['ra'] dec_wise = gaia_wise['dec'] c_wise = coordinates.SkyCoord(ra=ra_wise, dec=dec_wise, unit=(u.deg, u.deg), frame="icrs") idx_2mass1, idx_wise1, d2d, d3d = c_wise.search_around_sky(c_2mass, sep_min) # select only one nearest if there are more in the search reagion (minimum seperation parameter)! print("GAIA + 2MASS + WISE (using gaia coord): ", len(idx_2mass1)) ##### # Using 2MASS and WISE coord # ra_2 and dec_2 here are RA and DEC of 2MASS and WISE accordingly ra_2mass = gaia_2mass['ra_2'] dec_2mass = gaia_2mass['dec_2'] c_2mass = coordinates.SkyCoord(ra=ra_2mass, dec=dec_2mass, unit=(u.deg, u.deg), frame="icrs") ra_wise = gaia_wise['ra_2'] dec_wise = gaia_wise['dec_2'] c_wise = coordinates.SkyCoord(ra=ra_wise, dec=dec_wise, unit=(u.deg, u.deg), frame="icrs") idx_2mass2, idx_wise2, d2d, d3d = c_wise.search_around_sky(c_2mass, sep_min) # select only one nearest if there are more in the search reagion (minimum seperation parameter)! print("GAIA + 2MASS + WISE (using 2MASS-WISE coord): ", len(idx_2mass2)) print("Confusion level :", abs(len(idx_2mass1) - len(idx_2mass2))/3840. * 100, '%') # Combine dataset # GAIA-WISE # GAIA-2MASS # result of match with each other gaia_2mass___wise = gaia_2mass[idx_2mass2] gaia_wise___2mass = gaia_wise[idx_wise2] #Check if np.all(gaia_2mass___wise['solution_id'] == gaia_wise___2mass['solution_id']): # remove duplicating data # remove duplicating IDs in each dataset gaia_wise___2mass.remove_columns(['source_id_2', 'designation_2', 'allwise_oid_2']) gaia_2mass___wise.remove_columns(['source_id_2', 'designation_2', 'tmass_oid_2']) # remove gaia data from gaia_wise___2mas gaia_wise___2mass.remove_columns(['solution_id', 'designation', 'source_id', 'random_index', 'ref_epoch', 'ra', 'ra_error', 'dec', 'dec_error', 'parallax', 'parallax_error', 'parallax_over_error', 'pmra', 'pmra_error', 'pmdec', 'pmdec_error', 'ra_dec_corr', 'ra_parallax_corr', 'ra_pmra_corr', 'ra_pmdec_corr', 'dec_parallax_corr', 'dec_pmra_corr', 'dec_pmdec_corr', 'parallax_pmra_corr', 'parallax_pmdec_corr', 'pmra_pmdec_corr', 'astrometric_n_obs_al', 'astrometric_n_obs_ac', 'astrometric_n_good_obs_al', 'astrometric_n_bad_obs_al', 'astrometric_gof_al', 'astrometric_chi2_al', 'astrometric_excess_noise', 'astrometric_excess_noise_sig', 'astrometric_params_solved', 'astrometric_primary_flag', 'astrometric_weight_al', 'astrometric_pseudo_colour', 'astrometric_pseudo_colour_error', 'mean_varpi_factor_al', 'astrometric_matched_observations', 'visibility_periods_used', 'astrometric_sigma5d_max', 'frame_rotator_object_type', 'matched_observations', 'duplicated_source', 'phot_g_n_obs', 'phot_g_mean_flux', 'phot_g_mean_flux_error', 'phot_g_mean_flux_over_error', 'phot_g_mean_mag', 'phot_bp_n_obs', 'phot_bp_mean_flux', 'phot_bp_mean_flux_error', 'phot_bp_mean_flux_over_error', 'phot_bp_mean_mag', 'phot_rp_n_obs', 'phot_rp_mean_flux', 'phot_rp_mean_flux_error', 'phot_rp_mean_flux_over_error', 'phot_rp_mean_mag', 'phot_bp_rp_excess_factor', 'phot_proc_mode', 'bp_rp', 'bp_g', 'g_rp', 'radial_velocity', 'radial_velocity_error', 'rv_nb_transits', 'rv_template_teff', 'rv_template_logg', 'rv_template_fe_h', 'phot_variable_flag', 'l', 'b', 'ecl_lon', 'ecl_lat', 'priam_flags', 'teff_val', 'teff_percentile_lower', 'teff_percentile_upper', 'a_g_val', 'a_g_percentile_lower', 'a_g_percentile_upper', 'e_bp_min_rp_val', 'e_bp_min_rp_percentile_lower', 'e_bp_min_rp_percentile_upper', 'flame_flags', 'radius_val', 'radius_percentile_lower', 'radius_percentile_upper', 'lum_val', 'lum_percentile_lower', 'lum_percentile_upper', 'datalink_url', 'epoch_photometry_url']) # merge (hstack) gaia_2mass_wise = hstack([gaia_2mass___wise, gaia_wise___2mass], table_names=['2mass', 'wise'], uniq_col_name='{table_name}_{col_name}') print("Merge...") print(len(gaia_2mass_wise)) else: print("Big Error: not match") print(gaia_2mass_wise.colnames) # Make a sample of galaxy using W1-J cut w1j = gaia_2mass_wise['w1mpro'] - gaia_2mass_wise['j_m'] cutw1j = -1.7 galaxy_sample = gaia_2mass_wise[w1j<cutw1j] # Make a sample of star using large proper motion cut1 = gaia_2mass_wise[gaia_2mass_wise['pmra'] > 2] star_sample = gaia_2mass_wise[gaia_2mass_wise['pmdec'] > 2] """ Explanation: Combine End of explanation """ plt.scatter(gaia_2mass_wise['w1mpro'] - gaia_2mass_wise['j_m'], gaia_2mass_wise['j_m'], marker='.', color='gray', alpha=0.9) plt.scatter(galaxy_sample['w1mpro'] - galaxy_sample['j_m'], galaxy_sample['j_m'], marker='s', color='red', alpha=0.1) plt.scatter(star_sample['w1mpro'] - star_sample['j_m'], star_sample['j_m'], marker='o', color='blue', alpha=0.1) plt.gca().invert_yaxis() # list of parameters params = ['j_m', 'h_m', 'ks_m', 'w1mpro', 'w2mpro', 'w3mpro', 'w4mpro', 'phot_g_mean_mag', 'phot_bp_mean_mag', 'phot_rp_mean_mag'] ## check Masked value # unmasked value = 0 # NaN, INF ma_p = np.zeros(len(params)) for i,p in enumerate(params): for data in gaia_2mass_wise[p]: if data is ma.masked: ma_p[i] += 1 print(p, ma_p[i]) 58/3730. np.mean(gaia_2mass_wise['phot_bp_mean_mag']) np.where(gaia_2mass_wise['phot_bp_mean_mag'] == ma.masked) maske = gaia_2mass_wise['phot_bp_mean_mag'][gaia_2mass_wise['phot_bp_mean_mag'] == ma.masked] print(maske) maske.data x = np.array([1, 2, 3, -1, 5]) mx = ma.masked_array(x, mask=[0, 0, 0, 1, 0]) mx mx.data np.mean(mx.data) np.mean(mx) print(mx) print(x) a = np.copy(maske) maske print(a) print(mx) print(x) """ Explanation: Plot W1-J vs J End of explanation """
jc091/deep-learning
first-neural-network/.ipynb_checkpoints/DLND Your first neural network-checkpoint.ipynb
mit
%matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt """ Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and the model more. End of explanation """ data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head() """ Explanation: Load and prepare the data A critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! End of explanation """ rides[:24*10].plot(x='dteday', y='cnt') """ Explanation: Checking out the data This dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the cnt column. You can see the first few rows of the data above. Below is a plot showing the number of bike riders over the first 10 days or so in the data set. (Some days don't have exactly 24 entries in the data set, so it's not exactly 10 days.) You can see the hourly rentals here. This data is pretty complicated! The weekends have lower over all ridership and there are spikes when people are biking to and from work during the week. Looking at the data above, we also have information about temperature, humidity, and windspeed, all of these likely affecting the number of riders. You'll be trying to capture all this with your model. End of explanation """ dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday'] for dummy_field in dummy_fields: dummies = pd.get_dummies(rides[dummy_field], prefix=dummy_field, drop_first=False) rides = pd.concat([rides, dummies], axis=1) fields_to_drop = ['instant', 'dteday', 'season', 'weathersit', 'weekday', 'atemp', 'mnth', 'workingday', 'hr'] data = rides.drop(fields_to_drop, axis=1) data.head() data.size """ Explanation: Dummy variables Here we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to get_dummies(). End of explanation """ quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed'] # Store scalings in a dictionary so we can convert back later scaled_features = {} for quant_feature in quant_features: mean, std = data[quant_feature].mean(), data[quant_feature].std() scaled_features[quant_feature] = [mean, std] data.loc[:, quant_feature] = (data[quant_feature] - mean)/std """ Explanation: Scaling target variables To make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1. The scaling factors are saved so we can go backwards when we use the network for predictions. End of explanation """ # Save data for approximately the last 21 days test_data = data[-21*24:] # Now remove the test data from the data set data = data[:-21*24] # Separate the data into features and targets target_fields = ['cnt', 'casual', 'registered'] features, targets = data.drop(target_fields, axis=1), data[target_fields] test_features, test_targets = test_data.drop(target_fields, axis=1), test_data[target_fields] """ Explanation: Splitting the data into training, testing, and validation sets We'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders. End of explanation """ # Hold out the last 60 days or so of the remaining data as a validation set train_features, train_targets = features[:-60*24], targets[:-60*24] val_features, val_targets = features[-60*24:], targets[-60*24:] """ Explanation: We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). End of explanation """ class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes # Initialize weights self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5, (self.input_nodes, self.hidden_nodes)) self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5, (self.hidden_nodes, self.output_nodes)) self.lr = learning_rate #### TODO: Set self.activation_function to your implemented sigmoid function #### # # Note: in Python, you can define a function with a lambda expression, # as shown below. self.activation_function = lambda x : 1 / (1 + np.exp(-x)) def train(self, features, targets): ''' Train the network on batch of features and targets. Arguments --------- features: 2D array, each row is one data record, each column is a feature targets: 1D array of target values ''' n_records = features.shape[0] delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape) delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape) for X, y in zip(features, targets): #### Implement the forward pass here #### ### Forward pass ### # TODO: Hidden layer - Replace these values with your calculations. hidden_inputs = np.dot(X, self.weights_input_to_hidden) # signals into hidden layer hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer # TODO: Output layer - Replace these values with your calculations. final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) # signals into final output layer final_outputs = final_inputs # signals from final output layer #### Implement the backward pass here #### ### Backward pass ### # TODO: Output error - Replace this value with your calculations. error = y - final_outputs # Output layer error is the difference between desired target and actual output. # TODO: Calculate the hidden layer's contribution to the error hidden_error = np.dot(self.weights_hidden_to_output, error) # TODO: Backpropagated error terms - Replace these values with your calculations. output_error_term = error * 1 hidden_error_term = hidden_error * hidden_outputs * (1 - hidden_outputs) # Weight step (hidden to output) delta_weights_h_o += output_error_term * hidden_outputs[:, None] # Weight step (input to hidden) delta_weights_i_h += hidden_error_term * X[:, None] # TODO: Update the weights - Replace these values with your calculations. self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records # update hidden-to-output weights with gradient descent step self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records # update input-to-hidden weights with gradient descent step def run(self, features): ''' Run a forward pass through the network with input features Arguments --------- features: 1D array of feature values ''' #### Implement the forward pass here #### # TODO: Hidden layer - replace these values with the appropriate calculations. hidden_inputs = np.dot(features, self.weights_input_to_hidden) # signals into hidden layer hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer # TODO: Output layer - Replace these values with the appropriate calculations. final_inputs = np.dot(hidden_outputs, self.weights_hidden_to_output) # signals into final output layer final_outputs = final_inputs # signals from final output layer return final_outputs def MSE(y, Y): return np.mean((y-Y)**2) """ Explanation: Time to build the network Below you'll build your network. We've built out the structure and the backwards pass. You'll implement the forward pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes. <img src="assets/neural_network.png" width=300px> The network has two layers, a hidden layer and an output layer. The hidden layer will use the sigmoid function for activations. The output layer has only one node and is used for the regression, the output of the node is the same as the input of the node. That is, the activation function is $f(x)=x$. A function that takes the input signal and generates an output signal, but takes into account the threshold, is called an activation function. We work through each layer of our network calculating the outputs for each neuron. All of the outputs from one layer become inputs to the neurons on the next layer. This process is called forward propagation. We use the weights to propagate signals forward from the input to the output layers in a neural network. We use the weights to also propagate error backwards from the output back into the network to update our weights. This is called backpropagation. Hint: You'll need the derivative of the output activation function ($f(x) = x$) for the backpropagation implementation. If you aren't familiar with calculus, this function is equivalent to the equation $y = x$. What is the slope of that equation? That is the derivative of $f(x)$. Below, you have these tasks: 1. Implement the sigmoid function to use as the activation function. Set self.activation_function in __init__ to your sigmoid function. 2. Implement the forward pass in the train method. 3. Implement the backpropagation algorithm in the train method, including calculating the output error. 4. Implement the forward pass in the run method. End of explanation """ import unittest inputs = np.array([[0.5, -0.2, 0.1]]) targets = np.array([[0.4]]) test_w_i_h = np.array([[0.1, -0.2], [0.4, 0.5], [-0.3, 0.2]]) test_w_h_o = np.array([[0.3], [-0.1]]) class TestMethods(unittest.TestCase): ########## # Unit tests for data loading ########## def test_data_path(self): # Test that file path to dataset has been unaltered self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv') def test_data_loaded(self): # Test that data frame loaded self.assertTrue(isinstance(rides, pd.DataFrame)) ########## # Unit tests for network functionality ########## def test_activation(self): network = NeuralNetwork(3, 2, 1, 0.5) # Test that the activation function is a sigmoid self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5)))) def test_train(self): # Test that weights are updated correctly on training network = NeuralNetwork(3, 2, 1, 0.5) network.weights_input_to_hidden = test_w_i_h.copy() network.weights_hidden_to_output = test_w_h_o.copy() network.train(inputs, targets) self.assertTrue(np.allclose(network.weights_hidden_to_output, np.array([[ 0.37275328], [-0.03172939]]))) self.assertTrue(np.allclose(network.weights_input_to_hidden, np.array([[ 0.10562014, -0.20185996], [0.39775194, 0.50074398], [-0.29887597, 0.19962801]]))) def test_run(self): # Test correctness of run method network = NeuralNetwork(3, 2, 1, 0.5) network.weights_input_to_hidden = test_w_i_h.copy() network.weights_hidden_to_output = test_w_h_o.copy() self.assertTrue(np.allclose(network.run(inputs), 0.09998924)) suite = unittest.TestLoader().loadTestsFromModule(TestMethods()) unittest.TextTestRunner().run(suite) """ Explanation: Unit tests Run these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project. End of explanation """ import sys ### Set the hyperparameters here ### iterations = 5000 learning_rate = 0.4 hidden_nodes = 30 output_nodes = 1 N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {'train':[], 'validation':[]} for ii in range(iterations): # Go through a random batch of 128 records from the training data set batch = np.random.choice(train_features.index, size=128) X, y = train_features.ix[batch].values, train_targets.ix[batch]['cnt'] network.train(X, y) # Printing out the training progress train_loss = MSE(network.run(train_features).T, train_targets['cnt'].values) val_loss = MSE(network.run(val_features).T, val_targets['cnt'].values) sys.stdout.write("\rProgress: {:2.1f}".format(100 * ii/float(iterations)) \ + "% ... Training loss: " + str(train_loss)[:5] \ + " ... Validation loss: " + str(val_loss)[:5]) sys.stdout.flush() losses['train'].append(train_loss) losses['validation'].append(val_loss) plt.plot(losses['train'], label='Training loss') plt.plot(losses['validation'], label='Validation loss') plt.legend() _ = plt.ylim() """ Explanation: Training the network Here you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training set and will fail to generalize to the validation set. That is, the loss on the validation set will start increasing as the training set loss drops. You'll also be using a method know as Stochastic Gradient Descent (SGD) to train the network. The idea is that for each training pass, you grab a random sample of the data instead of using the whole data set. You use many more training passes than with normal gradient descent, but each pass is much faster. This ends up training the network more efficiently. You'll learn more about SGD later. Choose the number of iterations This is the number of batches of samples from the training data we'll use to train the network. The more iterations you use, the better the model will fit the data. However, if you use too many iterations, then the model with not generalize well to other data, this is called overfitting. You want to find a number here where the network has a low training loss, and the validation loss is at a minimum. As you start overfitting, you'll see the training loss continue to decrease while the validation loss starts to increase. Choose the learning rate This scales the size of weight updates. If this is too big, the weights tend to explode and the network fails to fit the data. A good choice to start at is 0.1. If the network has problems fitting the data, try reducing the learning rate. Note that the lower the learning rate, the smaller the steps are in the weight updates and the longer it takes for the neural network to converge. Choose the number of hidden nodes The more hidden nodes you have, the more accurate predictions the model will make. Try a few different numbers and see how it affects the performance. You can look at the losses dictionary for a metric of the network performance. If the number of hidden units is too low, then the model won't have enough space to learn and if it is too high there are too many options for the direction that the learning can take. The trick here is to find the right balance in number of hidden units you choose. End of explanation """ fig, ax = plt.subplots(figsize=(8,4)) mean, std = scaled_features['cnt'] predictions = network.run(test_features).T*std + mean ax.plot(predictions[0], label='Prediction') ax.plot((test_targets['cnt']*std + mean).values, label='Data') ax.set_xlim(right=len(predictions)) ax.legend() dates = pd.to_datetime(rides.ix[test_data.index]['dteday']) dates = dates.apply(lambda d: d.strftime('%b %d')) ax.set_xticks(np.arange(len(dates))[12::24]) _ = ax.set_xticklabels(dates[12::24], rotation=45) """ Explanation: Check out your predictions Here, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly. End of explanation """
metpy/MetPy
v0.10/_downloads/56e68110d2faf6be8284d896c8f4cd23/Natural_Neighbor_Verification.ipynb
bsd-3-clause
import matplotlib.pyplot as plt import numpy as np from scipy.spatial import ConvexHull, Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d from scipy.spatial.distance import euclidean from metpy.interpolate import geometry from metpy.interpolate.points import natural_neighbor_point """ Explanation: Natural Neighbor Verification Walks through the steps of Natural Neighbor interpolation to validate that the algorithmic approach taken in MetPy is correct. Find natural neighbors visual test A triangle is a natural neighbor for a point if the circumscribed circle &lt;https://en.wikipedia.org/wiki/Circumscribed_circle&gt;_ of the triangle contains that point. It is important that we correctly grab the correct triangles for each point before proceeding with the interpolation. Algorithmically: We place all of the grid points in a KDTree. These provide worst-case O(n) time complexity for spatial searches. We generate a Delaunay Triangulation &lt;https://docs.scipy.org/doc/scipy/ reference/tutorial/spatial.html#delaunay-triangulations&gt;_ using the locations of the provided observations. For each triangle, we calculate its circumcenter and circumradius. Using KDTree, we then assign each grid a triangle that has a circumcenter within a circumradius of the grid's location. The resulting dictionary uses the grid index as a key and a set of natural neighbor triangles in the form of triangle codes from the Delaunay triangulation. This dictionary is then iterated through to calculate interpolation values. We then traverse the ordered natural neighbor edge vertices for a particular grid cell in groups of 3 (n - 1, n, n + 1), and perform calculations to generate proportional polygon areas. Circumcenter of (n - 1), n, grid_location Circumcenter of (n + 1), n, grid_location Determine what existing circumcenters (ie, Delaunay circumcenters) are associated with vertex n, and add those as polygon vertices. Calculate the area of this polygon. Increment the current edges to be checked, i.e.: n - 1 = n, n = n + 1, n + 1 = n + 2 Repeat steps 5 & 6 until all of the edge combinations of 3 have been visited. Repeat steps 4 through 7 for each grid cell. End of explanation """ np.random.seed(100) pts = np.random.randint(0, 100, (10, 2)) xp = pts[:, 0] yp = pts[:, 1] zp = (pts[:, 0] * pts[:, 0]) / 1000 tri = Delaunay(pts) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) ax.ishold = lambda: True # Work-around for Matplotlib 3.0.0 incompatibility delaunay_plot_2d(tri, ax=ax) for i, zval in enumerate(zp): ax.annotate('{} F'.format(zval), xy=(pts[i, 0] + 2, pts[i, 1])) sim_gridx = [30., 60.] sim_gridy = [30., 60.] ax.plot(sim_gridx, sim_gridy, '+', markersize=10) ax.set_aspect('equal', 'datalim') ax.set_title('Triangulation of observations and test grid cell ' 'natural neighbor interpolation values') members, tri_info = geometry.find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy))) val = natural_neighbor_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0], tri_info) ax.annotate('grid 0: {:.3f}'.format(val), xy=(sim_gridx[0] + 2, sim_gridy[0])) val = natural_neighbor_point(xp, yp, zp, (sim_gridx[1], sim_gridy[1]), tri, members[1], tri_info) ax.annotate('grid 1: {:.3f}'.format(val), xy=(sim_gridx[1] + 2, sim_gridy[1])) """ Explanation: For a test case, we generate 10 random points and observations, where the observation values are just the x coordinate value times the y coordinate value divided by 1000. We then create two test points (grid 0 & grid 1) at which we want to estimate a value using natural neighbor interpolation. The locations of these observations are then used to generate a Delaunay triangulation. End of explanation """ def draw_circle(ax, x, y, r, m, label): th = np.linspace(0, 2 * np.pi, 100) nx = x + r * np.cos(th) ny = y + r * np.sin(th) ax.plot(nx, ny, m, label=label) members, tri_info = geometry.find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy))) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) ax.ishold = lambda: True # Work-around for Matplotlib 3.0.0 incompatibility delaunay_plot_2d(tri, ax=ax) ax.plot(sim_gridx, sim_gridy, 'ks', markersize=10) for i, info in tri_info.items(): x_t = info['cc'][0] y_t = info['cc'][1] if i in members[1] and i in members[0]: draw_circle(ax, x_t, y_t, info['r'], 'm-', str(i) + ': grid 1 & 2') ax.annotate(str(i), xy=(x_t, y_t), fontsize=15) elif i in members[0]: draw_circle(ax, x_t, y_t, info['r'], 'r-', str(i) + ': grid 0') ax.annotate(str(i), xy=(x_t, y_t), fontsize=15) elif i in members[1]: draw_circle(ax, x_t, y_t, info['r'], 'b-', str(i) + ': grid 1') ax.annotate(str(i), xy=(x_t, y_t), fontsize=15) else: draw_circle(ax, x_t, y_t, info['r'], 'k:', str(i) + ': no match') ax.annotate(str(i), xy=(x_t, y_t), fontsize=9) ax.set_aspect('equal', 'datalim') ax.legend() """ Explanation: Using the circumcenter and circumcircle radius information from :func:metpy.interpolate.geometry.find_natural_neighbors, we can visually examine the results to see if they are correct. End of explanation """ x_t, y_t = tri_info[8]['cc'] r = tri_info[8]['r'] print('Distance between grid0 and Triangle 8 circumcenter:', euclidean([x_t, y_t], [sim_gridx[0], sim_gridy[0]])) print('Triangle 8 circumradius:', r) """ Explanation: What?....the circle from triangle 8 looks pretty darn close. Why isn't grid 0 included in that circle? End of explanation """ cc = np.array([tri_info[m]['cc'] for m in members[0]]) r = np.array([tri_info[m]['r'] for m in members[0]]) print('circumcenters:\n', cc) print('radii\n', r) """ Explanation: Lets do a manual check of the above interpolation value for grid 0 (southernmost grid) Grab the circumcenters and radii for natural neighbors End of explanation """ vor = Voronoi(list(zip(xp, yp))) fig, ax = plt.subplots(1, 1, figsize=(15, 10)) ax.ishold = lambda: True # Work-around for Matplotlib 3.0.0 incompatibility voronoi_plot_2d(vor, ax=ax) nn_ind = np.array([0, 5, 7, 8]) z_0 = zp[nn_ind] x_0 = xp[nn_ind] y_0 = yp[nn_ind] for x, y, z in zip(x_0, y_0, z_0): ax.annotate('{}, {}: {:.3f} F'.format(x, y, z), xy=(x, y)) ax.plot(sim_gridx[0], sim_gridy[0], 'k+', markersize=10) ax.annotate('{}, {}'.format(sim_gridx[0], sim_gridy[0]), xy=(sim_gridx[0] + 2, sim_gridy[0])) ax.plot(cc[:, 0], cc[:, 1], 'ks', markersize=15, fillstyle='none', label='natural neighbor\ncircumcenters') for center in cc: ax.annotate('{:.3f}, {:.3f}'.format(center[0], center[1]), xy=(center[0] + 1, center[1] + 1)) tris = tri.points[tri.simplices[members[0]]] for triangle in tris: x = [triangle[0, 0], triangle[1, 0], triangle[2, 0], triangle[0, 0]] y = [triangle[0, 1], triangle[1, 1], triangle[2, 1], triangle[0, 1]] ax.plot(x, y, ':', linewidth=2) ax.legend() ax.set_aspect('equal', 'datalim') def draw_polygon_with_info(ax, polygon, off_x=0, off_y=0): """Draw one of the natural neighbor polygons with some information.""" pts = np.array(polygon)[ConvexHull(polygon).vertices] for i, pt in enumerate(pts): ax.plot([pt[0], pts[(i + 1) % len(pts)][0]], [pt[1], pts[(i + 1) % len(pts)][1]], 'k-') avex, avey = np.mean(pts, axis=0) ax.annotate('area: {:.3f}'.format(geometry.area(pts)), xy=(avex + off_x, avey + off_y), fontsize=12) cc1 = geometry.circumcenter((53, 66), (15, 60), (30, 30)) cc2 = geometry.circumcenter((34, 24), (53, 66), (30, 30)) draw_polygon_with_info(ax, [cc[0], cc1, cc2]) cc1 = geometry.circumcenter((53, 66), (15, 60), (30, 30)) cc2 = geometry.circumcenter((15, 60), (8, 24), (30, 30)) draw_polygon_with_info(ax, [cc[0], cc[1], cc1, cc2], off_x=-9, off_y=3) cc1 = geometry.circumcenter((8, 24), (34, 24), (30, 30)) cc2 = geometry.circumcenter((15, 60), (8, 24), (30, 30)) draw_polygon_with_info(ax, [cc[1], cc1, cc2], off_x=-15) cc1 = geometry.circumcenter((8, 24), (34, 24), (30, 30)) cc2 = geometry.circumcenter((34, 24), (53, 66), (30, 30)) draw_polygon_with_info(ax, [cc[0], cc[1], cc1, cc2]) """ Explanation: Draw the natural neighbor triangles and their circumcenters. Also plot a Voronoi diagram &lt;https://docs.scipy.org/doc/scipy/reference/tutorial/spatial.html#voronoi-diagrams&gt;_ which serves as a complementary (but not necessary) spatial data structure that we use here simply to show areal ratios. Notice that the two natural neighbor triangle circumcenters are also vertices in the Voronoi plot (green dots), and the observations are in the polygons (blue dots). End of explanation """ areas = np.array([60.434, 448.296, 25.916, 70.647]) values = np.array([0.064, 1.156, 2.809, 0.225]) total_area = np.sum(areas) print(total_area) """ Explanation: Put all of the generated polygon areas and their affiliated values in arrays. Calculate the total area of all of the generated polygons. End of explanation """ proportions = areas / total_area print(proportions) """ Explanation: For each polygon area, calculate its percent of total area. End of explanation """ contributions = proportions * values print(contributions) """ Explanation: Multiply the percent of total area by the respective values. End of explanation """ interpolation_value = np.sum(contributions) function_output = natural_neighbor_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0], tri_info) print(interpolation_value, function_output) """ Explanation: The sum of this array is the interpolation value! End of explanation """ plt.show() """ Explanation: The values are slightly different due to truncating the area values in the above visual example to the 3rd decimal place. End of explanation """
marcinofulus/teaching
Python4physicists_SS2017/numpy_analiza_matematyczna.ipynb
gpl-3.0
import numpy as np x = np.linspace(1,8,5) x.shape y = np.sin(x) y.shape for i in range(y.shape[0]-1): print( (y[i+1]-y[i]),(y[i+1]-y[i])/(x[i+1]-x[i])) y[1:]-y[:-1] y[1:] (y[1:]-y[:-1])/(x[1:]-x[:-1]) np.diff(y) np.diff(x) np.roll(y,-1) y np.gradient(y) import sympy X = sympy.Symbol('X') expr = (sympy.sin(X**2+1*sympy.cos(sympy.exp(X)))).diff(X) expr f = sympy.lambdify(X,expr,"numpy") f( np.array([1,2,3])) import ipywidgets as widgets from ipywidgets import interact widgets.IntSlider? @interact(x=widgets.IntSlider(1,2,10,1)) def g(x=1): print(x) """ Explanation: http://www.scipy-lectures.org/ End of explanation """ import numpy as np N = 10 x = np.linspace( 0,np.pi*1.23, N) f = np.sin(x) x,f np.diff(x) np.sum(f[:-1]*np.diff(x)) w = np.ones_like(x) h = np.diff(x)[0] w[-1] = 0 h*np.sum(w*f) w[0] = 0.5 w[-1] = 0.5 h*np.sum(w*f) import scipy.integrate scipy.integrate. """ Explanation: Całka oznaczona $$\int_a^b f(x) dx = \lim_{n\to\infty} \sum_{i=1}^{n} f(\hat x_i) \Delta x_i$$ End of explanation """ np.cumsum(f)*h np.sum(f)*h f.shape,np.cumsum(f).shape """ Explanation: Całka nieoznaczona $$\int_a^x f(y) dy = \lim_{n\to\infty} \sum_{i=1}^{n} f(\hat y_i) \Delta y_i$$ End of explanation """ x = np.linspace(0,2,50) y = np.linspace(0,2,50) X,Y = np.meshgrid(x,y,indexing='xy') X F = np.sin(X**2 + Y) F[1,2],X[1,2],Y[1,2] %matplotlib inline import matplotlib.pyplot as plt plt.contour(X,Y,F) plt.imshow(F,origin='lower') np.diff(F,axis=1).shape np.diff(F,2,axis=0).shape """ Explanation: Pochodne funkcji wielu zmiennych End of explanation """
anhiga/poliastro
docs/source/examples/Catch that asteroid!.ipynb
mit
import matplotlib.pyplot as plt plt.ion() from astropy import units as u from astropy.time import Time from astropy.utils.data import conf conf.dataurl conf.remote_timeout """ Explanation: Catch that asteroid! End of explanation """ conf.remote_timeout = 10000 from astropy.coordinates import solar_system_ephemeris solar_system_ephemeris.set("jpl") from poliastro.bodies import * from poliastro.twobody import Orbit from poliastro.plotting import OrbitPlotter, plot EPOCH = Time("2017-09-01 12:05:50", scale="tdb") earth = Orbit.from_body_ephem(Earth, EPOCH) earth plot(earth, label=Earth) from poliastro.neos import neows florence = neows.orbit_from_name("Florence") florence """ Explanation: First, we need to increase the timeout time to allow the download of data occur properly End of explanation """ florence.epoch florence.epoch.iso florence.inc """ Explanation: Two problems: the epoch is not the one we desire, and the inclination is with respect to the ecliptic! End of explanation """ florence = florence.propagate(EPOCH) florence.epoch.tdb.iso """ Explanation: We first propagate: End of explanation """ from astropy.coordinates import ( ICRS, GCRS, CartesianRepresentation, CartesianDifferential ) from poliastro.frames import HeliocentricEclipticJ2000 """ Explanation: And now we have to convert to another reference frame, using http://docs.astropy.org/en/stable/coordinates/. End of explanation """ florence_heclip = HeliocentricEclipticJ2000( x=florence.r[0], y=florence.r[1], z=florence.r[2], v_x=florence.v[0], v_y=florence.v[1], v_z=florence.v[2], representation=CartesianRepresentation, differential_type=CartesianDifferential, obstime=EPOCH ) florence_heclip """ Explanation: The NASA servers give the orbital elements of the asteroids in an Heliocentric Ecliptic frame. Fortunately, it is already defined in Astropy: End of explanation """ florence_icrs_trans = florence_heclip.transform_to(ICRS) florence_icrs_trans.representation = CartesianRepresentation florence_icrs_trans florence_icrs = Orbit.from_vectors( Sun, r=[florence_icrs_trans.x, florence_icrs_trans.y, florence_icrs_trans.z] * u.km, v=[florence_icrs_trans.v_x, florence_icrs_trans.v_y, florence_icrs_trans.v_z] * (u.km / u.s), epoch=florence.epoch ) florence_icrs florence_icrs.rv() """ Explanation: Now we just have to convert to ICRS, which is the "standard" reference in which poliastro works: End of explanation """ from poliastro.util import norm norm(florence_icrs.r - earth.r) - Earth.R """ Explanation: Let us compute the distance between Florence and the Earth: End of explanation """ from IPython.display import HTML HTML( """<blockquote class="twitter-tweet" data-lang="en"><p lang="es" dir="ltr">La <a href="https://twitter.com/esa_es">@esa_es</a> ha preparado un resumen del asteroide <a href="https://twitter.com/hashtag/Florence?src=hash">#Florence</a> 😍 <a href="https://t.co/Sk1lb7Kz0j">pic.twitter.com/Sk1lb7Kz0j</a></p>&mdash; AeroPython (@AeroPython) <a href="https://twitter.com/AeroPython/status/903197147914543105">August 31, 2017</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>""" ) """ Explanation: <div class="alert alert-success">This value is consistent with what ESA says! $7\,060\,160$ km</div> End of explanation """ frame = OrbitPlotter() frame.plot(earth, label="Earth") frame.plot(Orbit.from_body_ephem(Mars, EPOCH)) frame.plot(Orbit.from_body_ephem(Venus, EPOCH)) frame.plot(Orbit.from_body_ephem(Mercury, EPOCH)) frame.plot(florence_icrs, label="Florence") """ Explanation: And now we can plot! End of explanation """ frame = OrbitPlotter() frame.plot(earth, label="Earth") frame.plot(florence, label="Florence (Ecliptic)") frame.plot(florence_icrs, label="Florence (ICRS)") """ Explanation: The difference between doing it well and doing it wrong is clearly visible: End of explanation """ florence_gcrs_trans = florence_heclip.transform_to(GCRS(obstime=EPOCH)) florence_gcrs_trans.representation = CartesianRepresentation florence_gcrs_trans florence_hyper = Orbit.from_vectors( Earth, r=[florence_gcrs_trans.x, florence_gcrs_trans.y, florence_gcrs_trans.z] * u.km, v=[florence_gcrs_trans.v_x, florence_gcrs_trans.v_y, florence_gcrs_trans.v_z] * (u.km / u.s), epoch=EPOCH ) florence_hyper """ Explanation: And now let's do something more complicated: express our orbit with respect to the Earth! For that, we will use GCRS, with care of setting the correct observation time: End of explanation """ moon = Orbit.from_body_ephem(Moon, EPOCH) moon moon.a moon.ecc """ Explanation: Notice that the ephemerides of the Moon is also given in ICRS, and therefore yields a weird hyperbolic orbit! End of explanation """ moon_icrs = ICRS( x=moon.r[0], y=moon.r[1], z=moon.r[2], v_x=moon.v[0], v_y=moon.v[1], v_z=moon.v[2], representation=CartesianRepresentation, differential_type=CartesianDifferential ) moon_icrs moon_gcrs = moon_icrs.transform_to(GCRS(obstime=EPOCH)) moon_gcrs.representation = CartesianRepresentation moon_gcrs moon = Orbit.from_vectors( Earth, [moon_gcrs.x, moon_gcrs.y, moon_gcrs.z] * u.km, [moon_gcrs.v_x, moon_gcrs.v_y, moon_gcrs.v_z] * (u.km / u.s), epoch=EPOCH ) moon """ Explanation: So we have to convert again. End of explanation """ plot(moon, label=Moon) plt.gcf().autofmt_xdate() """ Explanation: And finally, we plot the Moon: End of explanation """ frame = OrbitPlotter() # This first plot sets the frame frame.plot(florence_hyper, label="Florence") # And then we add the Moon frame.plot(moon, label=Moon) plt.xlim(-1000000, 8000000) plt.ylim(-5000000, 5000000) plt.gcf().autofmt_xdate() """ Explanation: And now for the final plot: End of explanation """
james-prior/euler
euler-018-maximum-path-sum-i-20170902.ipynb
mit
t4 = [ [3], [7, 4], [2, 4, 6], [8, 5, 9, 3], ] t4 t15 = [ [75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23], ] len(t15) from copy import deepcopy def foo(t): t = deepcopy(t) for i in range(len(t))[::-1]: r = t[i] try: nr = t[i+1] except IndexError: for j in range(len(t[i])): t[i][j] = (t[i][j], None) else: for j in range(len(t[i])): dir = (t[i+1][j+1][0] > t[i+1][j+0][0]) t[i][j] = (t[i][j] + t[i+1][j+dir][0], dir) return t[0][0][0] n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: Project Euler Maximum path sum I Problem 18 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. <style TYPE="text/css"> p { text-align: center } </style> <p> **3** **7** 4 2 **4** 6 8 5 **9** 3 </p> That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: <center> 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 </center> NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o) End of explanation """ def foo(t): old_row = [] for row in t: stagger_max = map(max, zip([0] + old_row, old_row + [0])) old_row = list(map(sum, zip(stagger_max, row))) return max(old_row) n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: Let's try a somewhat functional approach. It is much easier to understand. I like that. End of explanation """ def foo(t): old_row = tuple() for row in t: stagger_max = map(max, zip((0,) + old_row, old_row + (0,))) old_row = tuple(map(sum, zip(stagger_max, row))) return max(old_row) n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: Try tuples instead of lists. It's a little bit faster and still readable. That's a good combination. End of explanation """ t4 = tuple(tuple(row) for row in t4) t15 = tuple(tuple(row) for row in t15) def foo(t): old_row = tuple() for row in t: stagger_max = map(max, zip((0,) + old_row, old_row + (0,))) old_row = tuple(map(sum, zip(stagger_max, row))) return max(old_row) n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: Convert t4 and t15 to be tuples instead of lists. This does not affect readability. It is faster yet. End of explanation """ def foo(t): old_row = tuple() for row in t: old_row = tuple(map(sum, zip( map(max, zip((0,) + old_row, old_row + (0,))), row))) return max(old_row) n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: I like cell 7 the most. For me, its lists are more readable than tuples. 2017-09-02 Now I play some more. First, Consolidate the body of the loop into a single ugly long statement. It is a little bit faster. End of explanation """ def goo(t): *upper_rows, bottom_row = t if not upper_rows: return tuple(bottom_row) maximums = goo(upper_rows) stagger_max = map(max, zip((0,) + maximums, maximums + (0,))) return tuple(map(sum, zip(stagger_max, bottom_row))) def foo(t): return max(goo(t)) n = t4 %timeit foo(n) foo(n) n = t15 %timeit foo(n) foo(n) """ Explanation: Next, eliminate the loop by using recursion. This code is much harder for me to understand. It is slower also. It was good exercise to play with replacing a loop with recursion. Functional programming fans should like it. End of explanation """
batfish/pybatfish
docs/source/notebooks/configProperties.ipynb
apache-2.0
bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Configuration Properties This category of questions enables you to retrieve and process the contents of device configurations in a vendor-agnostic manner (except where the question itself is vendor-specific). Batfish organizes configuration content into several sub-categories. Node Properties Interface Properties BGP Process Configuration BGP Peer Configuration HSRP Properties OSPF Process Configuration OSPF Interface Configuration OSPF Area Configuration Multi-chassis LAG IP Owners Named Structures Defined Structures Referenced Structures Undefined References Unused Structures VLAN Properties VRRP Properties A10 Virtual Server Configuration F5 BIG-IP VIP Configuration End of explanation """ result = bf.q.nodeProperties().answer().frame() """ Explanation: Node Properties Returns configuration settings of nodes. Lists global settings of devices in the network. Settings that are specific to interfaces, routing protocols, etc. are available via other questions. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | properties | Include properties matching this regex. | NodePropertySpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str AS_Path_Access_Lists | Names of AS path access lists | Set of str Authentication_Key_Chains | Names of authentication keychains | Set of str Community_Match_Exprs | Names of expressions for matching a community | Set of str Community_Set_Exprs | Names of expressions representing a community-set | Set of str Community_Set_Match_Exprs | Names of expressions for matching a ommunity-set | Set of str Community_Sets | Names of community-sets | Set of str Configuration_Format | Configuration format of the node | str DNS_Servers | Configured DNS servers | Set of str DNS_Source_Interface | Source interface to use for communicating with DNS servers | str Default_Cross_Zone_Action | Default action (PERMIT, DENY) for traffic that traverses firewall zones (null for non-firewall nodes) | str Default_Inbound_Action | Default action (PERMIT, DENY) for traffic destined for this node | str Domain_Name | Domain name of the node | str Hostname | Hostname of the node | str IKE_Phase1_Keys | Names of IKE Phase 1 keys | Set of str IKE_Phase1_Policies | Names of IKE Phase 1 policies | Set of str IKE_Phase1_Proposals | Names of IKE Phase 1 proposals | Set of str IP6_Access_Lists | Names of IPv6 filters (ACLs, firewall rule sets) | Set of str IP_Access_Lists | Names of IPv4 filters (ACLs, firewall rule sets) | Set of str IPsec_Peer_Configs | Names of IPSec peers | Set of str IPsec_Phase2_Policies | Names of IPSec Phase 2 policies | Set of str IPsec_Phase2_Proposals | Names of IPSec Phase 2 proposals | Set of str Interfaces | Names of interfaces | Set of str Logging_Servers | Configured logging servers | Set of str Logging_Source_Interface | Source interface for communicating with logging servers | str NTP_Servers | Configured NTP servers | Set of str NTP_Source_Interface | Source interface for communicating with NTP servers | str PBR_Policies | Names of policy-based routing (PBR) policies | Set of str Route6_Filter_Lists | Names of structures that filter IPv6 routes (e.g., prefix lists) | Set of str Route_Filter_Lists | Names of structures that filter IPv4 routes (e.g., prefix lists) | Set of str Routing_Policies | Names of policies that manipulate routes (e.g., route maps) | Set of str SNMP_Source_Interface | Source interface to use for communicating with SNMP servers | str SNMP_Trap_Servers | Configured SNMP trap servers | Set of str TACACS_Servers | Configured TACACS servers | Set of str TACACS_Source_Interface | Source interface to use for communicating with TACACS servers | str VRFs | Names of VRFs present on the node | Set of str Zones | Names of firewall zones on the node | Set of str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.interfaceProperties().answer().frame() """ Explanation: Interface Properties Returns configuration settings of interfaces. Lists interface-level settings of interfaces. Settings for routing protocols, VRFs, and zones etc. that are attached to interfaces are available via other questions. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | interfaces | Include interfaces matching this specifier. | InterfaceSpec | True | properties | Include properties matching this specifier. | InterfacePropertySpec | True | excludeShutInterfaces | Exclude interfaces that are shutdown. | bool | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Interface | Interface | Interface Access_VLAN | VLAN number when the switchport mode is access (null otherwise) | int Active | Whether the interface is active | bool Admin_Up | Whether the interface is administratively enabled | bool All_Prefixes | All IPv4 addresses assigned to the interface | List of str Allowed_VLANs | Allowed VLAN numbers when the switchport mode is trunk | str Auto_State_VLAN | For VLAN interfaces, whether the operational status depends on member switchports | bool Bandwidth | Nominal bandwidth in bits/sec, used for protocol cost calculations | float Blacklisted | Whether the interface is considered down for maintenance | bool Channel_Group | Name of the aggregated interface (e.g., a port channel) to which this interface belongs | str Channel_Group_Members | For aggregated interfaces (e.g., a port channel), names of constituent interfaces | List of str DHCP_Relay_Addresses | IPv4 addresses to which incoming DHCP requests are relayed | List of str Declared_Names | Any aliases explicitly defined for this interface | List of str Description | Configured interface description | str Encapsulation_VLAN | Number for VLAN encapsulation | int HSRP_Groups | HSRP group identifiers | Set of str HSRP_Version | HSRP version that will be used | str Inactive_Reason | Reason why interface is inactive | str Incoming_Filter_Name | Name of the input IPv4 filter | str MLAG_ID | MLAG identifier of the interface | int MTU | Layer3 MTU of the interface | int Native_VLAN | Native VLAN when switchport mode is trunk | int Outgoing_Filter_Name | Name of the output IPv4 filter | str PBR_Policy_Name | Name of policy-based routing (PBR) policy | str Primary_Address | Primary IPv4 address along with the prefix length | str Primary_Network | Primary IPv4 subnet, in canonical form | str Proxy_ARP | Whether proxy ARP is enabled | bool Rip_Enabled | Whether RIP is enabled | bool Rip_Passive | Whether interface is in RIP passive mode | bool Spanning_Tree_Portfast | Whether spanning-tree portfast feature is enabled | bool Speed | Link speed in bits/sec | float Switchport | Whether the interface is configured as switchport | bool Switchport_Mode | Switchport mode (ACCESS, DOT1Q_TUNNEL, DYNAMIC_AUTO, DYNAMIC_DESIRABLE, FEX_FABRIC, MONITOR, NONE, TAP, TOOL, TRUNK) for switchport interfaces | str Switchport_Trunk_Encapsulation | Encapsulation type (DOT1Q, ISL, NEGOTIATE) for switchport trunk interfaces | str VRF | Name of the VRF to which the interface belongs | str VRRP_Groups | All VRRP groups to which the interface belongs | List of int Zone_Name | Name of the firewall zone to which the interface belongs | str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.bgpProcessConfiguration().answer().frame() """ Explanation: BGP Process Configuration Returns configuration settings of BGP processes. Reports configuration settings for each BGP process on each node and VRF in the network. This question reports only process-wide settings. Peer-specific settings are reported by the bgpPeerConfiguration question. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | properties | Include properties matching this regex. | BgpProcessPropertySpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VRF | VRF | str Router_ID | Router ID | str Confederation_ID | Externally visible autonomous system number for the confederation | int Confederation_Members | Set of autonomous system numbers visible only within this BGP confederation | Set of int Multipath_EBGP | Whether multipath routing is enabled for EBGP | bool Multipath_IBGP | Whether multipath routing is enabled for IBGP | bool Multipath_Match_Mode | Which AS paths are considered equivalent (EXACT_PATH, FIRST_AS, PATH_LENGTH) when multipath BGP is enabled | str Neighbors | All peers configured on this process, identified by peer address (for active and dynamic peers) or peer interface (for BGP unnumbered peers) | Set of str Route_Reflector | Whether any BGP peer in this process is configured as a route reflector client, for ipv4 unicast address family | bool Tie_Breaker | Tie breaking mode (ARRIVAL_ORDER, CLUSTER_LIST_LENGTH, ROUTER_ID) | str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.bgpPeerConfiguration().answer().frame() """ Explanation: BGP Peer Configuration Returns configuration settings for BGP peerings. Reports configuration settings for each configured BGP peering on each node in the network. This question reports peer-specific settings. Settings that are process-wide are reported by the bgpProcessConfiguration question. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | properties | Include properties matching this regex. | BgpPeerPropertySpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VRF | VRF | str Local_AS | Local AS number | int Local_IP | Local IPv4 address (null for BGP unnumbered peers) | str Local_Interface | Local Interface | str Confederation | Confederation AS number | int Remote_AS | Remote AS numbers with which this peer may establish a session | str Remote_IP | Remote IP | str Description | Configured peer description | str Route_Reflector_Client | Whether this peer is a route reflector client | bool Cluster_ID | Cluster ID of this peer (null for peers that are not route reflector clients) | str Peer_Group | Name of the BGP peer group to which this peer belongs | str Import_Policy | Names of import policies to be applied to routes received by this peer | Set of str Export_Policy | Names of export policies to be applied to routes exported by this peer | Set of str Send_Community | Whether this peer propagates communities | bool Is_Passive | Whether this peer is passive | bool Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('ios_basic_hsrp') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.hsrpProperties().answer().frame() """ Explanation: HSRP Properties Returns configuration settings of HSRP groups. Lists information about HSRP groups on interfaces. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | interfaces | Include interfaces matching this specifier. | InterfaceSpec | True | virtualAddresses | Include only groups with at least one virtual address matching this specifier. | IpSpec | True | excludeShutInterfaces | Exclude interfaces that are shutdown. | bool | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Interface | Interface | Interface Group_Id | HSRP Group ID | int Virtual_Addresses | Virtual Addresses | Set of str Source_Address | Source Address used for HSRP messages | str Priority | HSRP router priority | int Preempt | Whether preemption is allowed | bool Active | Whether the interface is active | bool Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.ospfProcessConfiguration().answer().frame() """ Explanation: OSPF Process Configuration Returns configuration parameters for OSPF routing processes. Returns the values of important properties for all OSPF processes running across the network. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | properties | Include properties matching this specifier. | OspfProcessPropertySpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VRF | VRF name | str Process_ID | Process ID | str Areas | All OSPF areas for this process | Set of str Reference_Bandwidth | Reference bandwidth in bits/sec used to calculate interface OSPF cost | float Router_ID | Router ID of the process | str Export_Policy_Sources | Names of policies that determine which routes are exported into OSPF | Set of str Area_Border_Router | Whether this process is at the area border (with at least one interface in Area 0 and one in another area) | bool Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.ospfInterfaceConfiguration().answer().frame() """ Explanation: OSPF Interface Configuration Returns OSPF configuration of interfaces. Returns the interface level OSPF configuration details for the interfaces in the network which run OSPF. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | properties | Include properties matching this specifier. | OspfInterfacePropertySpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Interface | Interface | Interface VRF | VRF name | str Process_ID | Process ID | str OSPF_Area_Name | OSPF area to which the interface belongs | int OSPF_Enabled | Whether OSPF is enabled | bool OSPF_Passive | Whether interface is in OSPF passive mode | bool OSPF_Cost | OSPF cost if explicitly configured | int OSPF_Network_Type | Type of OSPF network associated with the interface | str OSPF_Hello_Interval | Interval in seconds between sending OSPF hello messages | int OSPF_Dead_Interval | Interval in seconds before a silent OSPF neighbor is declared dead | int Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.ospfAreaConfiguration().answer().frame() """ Explanation: OSPF Area Configuration Returns configuration parameters of OSPF areas. Returns information about all OSPF areas defined across the network. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VRF | VRF | str Process_ID | Process ID | str Area | Area number | str Area_Type | Area type | str Active_Interfaces | Names of active interfaces | Set of str Passive_Interfaces | Names of passive interfaces | Set of str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('aristaevpn') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.mlagProperties().answer().frame() """ Explanation: Multi-chassis LAG Returns MLAG configuration. Lists the configuration settings for each MLAG domain in the network. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | mlagIds | Include MLAG IDs matching this specifier. | MlagIdSpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node name | str MLAG_ID | MLAG domain ID | str Peer_Address | Peer's IP address | str Local_Interface | Local interface used for MLAG peering | Interface Source_Interface | Local interface used as source-interface for MLAG peering | Interface Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.ipOwners().answer().frame() """ Explanation: IP Owners Returns where IP addresses are attached in the network. For each device, lists the mapping from IPs to corresponding interface(s) and VRF(s). Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- ips | Restrict output to only specified IP addresses. | IpSpec | True | duplicatesOnly | Restrict output to only IP addresses that are duplicated (configured on a different node or VRF) in the snapshot. | bool | False | False Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node hostname | str VRF | VRF name | str Interface | Interface name | str IP | IP address | str Mask | Network mask length | int Active | Whether the interface is active | bool Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.namedStructures().answer().frame() """ Explanation: Named Structures Returns named structure definitions. Return structures defined in the configurations, represented in a vendor-independent JSON format. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | structureTypes | Include structures of this type. | NamedStructureSpec | True | structureNames | Include structures matching this name or regex. | str | True | ignoreGenerated | Whether to ignore auto-generated structures. | bool | True | True indicatePresence | Output if the structure is present or absent. | bool | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str Structure_Type | Structure type | str Structure_Name | Structure name | str Structure_Definition | Structure definition | dict Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.definedStructures().answer().frame() """ Explanation: Defined Structures Lists the structures defined in the network. Lists the structures defined in the network, along with the files and line numbers in which they are defined. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- filename | Include structures defined in the given file. | str | True | nodes | Include files used to generate nodes whose name matches this specifier. | NodeSpec | True | . names | Include structures whose name matches this string or regex. | str | True | . types | Include structures whose vendor-specific type matches this string or regex. | str | True | .* Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Structure_Type | Vendor-specific type of the structure | str Structure_Name | Name of the structure | str Source_Lines | File and line numbers where the structure is defined | FileLines Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.referencedStructures().answer().frame() """ Explanation: Referenced Structures Lists the references in configuration files to vendor-specific structures. Lists the references in configuration files to vendor-specific structures, along with the line number, the name and the type of the structure referenced, and configuration context in which each reference occurs. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include files used to generate nodes whose name matches this specifier. | NodeSpec | True | names | Include structures whose name matches this string or regex. | str | True | types | Include structures whose vendor-specific type matches this string or regex. | str | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Structure_Type | Type of structure referenced | str Structure_Name | The referenced structure | str Context | Configuration context in which the reference appears | str Source_Lines | Lines where reference appears | FileLines Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.undefinedReferences().answer().frame() """ Explanation: Undefined References Identifies undefined references in configuration. Finds configurations that have references to named structures (e.g., ACLs) that are not defined. Such occurrences indicate errors and can have serious consequences in some cases. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Look for undefined references on nodes matching this name or regex. | NodeSpec | True | .* Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- File_Name | File containing reference | str Struct_Type | Type of struct reference is supposed to be | str Ref_Name | The undefined reference | str Context | Context of undefined reference | str Lines | Lines where reference appears | FileLines Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('generate_questions') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.unusedStructures().answer().frame() """ Explanation: Unused Structures Returns nodes with structures such as ACLs, routemaps, etc. that are defined but not used. Return nodes with structures such as ACLs, routes, etc. that are defined but not used. This may represent a bug in the configuration, which may have occurred because a final step in a template or MOP was not completed. Or it could be harmless extra configuration generated from a master template that is not meant to be used on those nodes. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Look for unused structures on nodes matching this name or regex. | NodeSpec | True | .* Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Structure_Type | Vendor-specific type of the structure | str Structure_Name | Name of the structure | str Source_Lines | File and line numbers where the structure is defined | FileLines Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('aristaevpn') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.switchedVlanProperties().answer().frame() """ Explanation: VLAN Properties Returns configuration settings of switched VLANs. Lists information about implicitly and explicitly configured switched VLANs. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | interfaces | Include interfaces matching this specifier. | InterfaceSpec | True | vlans | Include VLANs in this space. | str | True | excludeShutInterfaces | Exclude interfaces that are shutdown. | bool | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VLAN_ID | VLAN_ID | int Interfaces | Switched interfaces carrying traffic for this VLAN | Set of Interface VXLAN_VNI | VXLAN VNI with which this VLAN is associated | int Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('ios_basic_vrrp') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.vrrpProperties().answer().frame() """ Explanation: VRRP Properties Returns configuration settings of VRRP groups. Lists information about VRRP groups on interfaces. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this specifier. | NodeSpec | True | interfaces | Include interfaces matching this specifier. | InterfaceSpec | True | virtualAddresses | Include only groups with at least one virtual address matching this specifier. | IpSpec | True | excludeShutInterfaces | Exclude interfaces that are shutdown. | bool | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Interface | Interface | Interface Group_Id | VRRP Group ID | int Virtual_Addresses | Virtual Addresses | Set of str Source_Address | Source Address used for VRRP messages | str Priority | VRRP router priority | int Preempt | Whether preemption is allowed | bool Active | Whether the interface is active | bool Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('a10') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.a10VirtualServerConfiguration().answer().frame() """ Explanation: A10 Virtual Server Configuration Returns Virtual Server configuration of A10 devices. Lists all the virtual-server to service-group to server mappings in A10 configurations. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | virtualServerIps | Include virtual servers whose IP match this specifier. | IpSpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str Virtual_Server_Name | Virtual Server Name | str Virtual_Server_Enabled | Virtual Server Enabled | bool Virtual_Server_IP | Virtual Server IP | str Virtual_Server_Port | Virtual Server Port | int Virtual_Server_Port_Enabled | Virtual Server Port Enabled | bool Virtual_Server_Type | Virtual Server Type | str Virtual_Server_Port_Type_Name | Virtual Server Port Type Name | str Service_Group_Name | Service Group Name | str Service_Group_Type | Service Group Type | str Servers | List of Servers. Each item is a 4-tuple: Server Name, Port, IP Address, and Active Status. | Set of List of str Source_NAT_Pool_Name | Source NAT Pool Name | str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] bf.set_network('generate_questions') bf.set_snapshot('f5') """ Explanation: Print the first row of the returned Dataframe End of explanation """ result = bf.q.f5BigipVipConfiguration().answer().frame() """ Explanation: F5 BIG-IP VIP Configuration Returns VIP configuration of F5 BIG-IP devices. Lists all the VIP to server IP mappings contained in F5 BIP-IP configurations. Inputs Name | Description | Type | Optional | Default Value --- | --- | --- | --- | --- nodes | Include nodes matching this name or regex. | NodeSpec | True | Invocation End of explanation """ result.head(5) """ Explanation: Return Value Name | Description | Type --- | --- | --- Node | Node | str VIP_Name | Virtual Service Name | str VIP_Endpoint | Virtual Service Endpoint | str Servers | Servers | Set of str Description | Description | str Print the first 5 rows of the returned Dataframe End of explanation """ result.iloc[0] """ Explanation: Print the first row of the returned Dataframe End of explanation """
google/tf-quant-finance
tf_quant_finance/examples/jupyter_notebooks/Monte_Carlo_Euler_Scheme.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ #@title Upgrade to TensorFlow 2.5+ !pip install --upgrade tensorflow #@title Install TF Quant Finance !pip install tf-quant-finance #@title Install QuantLib !pip install QuantLib-Python !nvidia-smi """ Explanation: Monte Carlo Pricing in Tensorflow Quant Finance (TFF) using Euler Scheme <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Monte_Carlo_Euler_Scheme.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/google/tf-quant-finance/blob/master/tf_quant_finance/examples/jupyter_notebooks/Monte_Carlo_Euler_Scheme.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> End of explanation """ #@title Imports { display-mode: "form" } import matplotlib.pyplot as plt import numpy as np import time import tensorflow as tf import QuantLib as ql # tff for Tensorflow Finance import tf_quant_finance as tff from IPython.core.pylabtools import figsize figsize(21, 14) # better graph size for Colab """ Explanation: Diffusion process $X(t) = (X_1(t), .. X_n(t))$ is a solution to a Stochastic Differential Equation (SDE) $$dS_i = a_i(t, S) dt + \sum_{j=1}^n S_{ij} (t, S) dW_j,\ i \in {1,.., n},$$ where $n$ is the dimensionality of the diffusion, ${W_j}{j=1}^n$ is $n$-dimensitonal Brownian motion, $a_i(t, S)$ is the instantaneous drift rate and the $S{ij}(t)$ is the volatility matrix. In this colab we demonstrate how to draw samples from the difusion solution in TFF using the Euler scheme. We also demonstrate how to use automatic differentiation framework for vega and delta computation and provide performance benchmarks. End of explanation """ #@title Set up parameters dtype = np.float64 #@param num_samples = 200000 #@param num_timesteps = 100 #@param expiries = [1.0] # This can be a rank 1 Tensor dt = 1. / num_timesteps rate = tf.constant(0.03, dtype=dtype) sigma = tf.constant(0.1, dtype=dtype) spot = tf.constant(700, dtype=dtype) strikes = tf.constant([600, 650, 680], dtype=dtype) def set_up_pricer(expiries, watch_params=False): """Set up European option pricing function under Black-Scholes model. Args: expiries: List of expiries at which to to sample the trajectories. watch_params: A Python bool. When `True`, gradients of the price function wrt the inputs are computed more efficiently. Returns: A callable that accepts a rank 1 tensor of strikes, and scalar values for the spots and volatility values. The callable outputs prices of the European call options on the grid `expiries x strikes`. """ def price_eu_options(strikes, spot, sigma): # Define drift and volatility functions. def drift_fn(t, x): del t, x return rate - 0.5 * sigma**2 def vol_fn(t, x): del t, x return tf.reshape(sigma, [1, 1]) # Use GenericItoProcess class to set up the Ito process process = tff.models.GenericItoProcess( dim=1, drift_fn=drift_fn, volatility_fn=vol_fn, dtype=dtype) log_spot = tf.math.log(tf.reduce_mean(spot)) if watch_params: watch_params_list = [sigma] else: watch_params_list = None paths = process.sample_paths( expiries, num_samples=num_samples, initial_state=log_spot, watch_params=watch_params_list, # Select a random number generator random_type=tff.math.random.RandomType.PSEUDO_ANTITHETIC, time_step=dt) prices = (tf.exp(-tf.expand_dims(rate * expiries, axis=-1)) * tf.reduce_mean(tf.nn.relu(tf.math.exp(paths) - strikes), 0)) return prices return price_eu_options price_eu_options = tf.function(set_up_pricer(expiries)) #@title Pricing time a CPU. Note TensorFlow does automatic multithreading. # First run (includes graph optimization time) with tf.device("/cpu:0"): price_eu_options(strikes, spot, sigma) # Second run (excludes graph optimization time) time_start = time.time() with tf.device("/cpu:0"): prices = price_eu_options(strikes, spot, sigma) time_end = time.time() time_price_cpu = time_end - time_start print("Time (seconds) to price a European Call Option on a CPU: ", time_price_cpu) """ Explanation: Setting up the Euler sampling for European call option pricing under Black-Scholes The pricing function outputs prices on the grid expiries x strikes. Sampling is performed using sample_paths method of GenericItoProcess class. The user is free to provide their own drift and volatility function in order to sample from the desired process. For many processes there exist efficient specialized samplers and the user should feel free to explore the TFF models module. In this example, however, we consider only GenericItoProcess. End of explanation """ price_eu_options_xla = tf.function(set_up_pricer(expiries), jit_compile=True) #@title Pricing times on a CPU with XLA compilation # First run (includes graph optimization time) with tf.device("/cpu:0"): price_eu_options_xla(strikes, spot, sigma) # Second run (excludes graph optimization time) time_start = time.time() with tf.device("/cpu:0"): prices = price_eu_options_xla(strikes, spot, sigma) time_end = time.time() time_price_cpu_xla = time_end - time_start print("Time (seconds) to price a European Call Option on a CPU with XLA: ", time_price_cpu_xla) """ Explanation: Better performance with XLA A quick guide on XLA is available on TensorFlow website. Roughly, XLA compiler generates a binary for the desired architecture (CPU/GPU/TPU). When underlying TF graph consists of many nodes, XLA might provide a significant speed up. Below we use tf.function with jit_compile=True to indicate that the whole Monte Carlo graph should be XLA-compiled. End of explanation """ #@title Monte Carlo sampling in QuantLib num_samples = 200000 #@param num_timesteps = 100 #@param expiry = 1.0 calculation_date = ql.Date(1, 1, 2010) maturity_date = ql.Date(1, 1, 2011) day_count = ql.Thirty360() calendar = ql.NullCalendar() ql_strike_price = 550 sigma_ql = 0.1 ql_volatility = ql.SimpleQuote(sigma_ql) ql_risk_free_rate = 0.03 option_type = ql.Option.Call ql.Settings.instance().evaluationDate = calculation_date payoff = ql.PlainVanillaPayoff(option_type, ql_strike_price) eu_exercise = ql.EuropeanExercise(maturity_date) european_option_ql = ql.VanillaOption(payoff, eu_exercise) flat_ts = ql.YieldTermStructureHandle( ql.FlatForward(calculation_date, ql_risk_free_rate, day_count) ) flat_vol_ts = ql.BlackVolTermStructureHandle( ql.BlackConstantVol(calculation_date, calendar, ql.QuoteHandle(ql_volatility), day_count) ) spot_ql = 700 spot_price = ql.SimpleQuote(spot_ql) spot_handle = ql.QuoteHandle( spot_price ) bsm_process = ql.BlackScholesProcess(spot_handle, flat_ts, flat_vol_ts) # Compute the same price number_of_options times engine = ql.MCEuropeanEngine(bsm_process, "PseudoRandom", timeSteps=num_timesteps, requiredSamples=num_samples, seed=42) european_option_ql.setPricingEngine(engine) # Price t = time.time() price_ql = european_option_ql.NPV() time_price_ql = time.time() - t print("Time (seconds) to price a European Call Option using QuantLib: ", time_price_ql) #@title Plot the results ind = np.arange(1) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() fig.set_figheight(9) fig.set_figwidth(12) ax.bar(ind - width/2, [time_price_cpu], width, label='TensorFlow (CPU)', color='darkorange') ax.bar(ind + width/2, [time_price_ql], width, label='QuantLib') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Time (sec) to sample {}'.format(num_samples)) ax.set_title('Monte Carlo sampling comparison') ax.set_xticks(ind) ax.legend() plt.show() """ Explanation: For the reference we provide performance of the Monte Carlo pricer in QuantLib End of explanation """ #@title Pricing times on CPU and GPU platforms # CPU without XLA with tf.device("/cpu:0"): price_eu_options(strikes, spot, sigma) time_start = time.time() with tf.device("/cpu:0"): prices = price_eu_options(strikes, spot, sigma) time_end = time.time() time_price_cpu = time_end - time_start # CPU with XLA with tf.device("/cpu:0"): price_eu_options_xla(strikes, spot, sigma) time_start = time.time() with tf.device("/cpu:0"): prices = price_eu_options_xla(strikes, spot, sigma) time_end = time.time() time_price_cpu_xla = time_end - time_start # GPU without XLA with tf.device("/gpu:0"): price_eu_options(strikes, spot, sigma) # Second run (excludes graph optimization time) time_start = time.time() with tf.device("/gpu:0"): prices = price_eu_options(strikes, spot, sigma) time_end = time.time() time_price_gpu = time_end - time_start # GPU with XLA with tf.device("/gpu:0"): price_eu_options_xla(strikes, spot, sigma) # Second run (excludes graph optimization time) time_start = time.time() with tf.device("/gpu:0"): prices = price_eu_options_xla(strikes, spot, sigma) time_end = time.time() time_price_gpu_xla = time_end - time_start #@title Plot the results ind = np.arange(1) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() fig.set_figheight(9) fig.set_figwidth(12) ax.bar(ind - width/8, [time_price_cpu], width / 8, label='TensorFlow (CPU)') ax.bar(ind, [time_price_cpu_xla], width / 8, label='TensorFlow (CPU XLA)') ax.bar(ind + width/8, [time_price_gpu], width / 8, label='TensorFlow (GPU)') ax.bar(ind + width/4, [time_price_gpu_xla], width / 8, label='TensorFlow (GPU XLA)') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Time (sec) to sample {}'.format(num_samples)) ax.set_title('Monte Carlo sampling comparison') ax.set_xticks(ind) ax.legend() plt.show() """ Explanation: GPU vs CPU performace Above one can see that TF effectively applies multithreading to achieve the best possible CPU performance. If the user has access to a good GPU, additional boost can be achieved as demonstrated below. For this specific model XLA provides significant speedup for both CPU and GPU platforms. Tesla V100 provides 100x speed up compared to a cloud CPU with 8 logical cores (n1-standard-8 machine type on Google Cloud Platform). End of explanation """ # Set up the pricer expiries = [0.5, 1.0] strikes = tf.constant([600, 650, 680], dtype=dtype) sigma = tf.constant(0.1, dtype=dtype) price_eu_options = set_up_pricer(expiries, watch_params=True) price_eu_options_no_watched_params = set_up_pricer(expiries) @tf.function(jit_compile=True) def price_eu_options_xla(strikes, spot, sigma): return price_eu_options_no_watched_params(strikes, spot, sigma) @tf.function def vega_fn(sigma): fn = lambda sigma: price_eu_options(strikes, spot, sigma) return tff.math.fwd_gradient(fn, sigma, use_gradient_tape=True) @tf.function(jit_compile=True) def vega_fn_xla(sigma): return vega_fn(sigma) @tf.function def delta_fn(spot): fn = lambda spot: price_eu_options(strikes, spot, sigma) return tff.math.fwd_gradient(fn, spot, use_gradient_tape=True) @tf.function(jit_compile=True) def delta_fn_xla(spot): return delta_fn(spot) estimated_deltas = delta_fn_xla(spot) print("Estimated deltas on grid expiries x strikes: \n", estimated_deltas.numpy()) estimated_vegas = vega_fn_xla(sigma) print("Estimated vegas on grid expiries x strikes: \n", estimated_vegas.numpy()) expiries_tensor = tf.expand_dims(tf.convert_to_tensor(expiries, dtype=dtype), axis=1) true_delta_fn = lambda spot : tff.black_scholes.option_price(volatilities=sigma, strikes=strikes, spots=spot, expiries=expiries_tensor, discount_rates=rate) true_vega_fn = lambda sigma : tff.black_scholes.option_price(volatilities=sigma, strikes=strikes, spots=spot, expiries=expiries_tensor, discount_rates=rate) true_delta = tff.math.fwd_gradient(true_delta_fn, spot) true_vega = tff.math.fwd_gradient(true_vega_fn, sigma) print("True deltas on grid expiries x strikes: \n", true_delta.numpy()) print("True vegas on grid expiries x strikes: \n", true_vega.numpy()) print("Relative error in delta estimation: \n", np.max(abs(estimated_deltas - true_delta) / true_delta)) print("Relative error in vega estimation: \n", np.max(abs(estimated_vegas - true_vega) / true_vega)) #@title Greek computation speed # Price CPU with XLA ## warmup with tf.device("/cpu:0"): price_eu_options_xla(strikes, spot, sigma) ## measure time time_start = time.time() with tf.device("/cpu:0"): prices = price_eu_options_xla(strikes, spot, sigma) time_end = time.time() time_price_cpu = time_end - time_start # Delta CPU with XLA ## warmup with tf.device("/cpu:0"): delta_fn_xla(spot) ## measure time time_start = time.time() with tf.device("/cpu:0"): delta_fn_xla(spot) time_end = time.time() time_delta_cpu = time_end - time_start # Vega CPU with XLA ## warmup with tf.device("/cpu:0"): vega_fn_xla(spot) ## measure time time_start = time.time() with tf.device("/cpu:0"): vega_fn_xla(spot) time_end = time.time() time_vega_cpu = time_end - time_start # Price GPU with XLA ## warmup with tf.device("/gpu:0"): price_eu_options_xla(strikes, spot, sigma) ## measure time time_start = time.time() with tf.device("/gpu:0"): prices = price_eu_options_xla(strikes, spot, sigma) time_end = time.time() time_price_gpu = time_end - time_start # Delta GPU with XLA ## warmup with tf.device("/gpu:0"): delta_fn_xla(spot) ## measure time time_start = time.time() with tf.device("/gpu:0"): delta_fn_xla(spot) time_end = time.time() time_delta_gpu = time_end - time_start # Vega GPU with XLA ## warmup with tf.device("/gpu:0"): vega_fn_xla(spot) ## measure time time_start = time.time() with tf.device("/gpu:0"): vega_fn_xla(spot) time_end = time.time() time_vega_gpu = time_end - time_start #@title CPU greeks computation speed ind = np.arange(1) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() fig.set_figheight(9) fig.set_figwidth(12) ax.bar(ind - width/8, [time_price_cpu], width / 8, label='Price time (CPU)') ax.bar(ind, [time_delta_cpu], width / 8, label='Delta time (CPU)') ax.bar(ind + width/8, [time_vega_cpu], width / 8, label='Vega time (CPU)') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Time (sec)') ax.set_title('Monte Carlo. Greeks computation on CPU') ax.set_xticks(ind) ax.legend() plt.show() #@title GPU greeks computation speed ind = np.arange(1) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() fig.set_figheight(9) fig.set_figwidth(12) ax.bar(ind - width/8, [time_price_gpu], width / 8, label='Price time (GPU)') ax.bar(ind, [time_delta_gpu], width / 8, label='Delta time (GPU)') ax.bar(ind + width/8, [time_vega_gpu], width / 8, label='Vega time (GPU)') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Time (sec)') ax.set_title('Monte Carlo. Greeks computation on GPU') ax.set_xticks(ind) ax.legend() plt.show() """ Explanation: Greek computation TF provides framework for automatic differentiation. Below we demostrate how to compute vega and delta for the European call options and compare the estimated results ti the true values. End of explanation """
gcgruen/homework
foundations-homework/12/homework-12-gruen-311timeseries.ipynb
mit
df = pd.read_csv("311-2014.csv", nrows=200000, low_memory = False) df.head(3) df.columns type(df['Created Date'][0]) print(df['Created Date'][0]) dateutil.parser.parse(df['Created Date'][0]) def str_to_time(str_date): datetype_date = dateutil.parser.parse(str_date) return datetype_date df['created_date'] = df['Created Date'].apply(str_to_time) df.index=df['created_date'] df.head(3) """ Explanation: First, I made a mistake naming the data set! It's 2015 data, not 2014 data. But yes, still use 311-2014.csv. You can rename it. Importing and preparing your data Import your data, but only the first 200,000 rows. You'll also want to change the index to be a datetime based on the Created Date column - you'll want to check if it's already a datetime, and parse it if not. End of explanation """ df.groupby("Complaint Type").count()['Unique Key'].sort_values(ascending=False) """ Explanation: What was the most popular type of complaint, and how many times was it filed? End of explanation """ plt.style.use('ggplot') ax = df.groupby("Complaint Type").count()['Unique Key'].sort_values(ascending=True).tail(5).plot(kind='barh', figsize=(10,7)) ax.set_title("5 most frequent complaint types") ax.set_xlabel("How many times was it filed?") """ Explanation: Make a horizontal bar graph of the top 5 most frequent complaint types. End of explanation """ df.groupby('Borough').count()['Unique Key'].sort_values(ascending=False) #https://en.wikipedia.org/wiki/Brooklyn inhabitants=[{'state': "BROOKLYN", 'inhabitants':2621793}, {'state': "QUEENS", 'inhabitants': 2321580}, {'state': "MANHATTAN", 'inhabitants': 1636268}, {'state': "BRONX", 'inhabitants': 1438159}, {'state': "STATEN ISLAND", 'inhabitants': 473279},] inhabitantsdf=pd.DataFrame(inhabitants) inhabitantsdf print("Complaints per capita: Brooklyn", 57129/2621793) print("Complaints per capita: Queens", 46824/2321580) print("Complaints per capita: Manhattan", 42050/1636268) print("Complaints per capita: Bronx", 29610/1438159) print("Complaints per capita: Staten Island", 7387/473279) """ Explanation: Which borough has the most complaints per capita? Since it's only 5 boroughs, you can do the math manually. End of explanation """ march_cases = df["2015-03"]['Unique Key'].count() may_cases = df["2015-05"]['Unique Key'].count() print("Cases filed in March:", march_cases) print("Cases filed in May:", may_cases) """ Explanation: Manhattan has the most complaints per capita. According to your selection of data, how many cases were filed in March? How about May? End of explanation """ df["2015-04-01"] """ Explanation: I'd like to see all of the 311 complaints called in on April 1st. Surprise! We couldn't do this in class, but it was just a limitation of our data set End of explanation """ df["2015-04-01"].groupby('Complaint Type').count()["Unique Key"].sort_values(ascending=False).head(1) """ Explanation: What was the most popular type of complaint on April 1st? End of explanation """ df["2015-04-01"].groupby('Complaint Type').count()["Unique Key"].sort_values(ascending=False).head(3) """ Explanation: What were the most popular three types of complaint on April 1st End of explanation """ ax = df.resample('m')['Unique Key'].count().plot(figsize=(10,5)) ax.set_title("Reports filed per month") ax.set_ylabel("Number of complaints") ax.set_xlabel("Month") df.resample('m')['Unique Key'].count().max() print("The month with most cases is May with",df.resample('m')['Unique Key'].count().max(), "cases.") """ Explanation: What month has the most reports filed? How many? Graph it. End of explanation """ ax = df.resample('W')['Unique Key'].count().plot(figsize=(10,5)) ax.set_title("Reports filed per week") ax.set_ylabel("Number of complaints") ax.set_xlabel("Week") # weeknumbers= list(range(1,52)) # ax.set_xticks(weeknumbers) print("The week with most cases is the second in May with",df.resample('W')['Unique Key'].count().max(), "cases.") """ Explanation: What week of the year has the most reports filed? How many? Graph the weekly complaints. End of explanation """ noise_df = df[df["Complaint Type"].str.contains("Noise ")] noiseax = noise_df.resample('W')['Unique Key'].count().plot(figsize=(10,5)) noiseax.set_title("Noise complaints filed over the year") noiseax.set_ylabel("Number of noise-related complaints") noiseax.set_xlabel("Time of year") noisedayax = noise_df.groupby(by=noise_df.index.hour)['Unique Key'].count().plot(figsize=(10,5)) noisedayax.set_title("Hour when noise complaints are filed") noisedayax.set_ylabel("Number of noise complaints") noisedayax.set_xticks([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]) noisedayax.set_xlabel("Hour of the day") """ Explanation: Noise complaints are a big deal. Use .str.contains to select noise complaints, and make an chart of when they show up annually. Then make a chart about when they show up every day (cyclic). End of explanation """ df.resample('D')['Unique Key'].count().sort_values(ascending=False).head(5) df.resample('D')['Unique Key'].count().sort_values().tail(5).plot(kind='barh') """ Explanation: Which were the top five days of the year for filing complaints? How many on each of those days? Graph it. End of explanation """ df.groupby(by=df.index.hour)['Unique Key'].count() ax = df.groupby(by=df.index.hour)['Unique Key'].count().plot(figsize=(10,5)) ax.set_title("Hour when complaints are filed") ax.set_ylabel("Number of complaints") ax.set_xticks([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]) ax.set_xlabel("Hour of the day") """ Explanation: What hour of the day are the most complaints? Graph a day of complaints. End of explanation """ # Midnight is is an outlier, complaint-number-wise hourly_df = pd.DataFrame(df.groupby(df.index.hour)['Complaint Type'].value_counts()) hourly_df #Most common complaint types at midnight hourly_df['Complaint Type'][0].head(5) #Most common complaint types the hour before midnight hourly_df['Complaint Type'][23].head(5) #Most common complaint types the hour after midnight hourly_df['Complaint Type'][1].head(5) """ Explanation: One of the hours has an odd number of complaints. What are the most common complaints at that hour, and what are the most common complaints the hour before and after? End of explanation """ midnight_df = df[df.index.hour==0] minutely_df = midnight_df.groupby(by=midnight_df.index.minute) minax = minutely_df['Unique Key'].count().plot(figsize=(15,5)) minax.set_title("Complaints filed per minute during midnight hour") minax.set_xlabel("Minutes of the hour") minax.set_ylabel("Numbers of complaints filed") minax.set_xticks([0,5,10,15,20,25,30,35,40,45,50,55,60]) """ Explanation: So odd. What's the per-minute breakdown of complaints between 12am and 1am? You don't need to include 1am. End of explanation """ midnight_df['Agency'].value_counts().sort_values(ascending=False).head(5) #Write test code for first agency hpd_df = df[df['Agency'] == 'HPD'] ax = hpd_df.groupby(by=hpd_df.index.hour).count()['Unique Key'].plot(figsize=(12,7), label= 'HPD', legend=True, linewidth=2) ax.set_title("Complaints per agency and time of the day") ax.set_xlabel("Hour of the day") ax.set_xticks([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]) ax.set_ylabel("Number of complaints filed") #Turn working code into a function: def complaints_by_agency(agency_name): complaints_agency = df[df['Agency'] == agency_name] return complaints_agency.groupby(by=complaints_agency.index.hour).count()['Unique Key'] #run code for remaining agencies for agency in ['NYPD', 'DOHMH', 'TLC', 'DOT']: complaints_by_agency(agency).plot(ax=ax, label = agency, legend=True, linewidth=2) """ Explanation: Looks like midnight is a little bit of an outlier. Why might that be? Take the 5 most common agencies and graph the times they file reports at (all day, not just midnight). End of explanation """ #Write test code for first agency #Copied code from above replacing groupby by resample('W') hpd_df = df[df['Agency'] == 'HPD'] ax = hpd_df.resample('W')['Unique Key'].count().plot(figsize=(12,7), label= 'HPD', legend=True, linewidth=2) ax.set_title("Complaints per agency and time of the year") ax.set_xlabel("Week of the year") ax.set_ylabel("Number of complaints filed") #Turn working code into a function: def agency_complaints_weekly(agency_name): complaints_weekly = df[df['Agency'] == agency_name] return complaints_weekly.resample('W')['Unique Key'].count() #run code for remaining agencies for agency in ['NYPD', 'DOHMH', 'TLC', 'DOT']: agency_complaints_weekly(agency).plot(ax=ax, label = agency, legend=True, linewidth=2) """ Explanation: Graph those same agencies on an annual basis - make it weekly. When do people like to complain? When does the NYPD have an odd number of complaints? End of explanation """ def ag_complaints(agency_name, str_date_s, str_date_e): newdf = df[df['Agency'] == agency_name] newdf.resample('M') return newdf[str_date_s : str_date_e].groupby("Complaint Type")['Unique Key'].count().sort_values(ascending=False).head(10) print("NYPD most popular complaints in July and August:") ag_complaints('NYPD', '2015-07', '2015-08') print("NYPD most popular complaints in May:") ag_complaints('NYPD', '2015-05', '2015-05') print("Most common complaints filed at the Housing Preservation Bureau (HPD) in winter") ag_complaints('HPD', '2015-11', '2016-02') print("Most common complaints filed at the Housing Preservation Bureau (HPD) in summer") ag_complaints('HPD', '2015-05', '2016-09') """ Explanation: NYPD has an odd number after the first week in May Maybe the NYPD deals with different issues at different times? Check the most popular complaints in July and August vs the month of May. Also check the most common complaints for the Housing Preservation Bureau (HPD) in winter vs. summer. End of explanation """
dsacademybr/PythonFundamentos
Cap03/Notebooks/DSA-Python-Cap03-04-Range.ipynb
gpl-3.0
# Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) """ Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 3</font> Download: http://github.com/dsacademybr End of explanation """ # Imprimindo números pares entre 50 e 101 for i in range(50, 101, 2): print(i) for i in range(3, 6): print (i) for i in range(0, -20, -2): print(i) lista = ['Morango', 'Banana', 'Abacaxi', 'Uva'] lista_tamanho = len(lista) for i in range(0, lista_tamanho): print(lista[i]) # Tudo em Python é um objeto type(range(0,3)) """ Explanation: Range End of explanation """
zhuanxuhit/deep-learning
embeddings/.ipynb_checkpoints/Skip-Grams-Solution-checkpoint.ipynb
mit
import time import numpy as np import tensorflow as tf import utils """ Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like translations. Readings Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material. A really good conceptual overview of word2vec from Chris McCormick First word2vec paper from Mikolov et al. NIPS paper with improvements for word2vec also from Mikolov et al. An implementation of word2vec from Thushan Ganegedara TensorFlow word2vec tutorial Word embeddings When you're dealing with language and words, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram. <img src="assets/word2vec_architectures.png" width="500"> In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts. First up, importing packages. End of explanation """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(dataset_filename): with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset_name) as pbar: urlretrieve( 'http://mattmahoney.net/dc/text8.zip', dataset_filename, pbar.hook) if not isdir(dataset_folder_path): with zipfile.ZipFile(dataset_filename) as zip_ref: zip_ref.extractall(dataset_folder_path) with open('data/text8') as f: text = f.read() """ Explanation: Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. Then you can extract it and delete the archive file to save storage space. End of explanation """ words = utils.preprocess(text) print(words[:30]) print("Total words: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) """ Explanation: Preprocessing Here I'm fixing up the text to make training easier. This comes from the utils module I wrote. The preprocess function coverts any punctuation into tokens, so a period is changed to &lt;PERIOD&gt;. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it. End of explanation """ vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] """ Explanation: And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list int_words. End of explanation """ from collections import Counter import random threshold = 1e-5 word_counts = Counter(int_words) total_count = len(int_words) freqs = {word: count/total_count for word, count in word_counts.items()} p_drop = {word: 1 - np.sqrt(threshold/freqs[word]) for word in word_counts} train_words = [word for word in int_words if p_drop[word] < random.random()] """ Explanation: Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by $$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$ where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset. I'm going to leave this up to you as an exercise. Check out my solution to see how I did it. Exercise: Implement subsampling for the words in int_words. That is, go through int_words and discard each word given the probablility $P(w_i)$ shown above. Note that $P(w_i)$ is that probability that a word is discarded. Assign the subsampled data to train_words. End of explanation """ def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' R = np.random.randint(1, window_size+1) start = idx - R if (idx - R) > 0 else 0 stop = idx + R target_words = set(words[start:idx] + words[idx+1:stop+1]) return list(target_words) """ Explanation: Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From Mikolov et al.: "Since the more distant words are usually less related to the current word than those close to it, we give less weight to the distant words by sampling less from those words in our training examples... If we choose $C = 5$, for each training word we will select randomly a number $R$ in range $< 1; C >$, and then use $R$ words from history and $R$ words from the future of the current word as correct labels." Exercise: Implement a function get_target that receives a list of words, an index, and a window size, then returns a list of words in the window around the index. Make sure to use the algorithm described above, where you chose a random number of words to from the window. End of explanation """ def get_batches(words, batch_size, window_size=5): ''' Create a generator of word batches as a tuple (inputs, targets) ''' n_batches = len(words)//batch_size # only full batches words = words[:n_batches*batch_size] for idx in range(0, len(words), batch_size): x, y = [], [] batch = words[idx:idx+batch_size] for ii in range(len(batch)): batch_x = batch[ii] batch_y = get_target(batch, ii, window_size) y.extend(batch_y) x.extend([batch_x]*len(batch_y)) yield x, y """ Explanation: Here's a function that returns batches for our network. The idea is that it grabs batch_size words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory. End of explanation """ train_graph = tf.Graph() with train_graph.as_default(): inputs = tf.placeholder(tf.int32, [None], name='inputs') labels = tf.placeholder(tf.int32, [None, None], name='labels') """ Explanation: Building the graph From Chris McCormick's blog, we can see the general structure of our network. The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden layer weight matrix to find efficient representations for our words. This weight matrix is usually called the embedding matrix or embedding look-up table. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset. I'm going to have you build the graph in stages now. First off, creating the inputs and labels placeholders like normal. Exercise: Assign inputs and labels using tf.placeholder. We're going to be passing in integers, so set the data types to tf.int32. The batches we're passing in will have varying sizes, so set the batch sizes to [None]. To make things work later, you'll need to set the second dimension of labels to None or 1. End of explanation """ n_vocab = len(int_to_vocab) n_embedding = 200 # Number of embedding features with train_graph.as_default(): embedding = tf.Variable(tf.random_uniform((n_vocab, n_embedding), -1, 1)) embed = tf.nn.embedding_lookup(embedding, inputs) """ Explanation: Embedding The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix: You don't actually need to do the matrix multiplication, you just need to select the row in the embedding matrix that corresponds to the input word. Then, the embedding matrix becomes a lookup table, you're looking up a vector the size of the hidden layer that represents the input word. <img src="assets/word2vec_weight_matrix_lookup_table.png" width=500> Exercise: Tensorflow provides a convenient function tf.nn.embedding_lookup that does this lookup for us. You pass in the embedding matrix and a tensor of integers, then it returns rows in the matrix corresponding to those integers. Below, set the number of embedding features you'll use (200 is a good start), create the embedding matrix variable, and use tf.nn.embedding_lookup to get the embedding tensors. For the embedding matrix, I suggest you initialize it with a uniform random numbers between -1 and 1 using tf.random_uniform. End of explanation """ # Number of negative labels to sample n_sampled = 100 with train_graph.as_default(): softmax_w = tf.Variable(tf.truncated_normal((n_vocab, n_embedding), stddev=0.1)) softmax_b = tf.Variable(tf.zeros(n_vocab)) # Calculate the loss using negative sampling loss = tf.nn.sampled_softmax_loss(softmax_w, softmax_b, labels, embed, n_sampled, n_vocab) cost = tf.reduce_mean(loss) optimizer = tf.train.AdamOptimizer().minimize(cost) """ Explanation: Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called "negative sampling". Tensorflow has a convenient function to do this, tf.nn.sampled_softmax_loss. Exercise: Below, create weights and biases for the softmax layer. Then, use tf.nn.sampled_softmax_loss to calculate the loss. Be sure to read the documentation to figure out how it works. End of explanation """ with train_graph.as_default(): ## From Thushan Ganegedara's implementation valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent valid_examples = np.array(random.sample(range(valid_window), valid_size//2)) valid_examples = np.append(valid_examples, random.sample(range(1000,1000+valid_window), valid_size//2)) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # We use the cosine distance: norm = tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keep_dims=True)) normalized_embedding = embedding / norm valid_embedding = tf.nn.embedding_lookup(normalized_embedding, valid_dataset) similarity = tf.matmul(valid_embedding, tf.transpose(normalized_embedding)) # If the checkpoints directory doesn't exist: !mkdir checkpoints epochs = 10 batch_size = 1000 window_size = 10 with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: iteration = 1 loss = 0 sess.run(tf.global_variables_initializer()) for e in range(1, epochs+1): batches = get_batches(train_words, batch_size, window_size) start = time.time() for x, y in batches: feed = {inputs: x, labels: np.array(y)[:, None]} train_loss, _ = sess.run([cost, optimizer], feed_dict=feed) loss += train_loss if iteration % 100 == 0: end = time.time() print("Epoch {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Avg. Training loss: {:.4f}".format(loss/100), "{:.4f} sec/batch".format((end-start)/100)) loss = 0 start = time.time() if iteration % 1000 == 0: # note that this is expensive (~20% slowdown if computed every 500 steps) sim = similarity.eval() for i in range(valid_size): valid_word = int_to_vocab[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k+1] log = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = int_to_vocab[nearest[k]] log = '%s %s,' % (log, close_word) print(log) iteration += 1 save_path = saver.save(sess, "checkpoints/text8.ckpt") embed_mat = sess.run(normalized_embedding) """ Explanation: Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. End of explanation """ with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) embed_mat = sess.run(embedding) """ Explanation: Restore the trained network if you need to: End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from sklearn.manifold import TSNE viz_words = 500 tsne = TSNE() embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :]) fig, ax = plt.subplots(figsize=(14, 14)) for idx in range(viz_words): plt.scatter(*embed_tsne[idx, :], color='steelblue') plt.annotate(int_to_vocab[idx], (embed_tsne[idx, 0], embed_tsne[idx, 1]), alpha=0.7) """ Explanation: Visualizing the word vectors Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out this post from Christopher Olah to learn more about T-SNE and other ways to visualize high-dimensional data. End of explanation """
zrhans/python
exemplos/Pandas_and_Friends.ipynb
gpl-2.0
import numpy as np # np.zeros, np.ones data0 = np.zeros((2, 4)) data0 # Make an array with 20 entries 0..19 data1 = np.arange(20) # print the first 8 data1[0:8] """ Explanation: Pandas and Friends Austin Godber Mail: godber@uberhip.com Twitter: @godber Presented at DesertPy, Jan 2015. What does it do? Pandas is a Python data analysis tool built on top of NumPy that provides a suite of data structures and data manipulation functions to work on those data structures. It is particularly well suited for working with time series data. Getting Started - Installation Installing with pip or apt-get:: ``` pip install pandas or sudo apt-get install python-pandas ``` Mac - Homebrew or MacPorts to get the dependencies, then pip Windows - Python(x,y)? Commercial Pythons: Anaconda, Canopy Getting Started - Dependencies Dependencies, required, recommended and optional ``` Required numpy, python-dateutil, pytx Recommended numexpr, bottleneck Optional cython, scipy, pytables, matplotlib, statsmodels, openpyxl ``` Pandas' Friends! Pandas works along side and is built on top of several other Python projects. IPython Numpy Matplotlib Pandas gets along with EVERYONE! <img src='panda-on-a-unicorn.jpg'> Background - IPython IPython is a fancy python console. Try running ipython or ipython --pylab on your command line. Some IPython tips ```python Special commands, 'magic functions', begin with % %quickref, %who, %run, %reset Shell Commands ls, cd, pwd, mkdir Need Help? help(), help(obj), obj?, function? Tab completion of variables, attributes and methods ``` Background - IPython Notebook There is a web interface to IPython, known as the IPython notebook, start it like this ``` ipython notebook or to get all of the pylab components ipython notebook --pylab ``` IPython - Follow Along Follow along by connecting to TMPNB.ORG! http://tmpnb.org Background - NumPy NumPy is the foundation for Pandas Numerical data structures (mostly Arrays) Operations on those. Less structure than Pandas provides. Background - NumPy - Arrays End of explanation """ # make it a 4,5 array data = np.arange(20).reshape(4, 5) data """ Explanation: Background - NumPy - Arrays End of explanation """ print("dtype: ", data.dtype) result = data * 20.5 print(result) """ Explanation: Background - NumPy - Arrays Arrays have NumPy specific types, dtypes, and can be operated on. End of explanation """ import pandas as pd import numpy as np """ Explanation: Now, on to Pandas Pandas Tabular, Timeseries, Matrix Data - labeled or not Sensible handling of missing data and data alignment Data selection, slicing and reshaping features Robust data import utilities. Advanced time series capabilities Data Structures Series - 1D labeled array DataFrame - 2D labeled array Panel - 3D labeled array (More D) Assumed Imports In my code samples, assume I import the following End of explanation """ s1 = pd.Series([1, 2, 3, 4, 5]) s1 """ Explanation: Series one-dimensional labeled array holds any data type axis labels known as index implicit integert indexes dict-like Create a Simple Series End of explanation """ # integer multiplication print(s1 * 5) """ Explanation: Series Operations End of explanation """ # float multiplication print(s1 * 5.0) """ Explanation: Series Operations - Cont. End of explanation """ s2 = pd.Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e']) s2 """ Explanation: Series Index End of explanation """ dates = pd.date_range('20130626', periods=5) print(dates) print() print(dates[0]) """ Explanation: Date Convenience Functions A quick aside ... End of explanation """ s3 = pd.Series([1, 2, 3, 4, 5], index=dates) print(s3) """ Explanation: Datestamps as Index End of explanation """ print(s3[0]) print(type(s3[0])) print() print(s3[1:3]) print(type(s3[1:3])) """ Explanation: Selecting By Index Note that the integer index is retained along with the new date index. End of explanation """ s3[s3 < 3] """ Explanation: Selecting by value End of explanation """ s3['20130626':'20130628'] """ Explanation: Selecting by Label (Date) End of explanation """ data1 = pd.DataFrame(np.random.rand(4, 4)) data1 """ Explanation: Series Wrapup Things not covered but you should look into: Other instantiation options: dict Operator Handling of missing data NaN Reforming Data and Indexes Boolean Indexing Other Series Attributes: index - index.name name - Series name DataFrame 2-dimensional labeled data structure Like a SQL Table, Spreadsheet or dict of Series objects. Columns of potentially different types Operations, slicing and other behavior just like Series DataFrame - Simple End of explanation """ dates = pd.date_range('20130626', periods=4) data2 = pd.DataFrame( np.random.rand(4, 4), index=dates, columns=list('ABCD')) data2 """ Explanation: DataFrame - Index/Column Names End of explanation """ data2['E'] = data2['B'] + 5 * data2['C'] data2 """ Explanation: DataFrame - Operations End of explanation """ # Deleting a Column del data2['E'] data2 """ Explanation: See? You never need Excel again! DataFrame - Column Access Deleting a column. End of explanation """ data2 """ Explanation: DataFrame Remember this, data2, for the next examples. End of explanation """ data2['B'] """ Explanation: DataFrame - Column Access As a dict End of explanation """ data2.B """ Explanation: DataFrame - Column Access As an attribute End of explanation """ data2.loc['20130627'] """ Explanation: DataFrame - Row Access By row label End of explanation """ data2.iloc[1] """ Explanation: DataFrame - Row Access By integer location End of explanation """ print(data2.B[0]) print(data2['B'][0]) print(data2.iloc[0,1]) # [row,column] """ Explanation: DataFrame - Cell Access Access column, then row or use iloc and row/column indexes. End of explanation """ data3 = pd.DataFrame(np.random.rand(100, 4)) data3.head() """ Explanation: DataFrame - Taking a Peek Look at the beginning of the DataFrame End of explanation """ data3.tail() """ Explanation: DataFrame - Taking a Peek Look at the end of the DataFrame. End of explanation """ # simple readcsv phxtemps1 = pd.read_csv('phx-temps.csv') phxtemps1.head() """ Explanation: DataFrame Wrap Up Just remember, A DataFrame is just a bunch of Series grouped together. Any one dimensional slice returns a Series Any two dimensional slice returns another DataFrame. Elements are typically NumPy types or Objects. Panel Like DataFrame but 3 or more dimensions. IO Tools Robust IO tools to read in data from a variety of sources CSV - pd.read_csv() Clipboard - pd.read_clipboard() SQL - pd.read_sql_table() Excel - pd.read_excel() Plotting Matplotlib - s.plot() - Standard Python Plotting Library Trellis - rplot() - An 'R' inspired Matplotlib based plotting tool Bringing it Together - Data The csv file (phx-temps.csv) contains Phoenix weather data from GSOD:: 1973-01-01 00:00:00,53.1,37.9 1973-01-02 00:00:00,57.9,37.0 ... 2012-12-30 00:00:00,64.9,39.0 2012-12-31 00:00:00,55.9,41.0 Bringing it Together - Code Simple read_csv() End of explanation """ # define index, parse dates, name columns phxtemps2 = pd.read_csv( 'phx-temps.csv', index_col=0, names=['highs', 'lows'], parse_dates=True) phxtemps2.head() """ Explanation: Bringing it Together - Code Advanced read_csv(), parsing the dates and using them as the index, and naming the columns. End of explanation """ import matplotlib.pyplot as plt %matplotlib inline phxtemps2.plot() # pandas convenience method """ Explanation: Bringing it Together - Plot End of explanation """ phxtemps2['20120101':'20121231'].plot() """ Explanation: Boo, Pandas and Friends would cry if they saw such a plot. Bringing it Together - Plot Lets see a smaller slice of time: End of explanation """ phxtemps2['diff'] = phxtemps2.highs - phxtemps2.lows phxtemps2['20120101':'20121231'].plot() """ Explanation: Bringing it Together - Plot Lets operate on the DataFrame ... lets take the differnce between the highs and lows. End of explanation """
probml/pyprobml
notebooks/misc/clip_make_dataset_tpu_jax.ipynb
mit
import os assert os.environ["COLAB_TPU_ADDR"], "Make sure to select TPU from Edit > Notebook settings > Hardware accelerator" import os if "google.colab" in str(get_ipython()) and "COLAB_TPU_ADDR" in os.environ: import jax import jax.tools.colab_tpu jax.tools.colab_tpu.setup_tpu() print("Connected to TPU.") else: print('No TPU detected. Can be changed under "Runtime/Change runtime type".') import jax print("jax version {}".format(jax.__version__)) print("jax backend {}".format(jax.lib.xla_bridge.get_backend().platform)) print(jax.lib.xla_bridge.device_count()) print(jax.local_device_count()) import jax.numpy as jnp devices = jax.local_devices() print(f"jax devices:") devices """ Explanation: <a href="https://colab.research.google.com/github/always-newbie161/pyprobml/blob/hermissue122/notebooks/clip_make_dataset_tpu_jax.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Required Installations and Environment End of explanation """ %cd /content/ !git clone https://github.com/kingoflolz/CLIP_JAX.git cd / content / CLIP_JAX pip install ftfy regex tqdm dm-haiku import numpy as np from PIL import Image import time import clip_jax image_fn, text_fn, jax_params, jax_preprocess = clip_jax.load("ViT-B/32", "cpu", jit=True) """ Explanation: Cloning Clip_jax and loading the jax version of clip_model. End of explanation """ jax_params_repl = jax.device_put_replicated(jax_params, devices) image_fn_pmapped = jax.pmap(image_fn) """ Explanation: pmapping the encoding function and replicating the params. End of explanation """ ds_name = "imagenette/160px-v2" data_dir = "/root/tensorflow_datasets" # @title Choose whether if you want to make a copy of the dataset in the drive # @markdown Drive can be mounted to download the tfds into the drive for future uses, # @markdown downloaded ds can be found in `your_drive_path/MyDrive/$ds_name` to_load_into_drive = False # @param ["False", "True"] {type:"raw"} if to_load_into_drive: from google.colab import drive drive.mount("/content/drive") !mkdir /content/drive/MyDrive/$ds_name # your_drive_path data_dir = f"/content/drive/MyDrive/{ds_name}" """ Explanation: Dataset Download the dataset used here so that it just loads the downloaded dataset when used later. Change ds_name to the dataset required. End of explanation """ import tensorflow as tf import tensorflow_datasets as tfds try: tfds.load(ds_name, data_dir=data_dir) except: tfds.load(ds_name, data_dir=data_dir) """ Explanation: Loading tfds End of explanation """ len(devices) """ Explanation: Model End of explanation """ class Tpu_data_loader: def __init__(self, loader, split, batch_per_core, no_of_cores): self.loader = loader self.split = split self.batch_size = batch_per_core * no_of_cores class NumpyDataModule: def __init__(self, ds_name: str, data_dir: str): self.ds_name = ds_name self.data_dir = data_dir self.image_size = 224 self.mean = [0.48145466, 0.4578275, 0.40821073] self.std = [0.48145466, 0.4578275, 0.40821073] self.ds = None def preprocess(self, sample): image = sample["image"] """ `uint8` -> `float32`.""" image = tf.cast(image, tf.float32) image = tf.image.resize_with_crop_or_pad(image, self.image_size, self.image_size) image = (image - self.mean) / (self.std) image = tf.transpose(image, perm=[2, 0, 1]) return image def make_dataset(self, split, batch_per_core, no_of_cores): ds = self.ds[split] ds = ds.map(self.preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) ds = ds.batch(batch_per_core).batch(no_of_cores) return Tpu_data_loader( tfds.as_numpy(ds.prefetch(tf.data.experimental.AUTOTUNE)), split, batch_per_core, no_of_cores ) def prepare_data(self): self.ds, ds_info = tfds.load( self.ds_name, with_info=True, data_dir=self.data_dir, ) return ds_info dm = NumpyDataModule(ds_name=ds_name, data_dir=data_dir) ds_info = dm.prepare_data() """ Explanation: Datamodule which makes the numpy dataloaders for the dataset that return batches such that their leading dimension is len(devices) End of explanation """ train_loader = dm.make_dataset("train", batch_per_core=62, no_of_cores=len(devices)) test_loader = dm.make_dataset("validation", batch_per_core=61, no_of_cores=len(devices)) print(ds_info.splits[train_loader.split].num_examples) print(ds_info.splits[test_loader.split].num_examples) import tqdm def clip_extract(tpu_loader): clip_features = [] steps = (ds_info.splits[tpu_loader.split].num_examples // tpu_loader.batch_size) + 1 for i, batch in zip(tqdm.trange(steps), tpu_loader.loader): # the last batch is not parallised. if i == steps - 1: clip_encoded_batch = image_fn(jax_params, np.squeeze(batch, axis=0)) else: clip_encoded_batch = image_fn_pmapped(jax_params_repl, batch) clip_encoded_batch = jax.device_get(clip_encoded_batch) clip_features.append(clip_encoded_batch) clip_flattened_features = [fea.reshape(-1, 512) for fea in clip_features] coco_clip = np.concatenate(clip_flattened_features) return coco_clip clip_train = clip_extract(train_loader) clip_eval = clip_extract(test_loader) def make_tfds_and_save(numpy_data, name): tf_ds = tf.data.Dataset.from_tensor_slices(numpy_data) tf.data.experimental.save(tf_ds, f"/content/{name}") return tf_ds clip_train_ds = make_tfds_and_save(clip_train, "clip_train_ds") clip_test_ds = make_tfds_and_save(clip_eval, "clip_test_ds") """ Explanation: batch_per_core should be such that (n_examples//batch_per_core) % no_of_cores == 0 End of explanation """
MingChen0919/learning-apache-spark
notebooks/02-data-manipulation/2.5-subset-dataframe-by-row.ipynb
mit
mtcars = spark.read.csv('../../data/mtcars.csv', inferSchema=True, header=True) # correct first column name mtcars = mtcars.withColumnRenamed('_c0', 'model') mtcars.show(5) """ Explanation: Example dataset End of explanation """ mtcars.rdd.zipWithIndex().take(5) """ Explanation: Select Rows by index First, we need to add index to each rows. The zipWithIndex function zips the RDD elements with their corresponding index and returns the result as a new element. End of explanation """ mtcars.rdd.zipWithIndex().map(lambda x: [x[1]] + list(x[0])).take(5) """ Explanation: Now we can apply the map function to modify the structure of each element. Assume x is an element from the above RDD object, x has two elements: x[0] and x[1]. x[0] is an Row object, and x[1] is the index, which is an integer. We want to merge these two values to create a list. And we also want the first element in the list is the index. End of explanation """ header = ['index'] + mtcars.columns mtcars_df = mtcars.rdd.zipWithIndex().map(lambda x: [x[1]] + list(x[0])).toDF(header) mtcars_df.show(5) """ Explanation: Let's add column names and save the result. End of explanation """ mtcars_df.filter(mtcars_df.index.isin([1,2,4,6,9])).show() """ Explanation: After we obtain the index column, we can apply the pyspark.sql.DataFrame.filter function to select rows of the DataFrame. The filter function takes a column of types.BooleanType as input. Select specific rows End of explanation """ mtcars_df.filter(mtcars_df.index.between(5, 10)).show() """ Explanation: Select rows between a range End of explanation """ mtcars_df.filter(mtcars_df.index < 9).show() mtcars_df.filter(mtcars_df.index >= 14).show() """ Explanation: Select rows by a cutoff index End of explanation """ mtcars_df.filter(mtcars_df.cyl == 4).show() """ Explanation: Select rows by logical criteria Example 1: select rows when cyl = 4 End of explanation """ from pyspark.sql import functions as F """ Explanation: Example 2: select rows when vs = 1 and am = 1 When the filtering is based on multiple conditions (e.g., vs = 1 and am = 1), we use the conditions to build a new boolean type column. And we filter the DataFrame by the new column. End of explanation """ filtering_column = F.when((mtcars_df.vs == 1) & (mtcars_df.am == 1), 1).name('filter_col') filtering_column """ Explanation: <span style="color:red">Warning: when passing multiple conditions to the when() function, each condition has to be within a pair of parentheses</span> End of explanation """ all_original_columns = [eval('mtcars_df.' + c) for c in mtcars_df.columns] all_original_columns all_columns = all_original_columns + [filtering_column] all_columns new_mtcars_df = mtcars_df.select(all_columns) new_mtcars_df.show() """ Explanation: Now we need to add the new column to the original DataFrame. This can be done by applying the select() function to select all original columns as well as the new filtering columns. End of explanation """ new_mtcars_df.filter(new_mtcars_df.filter_col == 1).drop('filter_col').show() """ Explanation: Now we can filter the DataFrame by the requested conditions. After we filter the DataFrame, we can drop the filtering column. End of explanation """
sysid/nbs
ts/ResidualErrors.ipynb
mit
import matplotlib import matplotlib.pyplot as plt %matplotlib inline matplotlib.style.use('ggplot') fn = '/data/daily-minimum-temperatures-in-me.csv' df = pd.read_csv(fn, header=0, sep=';', decimal=',') #df.info() df.plot(figsize=(20,10)); """ Explanation: Residual Error http://machinelearningmastery.com/visualize-time-series-residual-forecast-errors-with-python/ Forecast errors on a time series forecasting problem are called residual errors or residuals. e = y - yhat We often stop there and summarize the skill of a model as a summary of this error. Instead, we can collect these individual residual errors across all forecasts and use them to better understand the forecast model. Generally, when exploring residual errors we are looking for patterns or structure. A sign of a pattern suggests that the errors are not random. We expect the residual errors to be random, because it means that the model has captured all of the structure and the only error left is the random fluctuations in the time series that cannot be modeled. A sign of a pattern or structure suggests that there is more information that a model could capture and use to make better predictions. End of explanation """ # create lagged dataset dataframe = pd.concat([df.ix[:,1].shift(1), df.ix[:,1]], axis=1) dataframe.columns = ['t-1', 't+1'] # split into train and test sets X = dataframe.values train_size = int(len(X) * 0.66) train, test = X[1:train_size], X[train_size:] train_X, train_y = train[:,0], train[:,1] test_X, test_y = test[:,0], test[:,1] """ Explanation: Baseline Model This is called the “naive forecast” or the persistence forecast model. After the dataset is loaded, it is phrased as a supervised learning problem. A lagged version of the dataset is created where the prior time step (t-1) is used as the input variable and the next time step (t+1) is taken as the output variable. End of explanation """ # persistence model predictions = [x for x in test_X] # calculate residuals residuals = [test_y[i]-predictions[i] for i in range(len(predictions))] predictions = pd.DataFrame(predictions) residuals = pd.DataFrame(residuals) print(residuals.head()) """ Explanation: The persistence model is applied by predicting the output value (y) as a copy of the input value (x). End of explanation """ fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(20,10), sharex=True) predictions.plot(ax=ax0) residuals.plot(ax=ax1); """ Explanation: Residual Line Plot The first plot is to look at the residual forecast errors over time as a line plot. We would expect the plot to be random around the value of 0 and not show any trend or cyclic structure. End of explanation """ residuals.describe() """ Explanation: Primarily, we are interested in the mean value of the residual errors. A value close to zero suggests no bias in the forecasts, whereas positive and negative values suggest a positive or negative bias in the forecasts made. It is useful to know about a bias in the forecasts as it can be directly corrected in forecasts prior to their use or evaluation. End of explanation """ fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(20,10)) residuals.hist(ax=ax0) residuals.plot(kind='kde', ax=ax1); """ Explanation: Residual Histogram and Density Plots We would expect the forecast errors to be normally distributed around a zero mean. Plots can help discover skews in this distribution. If the plot showed a distribution that was distinctly non-Gaussian, it would suggest that assumptions made by the modeling process were perhaps incorrect and that a different modeling method may be required. A large skew may suggest the opportunity for performing a transform to the data prior to modeling, such as taking the log or square root. End of explanation """ import scipy from statsmodels.graphics.gofplots import qqplot dist = scipy.stats.distributions.norm residuals = np.array(residuals) fig, ax = plt.subplots(1, 1, figsize=(20,10)) qqplot(residuals, dist=dist, line='r', fit=False, ax=ax); """ Explanation: Residual Q-Q Plot A Q-Q plot, or quantile plot, compares two distributions and can be used to see how similar or different they happen to be. The Q-Q plot can be used to quickly check the normality of the distribution of residual errors. The values are ordered and compared to an idealized Gaussian distribution. The comparison is shown as a scatter plot (theoretical on the x-axis and observed on the y-axis) where a match between the two distributions is shown as a diagonal line from the bottom left to the top-right of the plot. The plot is helpful to spot obvious departures from this expectation. Below is an example of a Q-Q plot of the residual errors. The x-axis shows the theoretical quantiles and the y-axis shows the sample quantiles. End of explanation """ from pandas.tools.plotting import autocorrelation_plot residuals = pd.DataFrame(residuals) autocorrelation_plot(residuals) from statsmodels.graphics.tsaplots import plot_acf from pandas.tools.plotting import autocorrelation_plot fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True, facecolor='white', figsize=(20,10)) autocorrelation_plot(residuals, ax=ax0) ax0.set(title='pandas', xlabel='Lag', ylabel='Autocorrelation') ax0.set_xlim([0, 50]) ax0.set_ylim([-0.2, None]) #plot_acf(residuals, ax=ax1, lags=len(residuals)-1) plot_acf(residuals, ax=ax1) ax1.set(title='statsmodels', xlabel='Lag', ylabel='Autocorrelation'); from pandas.tools.plotting import lag_plot lag_plot(residuals, lag=1); """ Explanation: Why does this not look like a line?? Residual Autocorrelation Plot Next, we can check for correlations between the errors over time. We would not expect there to be any correlation between the residuals. This would be shown by autocorrelation scores being below the threshold of significance (dashed and dotted horizontal lines on the plot). A significant autocorrelation in the residual plot suggests that the model could be doing a better job of incorporating the relationship between observations and lagged observations, called autoregression. End of explanation """
mne-tools/mne-tools.github.io
0.22/_downloads/90c71f0d36d740bc290fd9fa30bddd8c/plot_compute_covariance.ipynb
bsd-3-clause
import os.path as op import mne from mne.datasets import sample """ Explanation: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cover the basics of sensor covariance computations and construct a noise covariance matrix that can be used when computing the minimum-norm inverse solution. For more information, see minimum_norm_estimates. End of explanation """ data_path = sample.data_path() raw_empty_room_fname = op.join( data_path, 'MEG', 'sample', 'ernoise_raw.fif') raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname) raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(raw_fname) raw.set_eeg_reference('average', projection=True) raw.info['bads'] += ['EEG 053'] # bads + 1 more """ Explanation: Source estimation method such as MNE require a noise estimations from the recordings. In this tutorial we cover the basics of noise covariance and construct a noise covariance matrix that can be used when computing the inverse solution. For more information, see minimum_norm_estimates. End of explanation """ raw_empty_room.info['bads'] = [ bb for bb in raw.info['bads'] if 'EEG' not in bb] raw_empty_room.add_proj( [pp.copy() for pp in raw.info['projs'] if 'EEG' not in pp['desc']]) noise_cov = mne.compute_raw_covariance( raw_empty_room, tmin=0, tmax=None) """ Explanation: The definition of noise depends on the paradigm. In MEG it is quite common to use empty room measurements for the estimation of sensor noise. However if you are dealing with evoked responses, you might want to also consider resting state brain activity as noise. First we compute the noise using empty room recording. Note that you can also use only a part of the recording with tmin and tmax arguments. That can be useful if you use resting state as a noise baseline. Here we use the whole empty room recording to compute the noise covariance (tmax=None is the same as the end of the recording, see :func:mne.compute_raw_covariance). Keep in mind that you want to match your empty room dataset to your actual MEG data, processing-wise. Ensure that filters are all the same and if you use ICA, apply it to your empty-room and subject data equivalently. In this case we did not filter the data and we don't use ICA. However, we do have bad channels and projections in the MEG data, and, hence, we want to make sure they get stored in the covariance object. End of explanation """ events = mne.find_events(raw) epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5, baseline=(-0.2, 0.0), decim=3, # we'll decimate for speed verbose='error') # and ignore the warning about aliasing """ Explanation: Now that you have the covariance matrix in an MNE-Python object you can save it to a file with :func:mne.write_cov. Later you can read it back using :func:mne.read_cov. You can also use the pre-stimulus baseline to estimate the noise covariance. First we have to construct the epochs. When computing the covariance, you should use baseline correction when constructing the epochs. Otherwise the covariance matrix will be inaccurate. In MNE this is done by default, but just to be sure, we define it here manually. End of explanation """ noise_cov_baseline = mne.compute_covariance(epochs, tmax=0) """ Explanation: Note that this method also attenuates any activity in your source estimates that resemble the baseline, if you like it or not. End of explanation """ noise_cov.plot(raw_empty_room.info, proj=True) noise_cov_baseline.plot(epochs.info, proj=True) """ Explanation: Plot the covariance matrices Try setting proj to False to see the effect. Notice that the projectors in epochs are already applied, so proj parameter has no effect. End of explanation """ noise_cov_reg = mne.compute_covariance(epochs, tmax=0., method='auto', rank=None) """ Explanation: How should I regularize the covariance matrix? The estimated covariance can be numerically unstable and tends to induce correlations between estimated source amplitudes and the number of samples available. The MNE manual therefore suggests to regularize the noise covariance matrix (see cov_regularization_math), especially if only few samples are available. Unfortunately it is not easy to tell the effective number of samples, hence, to choose the appropriate regularization. In MNE-Python, regularization is done using advanced regularization methods described in [1]_. For this the 'auto' option can be used. With this option cross-validation will be used to learn the optimal regularization: End of explanation """ evoked = epochs.average() evoked.plot_white(noise_cov_reg, time_unit='s') """ Explanation: This procedure evaluates the noise covariance quantitatively by how well it whitens the data using the negative log-likelihood of unseen data. The final result can also be visually inspected. Under the assumption that the baseline does not contain a systematic signal (time-locked to the event of interest), the whitened baseline signal should be follow a multivariate Gaussian distribution, i.e., whitened baseline signals should be between -1.96 and 1.96 at a given time sample. Based on the same reasoning, the expected value for the :term:global field power (GFP) &lt;GFP&gt; is 1 (calculation of the GFP should take into account the true degrees of freedom, e.g. ddof=3 with 2 active SSP vectors): End of explanation """ noise_covs = mne.compute_covariance( epochs, tmax=0., method=('empirical', 'shrunk'), return_estimators=True, rank=None) evoked.plot_white(noise_covs, time_unit='s') """ Explanation: This plot displays both, the whitened evoked signals for each channels and the whitened :term:GFP. The numbers in the GFP panel represent the estimated rank of the data, which amounts to the effective degrees of freedom by which the squared sum across sensors is divided when computing the whitened :term:GFP. The whitened :term:GFP also helps detecting spurious late evoked components which can be the consequence of over- or under-regularization. Note that if data have been processed using signal space separation (SSS) [2], gradiometers and magnetometers will be displayed jointly because both are reconstructed from the same SSS basis vectors with the same numerical rank. This also implies that both sensor types are not any longer statistically independent. These methods for evaluation can be used to assess model violations. Additional introductory materials can be found here &lt;https://goo.gl/ElWrxe&gt;. For expert use cases or debugging the alternative estimators can also be compared (see sphx_glr_auto_examples_visualization_plot_evoked_whitening.py) and sphx_glr_auto_examples_inverse_plot_covariance_whitening_dspm.py): End of explanation """ evoked_meg = evoked.copy().pick('meg') noise_cov['method'] = 'empty_room' noise_cov_baseline['method'] = 'baseline' evoked_meg.plot_white([noise_cov_baseline, noise_cov], time_unit='s') """ Explanation: This will plot the whitened evoked for the optimal estimator and display the :term:GFPs &lt;GFP&gt; for all estimators as separate lines in the related panel. Finally, let's have a look at the difference between empty room and event related covariance, hacking the "method" option so that their types are shown in the legend of the plot. End of explanation """
Meena-Mani/SECOM_class_imbalance
secomdata_gbm.ipynb
mit
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.preprocessing import Imputer from sklearn.model_selection import train_test_split as tts from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_curve, auc from sklearn.metrics import confusion_matrix, classification_report,\ roc_auc_score, accuracy_score from sklearn.metrics import make_scorer, matthews_corrcoef from time import time from __future__ import division import warnings warnings.filterwarnings("ignore") SEED = 7 # random state url = "http://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom.data" secom = pd.read_table(url, header=None, delim_whitespace=True) url = "http://archive.ics.uci.edu/ml/machine-learning-databases/secom/secom_labels.data" y = pd.read_table(url, header=None, usecols=[0], squeeze=True, delim_whitespace=True) print 'The dataset has {} observations/rows and {} variables/columns.' \ .format(secom.shape[0], secom.shape[1]) print 'The ratio of majority class to minority class is {}:1.' \ .format(int(y[y == -1].size/y[y == 1].size)) """ Explanation: Using the Gradient Boosting Classifier for an imbalanced data set Date created: Jan 11, 2017 Last modified: Jan 12, 2017 Tags: GBM, hyperopt, imbalanced data set, semiconductor data About: Classify imbalanced semicondutor manufacturing data set using the Gradient Boosting Machine. Weight imbalanced classes using sample_weight. Tune hyperparameters manually and algorithmically using hyperopt. <h3>I. Introduction</h3> The SECOM dataset in the UCI Machine Learning Repository is semicondutor manufacturing data. There are 1567 records, 590 anonymized features and 104 fails. This makes it an imbalanced dataset with a 14:1 ratio of pass to fails. The process yield has a simple pass/fail response (encoded -1/1). <h4>Objective</h4> We consider some of the different approaches to classify imbalanced data. There are two strategies available when working with highly imbalanced classes: cost sensitive learning (penalizing misclassification of the minority class) resampling to balance the classes In previous exercises we looked at the one-class SVM and SVM+oversampling using SMOTE. (The full list of methods we have looked can be found here). In this exercise we consider the Gradient Boosting (GBM) classifier which is an ensemble method that has been shown to perform very well in machine learning competitions. To implement a cost-sensitive GBM, the GBM fit method with the sample_weight option is used to weigh individual observations. <h4>Methodology</h4> The sklearn GBM Classifier module uses the sample_weight mask to assign a vector of weights to corresponding observations. To balance the two classes, we will weigh them in inverse proportion to their respective class frequencies. At each stage, the boosting algorithm will fit the residuals from the previous step. We need to determine if the data needs to be reweighted in order to get optimal results. We will look at: - the baseline case (with equal class weights) - sample weights (in inverse proportion to the class frequencies) In addition, since hyperparameter tuning is an important part of GBM performance, we will look at: - Manual selection of parameters - Hyperparameter optimization with cross validation using hyperopt - Grid search optimization with cross validation We will see if any of these three parameter selection methods suggest the use of default versus sample weights. <h4>Preprocessing</h4> Like the Random Forest (RF) classifier, the GBM can handle continuous and categorical varibles and does not require transformations or preprocessing such as one-hot encoding or scaling. The only preprocessing needed is with regards to the missing data. For this data set, the measurements come from a large number of processes or sensors and many of the records are missing. In addition some measurements are identical/constant and so not useful for prediction. We will remove the columns that have high missing counts or constant values and estimate values for the rest of the missing data. These are the same steps used for the one-class SVM and a more detailed explanation can be seen there. End of explanation """ # dropping columns which have large number of missing entries m = map(lambda x: sum(secom[x].isnull()), xrange(secom.shape[1])) m_200thresh = filter(lambda i: (m[i] > 200), xrange(secom.shape[1])) secom_drop_200thresh = secom.dropna(subset=[m_200thresh], axis=1) dropthese = [x for x in secom_drop_200thresh.columns.values if \ secom_drop_200thresh[x].std() == 0] secom_drop_200thresh.drop(dropthese, axis=1, inplace=True) print 'The SECOM data set now has {} variables.'\ .format(secom_drop_200thresh.shape[1]) # imputing missing values for the random forest imp = Imputer(missing_values='NaN', strategy='median', axis=0) secom_imp = imp.fit_transform(secom_drop_200thresh) """ Explanation: <h3>II. Preprocessing </h3> We process the missing values first, dropping columns which have a large number of missing values and imputing values for those that have only a few missing values. The one-class SVM exercise has a more detailed version of these steps. End of explanation """ # split data into train and holdout sets # stratify the sample used for modeling to preserve the class proportions X_train, X_test, y_train, y_test = tts(secom_imp, y, \ test_size=0.2, stratify=y, random_state=5) # function to test GBC parameters def GBC(params, weight): clf = GradientBoostingClassifier(**params) if weight: sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) clf.fit(X_train, y_train, sample_weight) else: clf.fit(X_train, y_train) print_results(clf, X_train, X_test) # function to print results def print_results(clf, X_train, X_test): # training data results print 'Training set results:' y_pred = clf.predict(X_train) print 'The train set MCC: {0:4.3f}'\ .format(matthews_corrcoef(y_train, y_pred)) # test set results print '\nTest set results:' acc = clf.score(X_test, y_test) print("Accuracy: {:.4f}".format(acc)) y_pred = clf.predict(X_test) print '\nThe confusion matrix: ' cm = confusion_matrix(y_test, y_pred) print cm print '\nThe test set MCC: {0:4.3f}'\ .format(matthews_corrcoef(y_test, y_pred)) """ Explanation: <h3>III. GBM: baseline vs using sample_weight</h3> We will first compare baseline results with the performance of a model where the sample_weight is used. As discussed in previous exercises, the <i>Matthews correlation coefficient (MCC)</i> is used instead of the <i>Accuracy</i> to compute the score. End of explanation """ params = {'n_estimators': 800, 'max_depth': 3, 'subsample': 0.8, 'max_features' : 'sqrt', 'learning_rate': 0.019, 'min_samples_split': 2, 'random_state': SEED} GBC(params, 0) """ Explanation: <h4>A) Baseline</h4> End of explanation """ # RUN 1 Using the same parameters as the baseline params = {'n_estimators': 800, 'max_depth': 3, 'subsample': 0.8, 'max_features' : 'sqrt', 'learning_rate': 0.019, 'min_samples_split': 2, 'random_state': SEED} GBC(params, 1) # RUN 2 Manually selecting parameters to optimize the train/test MCC with sample weights params = {'n_estimators': 800, 'max_depth': 3, 'subsample': 0.7, 'max_features' : 'log2', 'learning_rate': 0.018, 'min_samples_split': 2, 'random_state': SEED} GBC(params, 1) """ Explanation: <h4>B) Sample weight</h4> End of explanation """ params = {'n_estimators': 800, 'max_depth': 3, 'subsample': 0.8, 'max_features' : 'sqrt', 'learning_rate': 0.019, 'min_samples_split': 2, 'random_state': SEED} # GBM clf = GradientBoostingClassifier(**params) clf.fit(X_train, y_train) gbm_importance = clf.feature_importances_ gbm_ranked_indices = np.argsort(clf.feature_importances_)[::-1] # Random Forest rf = RandomForestClassifier(n_estimators=100, random_state=7) rf.fit(X_train, y_train) rf_importance = rf.feature_importances_ rf_ranked_indices = np.argsort(rf.feature_importances_)[::-1] # printing results in a table importance_results = pd.DataFrame(index=range(1,16), columns=pd.MultiIndex.from_product([['GBM','RF'],['Feature #','Importance']])) importance_results.index.name = 'Rank' importance_results.loc[:,'GBM'] = list(zip(gbm_ranked_indices[:15], gbm_importance[gbm_ranked_indices[:15]])) importance_results.loc[:,'RF'] = list(zip(rf_ranked_indices[:15], rf_importance[rf_ranked_indices[:15]])) print importance_results """ Explanation: In the baseline case (where we do not adjust the weights), we get a high MCC score for the training set (0.97). The test MCC is 0.197 so there is a large gap between the train and test MCC. When sample weights are used, we get a test set MCC of 0.242 after tuning the parameters. The tuning parameters play a big role in the performance of the GBM. In Section III (D) we will look at the MCC trend over the number of estimators. This will allow us to adjust the complexity of the model. In Sections IV and V we will use the hyperopt and gridsearchCV modules to select the hyperparameters. <h4>C) Feature importance</h4> Here we compute the feature importance (using the baseline parameters) for the GBM. We also compare the results with the feature importance for the Random Forest. End of explanation """ # function to compute MCC vs number of trees def GBC_trend(weight): base_params = {'max_depth': 3, 'subsample': 0.8, 'max_features' : 'sqrt', 'learning_rate': 0.019, 'min_samples_split': 2, 'random_state': SEED} mcc_train = [] mcc_test = [] for i in range(500, 1600, 100): params = dict(base_params) ntrees = {'n_estimators': i} params.update(ntrees) clf = GradientBoostingClassifier(**params) if weight: sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) clf.fit(X_train, y_train, sample_weight) else: clf.fit(X_train, y_train) y_pred_train = clf.predict(X_train) mcc_train.append(matthews_corrcoef(y_train, y_pred_train)) y_pred_test = clf.predict(X_test) mcc_test.append(matthews_corrcoef(y_test, y_pred_test)) return mcc_train, mcc_test # plot fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(7,4)) plt.style.use('ggplot') mcc_train, mcc_test = GBC_trend(0) ax[0].plot(range(500, 1600, 100), mcc_train, color='magenta', label='train MCC' ) ax[0].plot(range(500, 1600, 100), mcc_test, color='olive', label='test MCC' ) ax[0].set_title('For default weights') mcc_train, mcc_test = GBC_trend(1) ax[1].plot(range(500, 1600, 100), mcc_train, color='magenta', label='train MCC' ) ax[1].plot(range(500, 1600, 100), mcc_test, color='olive', label='test MCC' ) ax[1].set_title('For sample weights') ax[0].set_ylabel('MCC') fig.text(0.5, 0.04, 'Boosting Iterations', ha='center', va='center') plt.xlim(500,1500) plt.ylim(-0.1, 1.1); plt.legend(bbox_to_anchor=(1.05, 0), loc='lower left'); """ Explanation: Roughly half the top fifteen most important features for the GBM were also the top fifteen computed for the Random Forest classifier. There are complex interactions between the parameters so we do not expect the two classifiers to give the same results. In Section IV where we optimize the hyperparameters, the nvar (number of variables) parameter will select variables according to their ranked importance. <h4>D) Number of estimators -- model complexity</h4> The GBM sequentially fits the function and the number of steps (the number of estimators) is specified by the ntree parameter. At some stage, the model complexity increases to the point where we start overfitting the data. Here we will plot the MCC as a function of the number of estimators for the train set and test set to determine a good value for ntree. When <i>Accuracy</i> is used as score, a plot of <i>Classification Error</i> (= <i>1 - Accuracy</i>) versus the <i>Number of Trees</i> can be used as a diagnostic to determine bias and overfitting. The term <i>(1 - MCC)</i>, however, is hard to interpret since MCC is calculated with all four terms of the confusion matrix. (I did make those plots out of curiosity and the trends are similar to those seen in an "Error vs no. of estimators" plot an example of which is presented on Slide 3 of this Hastie/Tibshirani lecture). End of explanation """ # defining the MCC metric to assess cross-validation def mcc_score(y_true, y_pred): mcc = matthews_corrcoef(y_true, y_pred) return mcc mcc_scorer = make_scorer(mcc_score, greater_is_better=True) # convert to DataFrame for easy indexing of number of variables (nvar) X_train = pd.DataFrame(X_train) X_test = pd.DataFrame(X_test) from hyperopt import fmin, tpe, hp, STATUS_OK, Trials def hyperopt_train_test(params): weight = params['weight'] X_ = X_train.loc[:, gbm_ranked_indices[:params['nvar']]] del params['nvar'], params['weight'] clf = GradientBoostingClassifier(**params) if weight: sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) return cross_val_score(clf, X_, y_train, scoring=mcc_scorer,\ fit_params={'sample_weight': sample_weight}).mean() else: return cross_val_score(clf, X_, y_train, scoring=mcc_scorer).mean() space = { 'n_estimators': hp.choice('n_estimators', range(700,1300, 100)), 'max_features': hp.choice('max_features', ['sqrt', 'log2']), 'max_depth': hp.choice('max_depth', range(2,5)), 'subsample': hp.choice('subsample', [0.6, 0.7, 0.8, 0.9]), 'min_samples_split': hp.choice('min_samples_split', [2, 3]), 'learning_rate': hp.choice('learning_rate', [0.01, 0.015, 0.018, 0.02, 0.025]), 'nvar': hp.choice('nvar', [200, 300, 400]), 'weight': hp.choice('weight', [0, 1]), # select sample_weight or default 'random_state': SEED } def f(params): mcc = hyperopt_train_test(params) # with a negative sign, we maximize the MCC return {'loss': -mcc, 'status': STATUS_OK} """ Explanation: Default weight option (left): After about 900 iterations, the GBM models all the training data perfectly. At the same time, there is a large gap in the holdout data classification results. This is a classic case of overfitting. Sample weight option (right): This plot was constructed using the same parameters at the default weight plot. This may account for some of the bias (lower values for MCC) we see for the training data line. From III B, we can see that even when we tune the parameters for the sample weight model, the MCC for the training set is lower that for the default weight model. This gives us some indication that using sample weights adds bias. <h3>IV. Hyperparameter optimization using Hyperopt</h3> The python hyperopt module by James Bergstra uses Bayesian optimization (based on a tree-structured Parzen density estimate--TPE) <a href="#ref1">[1]</a> to automatically select the best hyperparameters. This blog post provides examples of how this can be used with <i>sklearn</i> classifiers. We will use the <i>MCC</i> instead of the <i>Accuracy</i> for the cross-validation score. Note that since the hyperopt function fmin will minimze the MCC, we need to negate the MCC to maximize its value. End of explanation """ start = time() trials = Trials() best = fmin(f, space, algo=tpe.suggest, max_evals=100, trials=trials) print("HyperoptCV took %.2f seconds."% (time() - start)) print '\nBest parameters (by index):' print best """ Explanation: <h4>Run 1</h4> End of explanation """ params = {'n_estimators': 1200, 'max_depth': 3, 'subsample': 0.7, 'max_features' : 'log2', 'learning_rate': 0.018, 'min_samples_split': 3, 'random_state': SEED} train_ = X_train.loc[:, gbm_ranked_indices[:200]] test_ = X_test.loc[:, gbm_ranked_indices[:200]] clf = GradientBoostingClassifier(**params) sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) clf.fit(train_, y_train, sample_weight) print_results(clf, train_, test_) """ Explanation: We will apply the optimal hyperparameters selected via hyperopt above to the GBM classifier. The optimal parameters include nvar= 200 and the use of sample_weight. End of explanation """ trials = Trials() best = fmin(f, space, algo=tpe.suggest, max_evals=100, trials=trials) print '\nBest parameters (by index):' print best params = {'n_estimators': 700, 'max_depth': 4, 'subsample': 0.8, 'max_features' : 'log2', 'learning_rate': 0.018, 'min_samples_split': 2, 'random_state': SEED} train_ = X_train.loc[:, gbm_ranked_indices[:200]] test_ = X_test.loc[:, gbm_ranked_indices[:200]] clf = GradientBoostingClassifier(**params) sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) clf.fit(train_, y_train, sample_weight) print_results(clf, train_, test_) """ Explanation: <h4>Run 2</h4> I repeated the run with hyperopt a few times and in each case the optimal parameters include nvar= 200 and the use of sample_weight. There is a great deal of variability among the remaining parameters selected across the runs. This is an example of a second run. End of explanation """ start = time() trials = Trials() best = fmin(f, space, algo=tpe.suggest, max_evals=100, trials=trials) print("HyperoptCV took %.2f seconds."% (time() - start)) print '\nBest parameters (by index):' print best params = {'n_estimators': 1000, 'max_depth': 2, 'subsample': 0.9, 'max_features' : 'log2', 'learning_rate': 0.025, 'min_samples_split': 3, 'random_state': SEED} train_ = X_train.loc[:, gbm_ranked_indices[:200]] test_ = X_test.loc[:, gbm_ranked_indices[:200]] clf = GradientBoostingClassifier(**params) clf.fit(train_, y_train) print_results(clf, train_, test_) """ Explanation: <h4> Run 3 -- default weight</h4> For both Run 1 and Run 2, hyperopt selected the sample_weight option. This was the case for most of the runs though there were a few instances in which the default option was selected. This is an example: End of explanation """ # cv function def GBMCV(weight): clf = GradientBoostingClassifier(random_state=SEED) param_grid = {"n_estimators": [800, 900, 1000, 1200], "max_depth": [2, 3], "subsample": [0.6, 0.7, 0.8], "min_samples_split": [2, 3], "max_features": ["sqrt", "log2"], "learning_rate": [0.01, 0.015, 0.018, 0.02, 0.025]} # run grid search if weight: sample_weight = np.array([14 if i == -1 else 1 for i in y_train]) grid_search = GridSearchCV(clf, param_grid=param_grid, scoring=mcc_scorer, \ fit_params={'sample_weight': sample_weight}) else: grid_search = GridSearchCV(clf, param_grid=param_grid, scoring=mcc_scorer) start = time() grid_search.fit(X_train, y_train) # print results print("GridSearchCV took %.2f seconds for %d candidate parameter settings." % (time() - start, len(grid_search.grid_scores_))) print 'The best parameters:' print '{}\n'. format(grid_search.best_params_) print 'Results for model fitted with the best parameter:' y_true, y_pred = y_test, grid_search.predict(X_test) print(classification_report(y_true, y_pred)) print 'The confusion matrix: ' cm = confusion_matrix(y_true, y_pred) print cm print '\nThe Matthews correlation coefficient: {0:4.3f}'\ .format(matthews_corrcoef(y_test, y_pred)) # CV with default weights print "CV with default weights:" GBMCV(0) # CV with sample weights GBMCV(1) """ Explanation: The results from hyperopt (tested over ten or more runs) were quite variable and no conclusions can be made. By seeding the random_state parameter, we should be able to get reproducible results but since this was not the case here, we will need to investigate this further. <h3>V. Grid search with cross-validation</h3> End of explanation """
ProfessorKazarinoff/staticsite
content/code/unit_conversion/unit_conversion_table_in_Python.ipynb
gpl-3.0
meters = [0, 10, 20, 30, 40, 50] meters centimeters = meters*0.01 centimeters """ Explanation: In this post, we are going to construct a unit conversion table in python. The table will have columns for meters (m), centimeter (cm), and inches (in). We will start off with a list of values that will be our meter collumn. End of explanation """ centimeters = [value*100 for value in meters] centimeters """ Explanation: One way we can accomplish this is with list comprehensions. End of explanation """ meters = list(range(11)) meters = [value*10 for value in meters] meters """ Explanation: We can also create our originol meter list in a more dynamic way. End of explanation """ import numpy as np meters = np.arange(0,110,10) meters """ Explanation: Another way to accomplish this same thing is to use numpy's array function End of explanation """ centimeters = meters*100 centimeters table = np.concatenate((meters,centimeters),axis=0) print(table) np.reshape(table,(2,11)) table table.shape """ Explanation: Now making the centimeters list is a little easier, because we can multiply each value in the array by the scalar 100 with one opperation and no need for list comprehensions. End of explanation """
mne-tools/mne-tools.github.io
0.19/_downloads/2677ee623a2aeff54fe63131444b1844/plot_channel_epochs_image.ipynb
bsd-3-clause
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() """ Explanation: Visualize channel over epochs as an image This will produce what is sometimes called an event related potential / field (ERP/ERF) image. Two images are produced, one with a good channel and one with a channel that does not show any evoked field. It is also demonstrated how to reorder the epochs using a 1D spectral embedding as described in [1]_. End of explanation """ raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' event_id, tmin, tmax = 1, -0.2, 0.4 # Setup for reading the raw data raw = io.read_raw_fif(raw_fname) events = mne.read_events(event_fname) # Set up pick list: EEG + MEG - bad channels (modify to your needs) raw.info['bads'] = ['MEG 2443', 'EEG 053'] # Create epochs, here for gradiometers + EOG only for simplicity epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=('grad', 'eog'), baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, eog=150e-6)) """ Explanation: Set parameters End of explanation """ # and order with spectral reordering # If you don't have scikit-learn installed set order_func to None from sklearn.cluster.spectral import spectral_embedding # noqa from sklearn.metrics.pairwise import rbf_kernel # noqa def order_func(times, data): this_data = data[:, (times > 0.0) & (times < 0.350)] this_data /= np.sqrt(np.sum(this_data ** 2, axis=1))[:, np.newaxis] return np.argsort(spectral_embedding(rbf_kernel(this_data, gamma=1.), n_components=1, random_state=0).ravel()) good_pick = 97 # channel with a clear evoked response bad_pick = 98 # channel with no evoked response # We'll also plot a sample time onset for each trial plt_times = np.linspace(0, .2, len(epochs)) plt.close('all') mne.viz.plot_epochs_image(epochs, [good_pick, bad_pick], sigma=.5, order=order_func, vmin=-250, vmax=250, overlay_times=plt_times, show=True) """ Explanation: Show event-related fields images End of explanation """
dbenn/photometry_tools
LocalCoordAperturePhotometry.ipynb
mit
import os from random import random from collections import OrderedDict import numpy as np import pandas as pd from astropy.io import fits from astropy.visualization import astropy_mpl_style import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from matplotlib.patches import Circle # TODO: why importing as tuple? from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage, AnnotationBbox) plt.style.use(astropy_mpl_style) %matplotlib inline from PythonPhot import aper """ Explanation: Local coordinate aperture photometry for input to AAVSO DSLR data worksheet Uses Python 3, astropy, matplotlib, PythonPhot Definitions Imports End of explanation """ def multi_file_photometry(fits_root, fits_files, data_index, coords, dataframe, aperture_radius, inner_sky_radius, outer_sky_radius, gain=1, zeropoint=0, suffix='.fit'): for fits_file in fits_files: fits_file_path = os.path.join(fits_root, fits_file) hdus = fits.open(fits_file_path) instr_mags = [] for x, y in coords: time, mag = aperture_photometry(hdus[data_index], x, y, aperture_radius, inner_sky_radius, outer_sky_radius, gain=gain, zeropoint=zeropoint) instr_mags.append(mag) dataframe[fits_file[0:fits_file.rindex(suffix)]] = [time] + instr_mags """ Explanation: Functions Photometry of a list of FITS files, creating a table of times and instrumental magnitudes End of explanation """ def aperture_photometry(hdu, x, y, aperture_radius, inner_sky_radius, outer_sky_radius, gain=1, zeropoint=0): image_data = hdu.data time = hdu.header[time_name] mag, magerr, flux, fluxerr, sky, skyerr, badflag, outstr = \ aper.aper(image_data, x, y, phpadu=gain, apr=aperture_radius, zeropoint=zeropoint, skyrad=[inner_sky_radius, outer_sky_radius], exact=True) return time, mag[0] """ Explanation: Single image+coordinate photometry, returning a time and instrumental magnitude Invoked by multi_file_photometry() End of explanation """ def show_image(image_data, coord_map, aperture_size, annotate=True, vmin=10, vmax=200, figx=20, figy=10): fig = plt.figure(figsize=(figx, figy)) plt.imshow(image_data, cmap='gray', vmin=vmin, vmax=vmax) plt.gca().invert_yaxis() plt.colorbar() if annotate: for designation in coord_map: xy = coord_map[designation] annotate_image(fig.axes[0], designation, xy, aperture_size) plt.show() """ Explanation: Display an image with target and reference stars annotated, to sanity check local coordinates End of explanation """ def annotate_image(axis, designation, xy, aperture_size): axis.plot(xy[0], xy[1], 'o', markersize=aperture_size, markeredgecolor='r', markerfacecolor='none', markeredgewidth=2) offsetbox = TextArea(designation, minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(-20, 40+random()*10-10), xycoords='data', boxcoords="offset points", arrowprops=dict(arrowstyle="->")) axis.add_artist(ab) """ Explanation: Annotate plot axis with coordinate positions and designations Invoked by show_image() End of explanation """ # Instrumental magnitude output file path instr_mag_file_root = "/Users/david/aavso/dslr-photometry/working" instr_mag_csv_file = "instr_mags.csv" # FITS file directory fits_root = "/Users/david/aavso/dslr-photometry/working" # B, G, and R FITS file prefixes to identify files, # e.g. stk-median-g matches stk-median-g1.fit, stk-median-g2.fit, ... fits_prefixes = ["stk-median-b", "stk-median-g", "stk-median-r"] # FITS file data HDU index data_index = 0 # Time column name time_name = "JD" """ Explanation: Inputs Change these to suit your environment File settings End of explanation """ # TODO: this ordering only holds because I'm using Py 3.6!! Change to position_map[...] = () # Ordered dictionary of object names/IDs to local coordinates position_map = OrderedDict({ # ** Your name-coordinate mappings go here ** "eta Car":(2188.101,1350.250), "45 000-BBR-533":(2911.183,1727.747), # (furthest east) (CHK) "46 000-BBR-603":(2088.885,1067.720), # (furthest west) "46 000-BBS-066":(1082.639,1707.460), # (furthest east) "47 000-BBR-573":(2501.905,1350.379), # (furthest east) "51 000-BBR-998":(992.812,1149.498), # (furthest east) "52 000-BBR-795":(2321.108,2213.099), # (furthest east) "55 000-BBR-563":(2629.498,1445.678) # ** END ** }) """ Explanation: Map of object designations to local coordinates End of explanation """ # Aperture radii measurement_aperture = 12 inner_sky_annulus = 15 outer_sky_annulus = 20 # ph/ADU # Note: PythonPhot's aperture photometry function takes a phadu parameter. # Assumption: this is photons/ADU or e-/ADU, i.e. gain. gain=1.67 """ Explanation: Aperture radii and gain End of explanation """ files = os.listdir(fits_root) fits_files = [] for fits_prefix in fits_prefixes: fits_files += sorted([file for file in files if fits_prefix in file]) """ Explanation: Outputs Find B, G, R files in the FITS file directory End of explanation """ fits_file = fits_files[0] hdus = fits.open(os.path.join(fits_root, fits_file)) image_data = hdus[data_index].data median = np.median(image_data) show_image(image_data, position_map, measurement_aperture, annotate=True, vmin=10, vmax=median*4) """ Explanation: Aperture location sanity check by visual inspection Arbitrarily choose the first G FITS file End of explanation """ # Create empty table with time and object headers pd.options.display.float_format = '{:,.6f}'.format instr_mag_df = pd.DataFrame() names = [name for name in position_map] instr_mag_df['name'] = [time_name] + names instr_mag_df.set_index('name', inplace=True) # Carry out photometry on B, G, R FITS files, yielding instrumental magnitudes positions = position_map.values() multi_file_photometry(fits_root, fits_files, data_index, positions, instr_mag_df, measurement_aperture, inner_sky_annulus, outer_sky_annulus, gain=gain) # Save photometry table as CSV instr_mag_csv_path = os.path.join(instr_mag_file_root, instr_mag_csv_file) instr_mag_df.T.to_csv(instr_mag_csv_path) # Display photometry table instr_mag_df.T # TODO: to do this properly, create separate IM DFs above and summarise each here # The multiple DFs above can be merged for display and written as a single file for # input into next stage of analysis (spreadsheet) # cols = [col for col in instr_mag_df.columns]# if col.startswith(fits_prefixes[0])] # mean_df = pd.DataFrame(columns=cols) # stdev_df = pd.DataFrame(columns=cols) # for fits_prefix in fits_prefixes: # row_names = instr_mag_df.T.columns # row = [fits_prefix] # for row_index, row_name in enumerate(row_names): # row.append(instr_mag_df[cols].loc[row_name]) # #mean_df.loc[row_index] = [row_name, np.mean(row)] # #stdev_df.loc[row_index] = [row_name, np.mean(row)] # mean_df # stdev_df """ Explanation: Aperture photometry End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/ncc/cmip6/models/noresm2-mh/ocean.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-mh', 'ocean') """ Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NCC Source ID: NORESM2-MH Topic: Ocean Sub-Topics: Timestepping Framework, Advection, Lateral Physics, Vertical Physics, Uplow Boundaries, Boundary Forcing. Properties: 133 (101 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:24 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Seawater Properties 3. Key Properties --&gt; Bathymetry 4. Key Properties --&gt; Nonoceanic Waters 5. Key Properties --&gt; Software Properties 6. Key Properties --&gt; Resolution 7. Key Properties --&gt; Tuning Applied 8. Key Properties --&gt; Conservation 9. Grid 10. Grid --&gt; Discretisation --&gt; Vertical 11. Grid --&gt; Discretisation --&gt; Horizontal 12. Timestepping Framework 13. Timestepping Framework --&gt; Tracers 14. Timestepping Framework --&gt; Baroclinic Dynamics 15. Timestepping Framework --&gt; Barotropic 16. Timestepping Framework --&gt; Vertical Physics 17. Advection 18. Advection --&gt; Momentum 19. Advection --&gt; Lateral Tracers 20. Advection --&gt; Vertical Tracers 21. Lateral Physics 22. Lateral Physics --&gt; Momentum --&gt; Operator 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff 24. Lateral Physics --&gt; Tracers 25. Lateral Physics --&gt; Tracers --&gt; Operator 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity 28. Vertical Physics 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum 32. Vertical Physics --&gt; Interior Mixing --&gt; Details 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum 35. Uplow Boundaries --&gt; Free Surface 36. Uplow Boundaries --&gt; Bottom Boundary Layer 37. Boundary Forcing 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing 1. Key Properties Ocean key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of ocean model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean model code (NEMO 3.6, MOM 5.0,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_family') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OGCM" # "slab ocean" # "mixed layer ocean" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Model Family Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of ocean model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.basic_approximations') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Primitive equations" # "Non-hydrostatic" # "Boussinesq" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Basic approximations made in the ocean. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Potential temperature" # "Conservative temperature" # "Salinity" # "U-velocity" # "V-velocity" # "W-velocity" # "SSH" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.5. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of prognostic variables in the ocean component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear" # "Wright, 1997" # "Mc Dougall et al." # "Jackett et al. 2006" # "TEOS 2010" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Seawater Properties Physical properties of seawater in ocean 2.1. Eos Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EOS for sea water End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_temp') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Potential temperature" # "Conservative temperature" # TODO - please enter value(s) """ Explanation: 2.2. Eos Functional Temp Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Temperature used in EOS for sea water End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_salt') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Practical salinity Sp" # "Absolute salinity Sa" # TODO - please enter value(s) """ Explanation: 2.3. Eos Functional Salt Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Salinity used in EOS for sea water End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Pressure (dbars)" # "Depth (meters)" # TODO - please enter value(s) """ Explanation: 2.4. Eos Functional Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Depth or pressure used in EOS for sea water ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_freezing_point') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "TEOS 2010" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 2.5. Ocean Freezing Point Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Equation used to compute the freezing point (in deg C) of seawater, as a function of salinity and pressure End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_specific_heat') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 2.6. Ocean Specific Heat Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specific heat in ocean (cpocean) in J/(kg K) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_reference_density') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 2.7. Ocean Reference Density Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Boussinesq reference density (rhozero) in kg / m3 End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.reference_dates') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Present day" # "21000 years BP" # "6000 years BP" # "LGM" # "Pliocene" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Bathymetry Properties of bathymetry in ocean 3.1. Reference Dates Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Reference date of bathymetry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.type') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.2. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the bathymetry fixed in time in the ocean ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.ocean_smoothing') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.3. Ocean Smoothing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe any smoothing or hand editing of bathymetry in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.source') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.4. Source Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe source of bathymetry in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.isolated_seas') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Nonoceanic Waters Non oceanic waters treatement in ocean 4.1. Isolated Seas Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how isolated seas is performed End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.river_mouth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. River Mouth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how river mouth mixing or estuaries specific treatment is performed End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Software Properties Software properties of ocean code 5.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Key Properties --&gt; Resolution Resolution in the ocean grid 6.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.2. Canonical Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.range_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.3. Range Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Range of horizontal resolution with spatial details, eg. 50(Equator)-100km or 0.1-0.5 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 6.4. Number Of Horizontal Gridpoints Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 6.5. Number Of Vertical Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of vertical levels resolved on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.6. Is Adaptive Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Default is False. Set true if grid resolution changes during execution. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.thickness_level_1') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 6.7. Thickness Level 1 Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Thickness of first surface ocean level (in meters) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Key Properties --&gt; Tuning Applied Tuning methodology for ocean component 7.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state (e.g THC, AABW, regional means etc) used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Key Properties --&gt; Conservation Conservation in the ocean component 8.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Brief description of conservation methodology End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.scheme') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Energy" # "Enstrophy" # "Salt" # "Volume of ocean" # "Momentum" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Properties conserved in the ocean by the numerical schemes End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.consistency_properties') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.3. Consistency Properties Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Any additional consistency properties (energy conversion, pressure gradient discretisation, ...)? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.corrected_conserved_prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.4. Corrected Conserved Prognostic Variables Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Set of variables which are conserved by more than the numerical scheme alone. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.was_flux_correction_used') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 8.5. Was Flux Correction Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Does conservation involve flux correction ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Grid Ocean grid 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of grid in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.vertical.coordinates') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Z-coordinate" # "Z*-coordinate" # "S-coordinate" # "Isopycnic - sigma 0" # "Isopycnic - sigma 2" # "Isopycnic - sigma 4" # "Isopycnic - other" # "Hybrid / Z+S" # "Hybrid / Z+isopycnic" # "Hybrid / other" # "Pressure referenced (P)" # "P*" # "Z**" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Grid --&gt; Discretisation --&gt; Vertical Properties of vertical discretisation in ocean 10.1. Coordinates Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of vertical coordinates in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.vertical.partial_steps') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 10.2. Partial Steps Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Using partial steps with Z or Z vertical coordinate in ocean ?* End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Lat-lon" # "Rotated north pole" # "Two north poles (ORCA-style)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11. Grid --&gt; Discretisation --&gt; Horizontal Type of horizontal discretisation scheme in ocean 11.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal grid type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.staggering') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Arakawa B-grid" # "Arakawa C-grid" # "Arakawa E-grid" # "N/a" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Staggering Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal grid staggering type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Finite difference" # "Finite volumes" # "Finite elements" # "Unstructured grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.3. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12. Timestepping Framework Ocean Timestepping Framework 12.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of time stepping in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.diurnal_cycle') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Via coupling" # "Specific treatment" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.2. Diurnal Cycle Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Diurnal cycle type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.tracers.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Leap-frog + Asselin filter" # "Leap-frog + Periodic Euler" # "Predictor-corrector" # "Runge-Kutta 2" # "AM3-LF" # "Forward-backward" # "Forward operator" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13. Timestepping Framework --&gt; Tracers Properties of tracers time stepping in ocean 13.1. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracers time stepping scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.tracers.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracers time step (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Preconditioned conjugate gradient" # "Sub cyling" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14. Timestepping Framework --&gt; Baroclinic Dynamics Baroclinic dynamics in ocean 14.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Baroclinic dynamics type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Leap-frog + Asselin filter" # "Leap-frog + Periodic Euler" # "Predictor-corrector" # "Runge-Kutta 2" # "AM3-LF" # "Forward-backward" # "Forward operator" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Baroclinic dynamics scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.3. Time Step Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Baroclinic time step (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.barotropic.splitting') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "split explicit" # "implicit" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15. Timestepping Framework --&gt; Barotropic Barotropic time stepping in ocean 15.1. Splitting Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time splitting method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.barotropic.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.2. Time Step Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Barotropic time step (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.vertical_physics.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16. Timestepping Framework --&gt; Vertical Physics Vertical physics time stepping in ocean 16.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Details of vertical time stepping in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17. Advection Ocean advection 17.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of advection in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Flux form" # "Vector form" # TODO - please enter value(s) """ Explanation: 18. Advection --&gt; Momentum Properties of lateral momemtum advection scheme in ocean 18.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of lateral momemtum advection scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 18.2. Scheme Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean momemtum advection scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.ALE') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 18.3. ALE Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Using ALE for vertical advection ? (if vertical coordinates are sigma) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 19. Advection --&gt; Lateral Tracers Properties of lateral tracer advection scheme in ocean 19.1. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral tracer advection scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.flux_limiter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 19.2. Flux Limiter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Monotonic flux limiter for lateral tracer advection scheme in ocean ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.effective_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 19.3. Effective Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Effective order of limited lateral tracer advection scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19.4. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Descriptive text for lateral tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Ideal age" # "CFC 11" # "CFC 12" # "SF6" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 19.5. Passive Tracers Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Passive tracers advected End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers_advection') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19.6. Passive Tracers Advection Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Is advection of passive tracers different than active ? if so, describe. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.vertical_tracers.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 20. Advection --&gt; Vertical Tracers Properties of vertical tracer advection scheme in ocean 20.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Descriptive text for vertical tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.vertical_tracers.flux_limiter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 20.2. Flux Limiter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Monotonic flux limiter for vertical tracer advection scheme in ocean ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 21. Lateral Physics Ocean lateral physics 21.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of lateral physics in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Eddy active" # "Eddy admitting" # TODO - please enter value(s) """ Explanation: 21.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of transient eddy representation in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Horizontal" # "Isopycnal" # "Isoneutral" # "Geopotential" # "Iso-level" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22. Lateral Physics --&gt; Momentum --&gt; Operator Properties of lateral physics operator for momentum in ocean 22.1. Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Direction of lateral physics momemtum scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Harmonic" # "Bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.2. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral physics momemtum scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Second order" # "Higher order" # "Flux limiter" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.3. Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Discretisation of lateral physics momemtum scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Space varying" # "Time + space varying (Smagorinsky)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff Properties of eddy viscosity coeff in lateral physics momemtum scheme in the ocean 23.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Lateral physics momemtum eddy viscosity coeff type in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.constant_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 23.2. Constant Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant, value of eddy viscosity coeff in lateral physics momemtum scheme (in m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.variable_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 23.3. Variable Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If space-varying, describe variations of eddy viscosity coeff in lateral physics momemtum scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 23.4. Coeff Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe background eddy viscosity coeff in lateral physics momemtum scheme (give values in m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_backscatter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 23.5. Coeff Backscatter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there backscatter in eddy viscosity coeff in lateral physics momemtum scheme ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.mesoscale_closure') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 24. Lateral Physics --&gt; Tracers Properties of lateral physics for tracers in ocean 24.1. Mesoscale Closure Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there a mesoscale closure in the lateral physics tracers scheme ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.submesoscale_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 24.2. Submesoscale Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there a submesoscale mixing parameterisation (i.e Fox-Kemper) in the lateral physics tracers scheme ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Horizontal" # "Isopycnal" # "Isoneutral" # "Geopotential" # "Iso-level" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25. Lateral Physics --&gt; Tracers --&gt; Operator Properties of lateral physics operator for tracers in ocean 25.1. Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Direction of lateral physics tracers scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Harmonic" # "Bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.2. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral physics tracers scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Second order" # "Higher order" # "Flux limiter" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.3. Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Discretisation of lateral physics tracers scheme in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Space varying" # "Time + space varying (Smagorinsky)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff Properties of eddy diffusity coeff in lateral physics tracers scheme in the ocean 26.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Lateral physics tracers eddy diffusity coeff type in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.constant_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 26.2. Constant Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant, value of eddy diffusity coeff in lateral physics tracers scheme (in m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.variable_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 26.3. Variable Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If space-varying, describe variations of eddy diffusity coeff in lateral physics tracers scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_background') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 26.4. Coeff Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe background eddy diffusity coeff in lateral physics tracers scheme (give values in m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_backscatter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 26.5. Coeff Backscatter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there backscatter in eddy diffusity coeff in lateral physics tracers scheme ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "GM" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity Properties of eddy induced velocity (EIV) in lateral physics tracers scheme in the ocean 27.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV in lateral physics tracers in the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.constant_val') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 27.2. Constant Val Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If EIV scheme for tracers is constant, specify coefficient value (M2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.flux_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.3. Flux Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV flux (advective or skew) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.added_diffusivity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.4. Added Diffusivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV added diffusivity (constant, flow dependent or none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 28. Vertical Physics Ocean Vertical Physics 28.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of vertical physics in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.details.langmuir_cells_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details Properties of vertical physics in ocean 29.1. Langmuir Cells Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there Langmuir cells mixing in upper ocean ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure - TKE" # "Turbulent closure - KPP" # "Turbulent closure - Mellor-Yamada" # "Turbulent closure - Bulk Mixed Layer" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers *Properties of boundary layer (BL) mixing on tracers in the ocean * 30.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of boundary layer mixing for tracers in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.2. Closure Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If turbulent BL mixing of tracers, specific order of closure (0, 1, 2.5, 3) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.3. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant BL mixing of tracers, specific coefficient (m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background BL mixing of tracers coefficient, (schema and value in m2/s - may by none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure - TKE" # "Turbulent closure - KPP" # "Turbulent closure - Mellor-Yamada" # "Turbulent closure - Bulk Mixed Layer" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum *Properties of boundary layer (BL) mixing on momentum in the ocean * 31.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of boundary layer mixing for momentum in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 31.2. Closure Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If turbulent BL mixing of momentum, specific order of closure (0, 1, 2.5, 3) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 31.3. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant BL mixing of momentum, specific coefficient (m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 31.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background BL mixing of momentum coefficient, (schema and value in m2/s - may by none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.convection_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Non-penetrative convective adjustment" # "Enhanced vertical diffusion" # "Included in turbulence closure" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32. Vertical Physics --&gt; Interior Mixing --&gt; Details *Properties of interior mixing in the ocean * 32.1. Convection Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of vertical convection in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.tide_induced_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32.2. Tide Induced Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how tide induced mixing is modelled (barotropic, baroclinic, none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.double_diffusion') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 32.3. Double Diffusion Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there double diffusion End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.shear_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 32.4. Shear Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there interior shear mixing End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure / TKE" # "Turbulent closure - Mellor-Yamada" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers *Properties of interior mixing on tracers in the ocean * 33.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of interior mixing for tracers in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 33.2. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant interior mixing of tracers, specific coefficient (m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.profile') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 33.3. Profile Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the background interior mixing using a vertical profile for tracers (i.e is NOT constant) ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 33.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background interior mixing of tracers coefficient, (schema and value in m2/s - may by none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure / TKE" # "Turbulent closure - Mellor-Yamada" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum *Properties of interior mixing on momentum in the ocean * 34.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of interior mixing for momentum in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 34.2. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant interior mixing of momentum, specific coefficient (m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.profile') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 34.3. Profile Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the background interior mixing using a vertical profile for momentum (i.e is NOT constant) ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 34.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background interior mixing of momentum coefficient, (schema and value in m2/s - may by none) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 35. Uplow Boundaries --&gt; Free Surface Properties of free surface in ocean 35.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of free surface in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear implicit" # "Linear filtered" # "Linear semi-explicit" # "Non-linear implicit" # "Non-linear filtered" # "Non-linear semi-explicit" # "Fully explicit" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 35.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Free surface scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.embeded_seaice') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 35.3. Embeded Seaice Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the sea-ice embeded in the ocean model (instead of levitating) ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36. Uplow Boundaries --&gt; Bottom Boundary Layer Properties of bottom boundary layer in ocean 36.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of bottom boundary layer in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.type_of_bbl') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Diffusive" # "Acvective" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 36.2. Type Of Bbl Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of bottom boundary layer in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.lateral_mixing_coef') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 36.3. Lateral Mixing Coef Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If bottom BL is diffusive, specify value of lateral mixing coefficient (in m2/s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.sill_overflow') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36.4. Sill Overflow Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe any specific treatment of sill overflows End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37. Boundary Forcing Ocean boundary forcing 37.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of boundary forcing in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.surface_pressure') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.2. Surface Pressure Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how surface pressure is transmitted to ocean (via sea-ice, nothing specific,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum_flux_correction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.3. Momentum Flux Correction Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any type of ocean surface momentum flux correction and, if applicable, how it is applied and where. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers_flux_correction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.4. Tracers Flux Correction Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any type of ocean surface tracers flux correction and, if applicable, how it is applied and where. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.wave_effects') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.5. Wave Effects Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how wave effects are modelled at ocean surface. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.river_runoff_budget') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.6. River Runoff Budget Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how river runoff from land surface is routed to ocean and any global adjustment done. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.geothermal_heating') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.7. Geothermal Heating Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how geothermal heating is present at ocean bottom. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum.bottom_friction.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear" # "Non-linear" # "Non-linear (drag function of speed of tides)" # "Constant drag coefficient" # "None" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction Properties of momentum bottom friction in ocean 38.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of momentum bottom friction in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum.lateral_friction.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Free-slip" # "No-slip" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction Properties of momentum lateral friction in ocean 39.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of momentum lateral friction in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "1 extinction depth" # "2 extinction depth" # "3 extinction depth" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration Properties of sunlight penetration scheme in ocean 40.1. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of sunlight penetration scheme in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.ocean_colour') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 40.2. Ocean Colour Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the ocean sunlight penetration scheme ocean colour dependent ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.extinction_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 40.3. Extinction Depth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe and list extinctions depths for sunlight penetration scheme (if applicable). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_atmopshere') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Freshwater flux" # "Virtual salt flux" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing Properties of surface fresh water forcing in ocean 41.1. From Atmopshere Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface fresh water forcing from atmos in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_sea_ice') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Freshwater flux" # "Virtual salt flux" # "Real salt flux" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41.2. From Sea Ice Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface fresh water forcing from sea-ice in ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.forced_mode_restoring') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 41.3. Forced Mode Restoring Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface salinity restoring in forced mode (OMIP) End of explanation """
megbedell/wobble
notebooks/demo.ipynb
mit
data = wobble.Data('../data/51peg_e2ds.hdf5') """ Explanation: First, you'll need some data to load up. You can download example HARPS data files (and results files) to play around with linked in the documentation. Here we'll assume that you have the data 51peg_e2ds.hdf5 saved in the wobble/data directory. By default, loading the data will load all echelle orders and all epochs in the data file; you can change this with the optional orders and epochs kwargs, which each take lists (or 1-d numpy arrays) of indices for the desired orders/epochs to load. End of explanation """ r = 0 # index of echelle order to plot n = 0 # index of epoch to plot plt.plot(data.xs[r][n], data.ys[r][n], 'k.', ms=6) mask = data.ivars[r][n] <= 1.e-8 # masked-out bad data plt.plot(data.xs[r][n][mask], data.ys[r][n][mask], 'w.', ms=4) plt.ylabel('ln(flux)') plt.xlabel('ln(wave)'); """ Explanation: The data we just loaded are assumed to be continuum normalized, with regions of bad data (negative flux values or very low SNR) "masked out" by setting their uncertainties to be infinite. In this example, the data are also in units of log(wavelength) vs. log(flux). End of explanation """ results = wobble.Results(data=data) """ Explanation: Now let's create a results object in which to store the outputs of wobble: End of explanation """ r = 67 # index into data.orders for the desired order model = wobble.Model(data, results, r) model.add_star('star') model.add_telluric('tellurics') wobble.optimize_order(model) """ Explanation: This object is not currently populated with useful information (because we haven't optimized anything yet!), but once it is we'll be able to save it with the results.write('filename.hdf5') function. A saved results file can be loaded as: results = wobble.Results(filename='filename.hdf5') Here's a minimal example of optimizing a model consisting of a star and tellurics for a single order: End of explanation """ n = 40 # epoch to plot results.plot_spectrum(r, n, data, 'demo1.png') from IPython.display import Image Image(filename='demo1.png') """ Explanation: The results have been automatically saved and we can now view them by generating a plot: End of explanation """ results2 = wobble.Results(data=data) model = wobble.Model(data, results2, r) model.add_star('star') model.add_telluric('tellurics', variable_bases=2) wobble.optimize_order(model) results2.plot_spectrum(r, n, data, 'demo2.png') Image(filename='demo2.png') """ Explanation: The residuals look good for the star but not great around the tellurics. Let's try running with variable tellurics. End of explanation """ plt.errorbar(results2.dates, results2.star_rvs[r] + results2.bervs, 1./np.sqrt(results2.star_ivars_rvs[r]), fmt='o', ms=5, elinewidth=1) plt.xlabel('JD') plt.ylabel(r'RV (m s$^{-1}$)') plt.xlim([2456505, 2456570]); """ Explanation: Looks better! Here are the RVs for this single order. Once we run on all orders, we can combine the order-by-order velocities using results.combine_orders('star') and access the final (non-barycentric-corrected RVs as results.star_time_rvs. End of explanation """ data = wobble.Data('../data/51peg_e2ds.hdf5', orders=np.arange(65,70)) """ Explanation: Now let's generalize this to multiple orders and get RVs for the full* spectrum: * not actually the complete spectrum in this tutorial because that would take a long time to run Here we'll overwrite the Data object with one that contains only a subset of spectral orders. The following commands could (and should) be used on the entire object containing all orders, but that can take a long time (up to an hour) so for the sake of the tutorial we'll use a smaller subsample. End of explanation """ results = wobble.Results(data=data) for r in range(len(data.orders)): print('starting order {0} of {1}'.format(r+1, len(data.orders))) model = wobble.Model(data, results, r) model.add_star('star') model.add_telluric('tellurics', variable_bases=2) wobble.optimize_order(model) """ Explanation: In the following loop, we'll continually be overwriting the "model" variable. That's ok! All optimized results will be copied over to the "results" object automatically, and as long as the star component is given the same name in the model for every order, they'll be associated in the results object as we'd expect. End of explanation """ results.combine_orders('star') results.apply_drifts('star') # instrumental drift corrections results.apply_bervs('star') # barycentric corrections """ Explanation: Now that we have RVs, let's do some post-processing on them: End of explanation """ plt.errorbar(data.dates, results.star_time_rvs - np.mean(results.star_time_rvs), results.star_time_sigmas, fmt='o', ms=5, elinewidth=1) plt.xlabel('JD') plt.ylabel(r'RV (m s$^{-1}$)'); results.write_rvs('star', 'demo_rvs.txt') """ Explanation: Finally, we can look at the resulting RVs and save them to a text file: End of explanation """ results.write('demo_results.hdf5') """ Explanation: The above command saved the RVs; we probably also want to save the spectral fits and other diagnostic information for future reference. We can do that with the following command, which preserves the entire Results object (including RVs and spectra): End of explanation """
palindromed/data-science
problem_set2/problem_set2.ipynb
mit
import numpy as np import pandas as pd import matplotlib.pyplot as plt titanic_data = pd.read_csv('../knn/train.csv', header=0) titanic_data.info() titanic_data.Survived.mean() """ Explanation: PROBLEM SET 2 Find the Probability that a passenger survived. End of explanation """ fem_sibsp = titanic_data[(titanic_data.Sex == 'female') & (titanic_data.SibSp > 0)] ans = len(fem_sibsp)/len(titanic_data.PassengerId) print(ans) """ Explanation: 38% of Surviving the Titanic. Probability of female passenger with at least one sibling or spouse on board End of explanation """ from_cherb = titanic_data[(titanic_data.Embarked == 'C') & (titanic_data.Survived == 1)] print(len(from_cherb)) print(len(from_cherb)/len(titanic_data.PassengerId)) """ Explanation: There is a 15% Chance of being female with a sibling or spouse on board. What is the probability of being a survivor from Cherbourg End of explanation """ titanic_data_no_ages = titanic_data.dropna(subset=['Age']) %matplotlib inline h, edges = np.histogram(titanic_data_no_ages.Age.values, bins=20) plt.figure(figsize=(10, 4)) ax = plt.subplot(111) ax.bar(edges[:-1], h, width=edges[1] - edges[0]) ax.text(0.9,0.9, '*Known Ages', horizontalalignment='right', transform=ax.transAxes) ax.set_xlabel('Age Range') ax.set_ylabel('Number of People') ax.minorticks_on() plt.show() print(len(titanic_data_no_ages)) """ Explanation: 10% chance of a passenger surviving from Cherbourg Plot the distribution of passenger ages. End of explanation """ print(len(titanic_data[titanic_data.Age < 10])/len(titanic_data.PassengerId)) """ Explanation: Probability that a passenger was less than 10 years old End of explanation """ from scipy.stats import binom binom.pmf(42, 100, 0.38) """ Explanation: 7% probability that a passenger was under 10 years old What is the probability of exactly 42 passengers surviving if 100 passengers are chosen at random? End of explanation """ prob_42 = binom.cdf(42, 100, 0.38) print(1 - prob_42) """ Explanation: Roughly 6% What's the probability that at least 42 of those 100 passengers survive? End of explanation """ from scipy.stats import ttest_ind fem_surv_avg_age = titanic_data[(titanic_data.Survived == 1) & (titanic_data.Sex =='female') & (titanic_data.Age > 0)].Age male_surv_avg_age = titanic_data[(titanic_data.Survived == 1) & (titanic_data.Sex =='male') & (titanic_data.Age > 0)].Age t_stat, p_value = ttest_ind(male_surv_avg_age, fem_surv_avg_age) print("Results: %.5f"% p_value) """ Explanation: Roughly 18% chance that at least 42 survive Is there a statistically significant difference between the ages of male and female survivors? End of explanation """ queen_fare = titanic_data[(titanic_data['Embarked'] == 'Q')].Fare cherb_fare = titanic_data[(titanic_data['Embarked'] == 'C')].Fare t_stat, p_value = ttest_ind(cherb_fare, queen_fare) print("Results: %.5f"% p_value) """ Explanation: The age difference between the male and female survivors is statistically significant because the p-value is over .05. Is there a statistically significant difference between fares paid by the passengers from Queenstown and the ones from Cherbourg? End of explanation """ plt.figure(figsize=(10, 4)) opacity = 0.5 plt.hist(fem_surv_avg_age, bins=np.arange(0, 80, 4), alpha=opacity, label='Female') plt.hist(male_surv_avg_age, bins=np.arange(0, 80, 4), alpha=opacity, label='Male') plt.legend() plt.xlabel('Age') plt.ylabel('Number of Survivors') plt.show() plt.figure(figsize=(10, 4)) opacity = 0.5 plt.hist(cherb_fare, bins=np.arange(0, 150, 4), alpha=opacity, label='Cherbourg') plt.hist(queen_fare, bins=np.arange(0, 150, 4), alpha=opacity, label='Queenstown') plt.legend() plt.xlabel('Fare') plt.ylabel('Number of people paying') plt.show() """ Explanation: There is not a statistically significant difference between the fares paid at Queenstown and Cherbourg ports. Graph difference of ages between male and female survivors End of explanation """
florent-leclercq/borg_sdss_data_release
borg_sdss_tweb/borg_sdss_tweb.ipynb
gpl-3.0
import numpy as np tweb = np.load('borg_sdss_tweb.npz') """ Explanation: BORG SDSS data products borg_sdss_tweb package Authors: Florent Leclercq, Jens Jasche, Benjamin Wandelt Last update: 09/10/2018 This package contains the maps obtained by Leclercq et al. (2015b), who performed a Bayesian analysis of the cosmic web in the SDSS volume. These maps can be used as inputs to the decision-theoretic framework introduced by Leclercq et al. (2015c). The results are four probabilistic maps of the voids, sheets, filaments, and clusters. Structures are defined using the T-web algorithm (Hahn et al. 2007). Data are provided in terms of a standard 3D numpy array and can easily be accessed and processed suign python. For further details on the data and employed methods please consult Leclercq et al. (2015b) and Leclercq et al. (2015c) (references below). File content This package consists of two files: * borg_sdss_tweb.ipynb: The file you are currently reading. * borg_sdss_tweb.tar.gz: Archive available on GitHub LFS and on the author's website. The archive borg_sdss_tweb.tar.gz can be extracted using bash tar -xzf borg_sdss_tweb.tar.gz It contains the file borg_sdss_tweb.npz. Usage Loading and accessing the data The file borg_sdss_tweb.npz contains the probabilistic structure types maps in a standard uncompressed .npz format. To load and process the data execute the following commands: End of explanation """ #3D probabilistic maps for T-web structures V=tweb['voids'] S=tweb['sheets'] F=tweb['filaments'] C=tweb['clusters'] """ Explanation: To access the 3D structure maps use: End of explanation """ k=10;j=127;i=243 V_ijk=V[k,j,i] """ Explanation: Individual voxels in this 3D volumetric data cube can be accessed as follows: End of explanation """ #Minimum and maximum position along the x-axis in Mpc/h xmin=tweb['ranges'][0] xmax=tweb['ranges'][1] #Minimum and maximum position along the y-axis in Mpc/h ymin=tweb['ranges'][2] ymax=tweb['ranges'][3] #Minimum and maximum position along the z-axis in Mpc/h zmin=tweb['ranges'][4] zmax=tweb['ranges'][5] """ Explanation: where i,j and k index voxel positions along the x,y and z axes respectively. All indices run from 0 to 255. The ranges describing the extent of the cubic cartesian volume along the x,y and z axes can be accessed as follows: End of explanation """ from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.patches as mpatches from matplotlib.colors import ListedColormap %matplotlib inline """ Explanation: Units are Mpc/h. (Note that all the maps that are part of the BORG SDSS data products have consistent coordinate systems. The coordinate transform to change from Cartesian to spherical coordinates and vice versa is given in appendix B of Jasche et al. 2015). Example plot: Structure types map Some useful definitions for the following plots: End of explanation """ f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='row', sharey='col', figsize=(12,12)) ax1.imshow(V[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], vmin=0., vmax=1., cmap="viridis") ax1.set_title("voids") ax2.imshow(S[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], vmin=0., vmax=1., cmap="viridis") ax2.set_title("sheets") ax3.imshow(F[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], vmin=0., vmax=1., cmap="viridis") ax3.set_title("filaments") ax4.imshow(C[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], vmin=0., vmax=1., cmap="viridis") ax4.set_title("clusters") plt.show() """ Explanation: The following code can be used to to reproduce figure 3 in Leclercq et al. (2015b). End of explanation """ import warnings warnings.filterwarnings("ignore") VlogV = V*np.log2(V) SlogS = S*np.log2(S) FlogF = F*np.log2(F) ClogC = C*np.log2(C) VlogV[np.isnan(VlogV)]=0. SlogS[np.isnan(SlogS)]=0. FlogF[np.isnan(FlogF)]=0. ClogC[np.isnan(ClogC)]=0. H = - VlogV - SlogS - FlogF - ClogC """ Explanation: Example plot: Entropy The entropy is computed as follows: End of explanation """ fig, ax = plt.subplots(figsize=(6,6)) im = ax.imshow(H[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], vmin=0., vmax=2., cmap="viridis") ax.set_title("Entropy") divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = fig.colorbar(im, cax=cax) plt.show() """ Explanation: We can now plot a slice, reproducing figure 4 (left) in Leclercq et al. (2015b): End of explanation """ Prior_V = 0.14261 Prior_S = 0.59561 Prior_F = 0.24980 Prior_C = 0.01198 """ Explanation: Example plot: Information gain (Kullback-Leibler divergence) We first define th prior probabilities (numbers are given in table II in Leclercq et al. 2015b): End of explanation """ VlogV = V*np.log2(V) SlogS = S*np.log2(S) FlogF = F*np.log2(F) ClogC = C*np.log2(C) VlogV[np.isnan(VlogV)]=0. SlogS[np.isnan(SlogS)]=0. FlogF[np.isnan(FlogF)]=0. ClogC[np.isnan(ClogC)]=0. VlogPrior_V = V*np.log2(Prior_V) SlogPrior_S = S*np.log2(Prior_S) FlogPrior_F = F*np.log2(Prior_F) ClogPrior_C = C*np.log2(Prior_C) DKL = VlogV + SlogS + FlogF + ClogC - VlogPrior_V - SlogPrior_S - FlogPrior_F - ClogPrior_C """ Explanation: The information gain (Kullback-Leibler divergence) is computed as follows: End of explanation """ fig, ax = plt.subplots(figsize=(6,6)) im = ax.imshow(DKL[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], cmap="gist_earth_r") ax.set_title("Kullback-Leibler divergence") divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = fig.colorbar(im, cax=cax) plt.show() """ Explanation: We can now plot a slice, reproducing figure 4 (right) in Leclercq et al. (2015b): End of explanation """ Posterior_l0=tweb['voids'] Posterior_l1=tweb['sheets'] Posterior_l2=tweb['filaments'] Posterior_l3=tweb['clusters'] """ Explanation: Example plot: Decision theory (Leclercq et al. 2015c) We first define the posteriors, i.e. the 3D probabilistic maps for T-web structures: End of explanation """ Prior_l0 = 0.14261 Prior_l1 = 0.59561 Prior_l2 = 0.24980 Prior_l3 = 0.01198 """ Explanation: and the prior probabilities (numbers are given in table II in Leclercq et al. 2015b): End of explanation """ alpha = 1.5 # The free parameter here corresponding to the "cost of the game" G_a0l0 = 1./Prior_l0-alpha G_awl0 = -alpha G_a4l0 = 0. G_a1l1 = 1./Prior_l1-alpha G_awl1 = -alpha G_a4l1 = 0. G_a2l2 = 1./Prior_l2-alpha G_awl2 = -alpha G_a4l2 = 0. G_a3l3 = 1./Prior_l3-alpha G_awl3 = -alpha G_a4l3 = 0. # define the utility functions U_a0 = G_a0l0*Posterior_l0 + G_awl1*Posterior_l1 + G_awl2*Posterior_l2 + G_awl3*Posterior_l3 U_a1 = G_awl0*Posterior_l0 + G_a1l1*Posterior_l1 + G_awl2*Posterior_l2 + G_awl3*Posterior_l3 U_a2 = G_awl0*Posterior_l0 + G_awl1*Posterior_l1 + G_a2l2*Posterior_l2 + G_awl3*Posterior_l3 U_a3 = G_awl0*Posterior_l0 + G_awl1*Posterior_l1 + G_awl3*Posterior_l2 + G_a3l3*Posterior_l3 U_a4 = G_a4l0*Posterior_l0 + G_a4l1*Posterior_l1 + G_a4l2*Posterior_l2 + G_a4l3*Posterior_l3 # make the decision maximizing the utility function MAP = np.copy(U_a4) MAP[np.where((U_a0>U_a1) * (U_a0>U_a2) * (U_a0>U_a3) * (U_a0>U_a4))] = 0.; #voids MAP[np.where((U_a1>U_a0) * (U_a1>U_a2) * (U_a1>U_a3) * (U_a1>U_a4))] = 1.; #sheets MAP[np.where((U_a2>U_a0) * (U_a2>U_a1) * (U_a2>U_a3) * (U_a2>U_a4))] = 2.; #filaments MAP[np.where((U_a3>U_a0) * (U_a3>U_a1) * (U_a3>U_a2) * (U_a3>U_a4))] = 3.; #clusters MAP[np.where((U_a4>=U_a0) * (U_a4>=U_a1) * (U_a4>=U_a2) * (U_a4>=U_a3))] = -1.; #undecided """ Explanation: The following code implements the decision theory framework introduced in Leclercq et al. (2015c). End of explanation """ void_blue = (128./256,128./256,255./256,1.) sheet_green = (95./256,190./256,95./256,1.) filament_yellow = (255./256,210./256,126./256,1.) cluster_red = (255./256,128./256,128./256,1.) StructuresMap=ListedColormap(['black',void_blue,sheet_green,filament_yellow,cluster_red]) plt.figure(figsize=(6,6)) plt.imshow(MAP[:,:,128], origin='lower', extent=[ymin,ymax,zmin,zmax], cmap=StructuresMap) u_patch = mpatches.Patch(color='black', label='undecided') v_patch = mpatches.Patch(color=void_blue, label='voids') s_patch = mpatches.Patch(color=sheet_green, label='sheets') f_patch = mpatches.Patch(color=filament_yellow, label='filaments') c_patch = mpatches.Patch(color=cluster_red, label='clusters') handles = [v_patch,s_patch,f_patch,c_patch,u_patch] plt.legend(handles=handles,frameon=False,loc='center left',bbox_to_anchor=(1, 0.5)) plt.show() """ Explanation: We can now plot a slice, reproducing figure 1 in Leclercq et al. (2015c): End of explanation """
isendel/machine-learning
ml-regression/week 6/K-NN.ipynb
apache-2.0
print(features_test[0]) print(features_train[9]) import math def get_distance(vec1, vec2): return math.sqrt(np.sum((vec1 - vec2)**2)) get_distance(features_test[0], features_train[9]) """ Explanation: Quiz Question: What is the Euclidean distance between the query house and the 10th house of the training set? End of explanation """ min_distance = None closest_house = None for i, train_house in enumerate(features_train[0:10]): dist = get_distance(features_test[0], train_house) if i == 0 or dist < min_distance: min_distance = dist closest_house = i print(min_distance) print(closest_house) diff = features_train - features_test[0] np.sum(diff[-1], axis=0) dist = np.sqrt(np.sum(diff**2, axis=1)) dist[100] def compute_distances(features_instances, features_query): diff = features_instances - features_query distances = np.sqrt(np.sum(diff**2, axis=1)) return distances """ Explanation: Quiz Question: Among the first 10 training houses, which house is the closest to the query house? End of explanation """ distances = compute_distances(features_train, features_test[2]) print(distances) print(np.argmin(distances)) np.where(distances == min(distances)) distances[1149] def k_nearest_neighbors(k, feature_train, features_query): distances = compute_distances(features_train, features_query) return distances, np.argsort(distances)[:k] distances, neighbours = k_nearest_neighbors(4, features_train, features_test[2]) for n in neighbours: print(distances[n]) print(neighbours) print(neighbours) def predict_output_of_query(k, features_train, output_train, features_query): distances, neighbours = k_nearest_neighbors(k, features_train, features_query) prediction = output_train[neighbours].mean() return prediction predict_output_of_query(1, features_train, output_train, features_test[2]) predict_output_of_query(4, features_train, output_train, features_test[2]) print(output_test[2]) def predict_output(k, features_train, output_train, features_query): #distances, neighbours = k_nearest_neighbors(k, features_train, features_query) predictions = np.zeros((features_query.shape[0], 1)) for i in range(features_query.shape[0]): predictions[i,0] = predict_output_of_query(k,features_train, output_train, features_query[i]) return predictions predictions = predict_output(10, features_train, output_train, features_test[:10]) print(predictions) print(np.argmin(predictions)) print(output_test[:10]) rsss = [] for k in range(1,16): predictions = predict_output(k, features_train, output_train, features_valid) error = predictions - output_valid rss = error.T.dot(error) print('RSS for k=%s: %s' % (k, rss)) rsss.append(rss) predictions = predict_output(3, features_train, output_train, features_test) error = predictions - output_test rss = error.T.dot(error) print(rss) """ Explanation: 17. Quiz Question: What is the predicted value of the query house based on 1-nearest neighbor regression? End of explanation """
mne-tools/mne-tools.github.io
0.19/_downloads/d9e2f27df3a137317d331d3be6f3814d/plot_dics_source_power.ipynb
bsd-3-clause
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # Roman Goj <roman.goj@gmail.com> # Denis Engemann <denis.engemann@gmail.com> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne.datasets import somato from mne.time_frequency import csd_morlet from mne.beamformer import make_dics, apply_dics_csd print(__doc__) """ Explanation: Compute source power using DICS beamfomer Compute a Dynamic Imaging of Coherent Sources (DICS) [1]_ filter from single-trial activity to estimate source power across a frequency band. This example demonstrates how to source localize the event-related synchronization (ERS) of beta band activity in this dataset: somato-dataset References .. [1] Gross et al. Dynamic imaging of coherent sources: Studying neural interactions in the human brain. PNAS (2001) vol. 98 (2) pp. 694-699 End of explanation """ data_path = somato.data_path() subject = '01' task = 'somato' raw_fname = op.join(data_path, 'sub-{}'.format(subject), 'meg', 'sub-{}_task-{}_meg.fif'.format(subject, task)) raw = mne.io.read_raw_fif(raw_fname) # Set picks, use a single sensor type picks = mne.pick_types(raw.info, meg='grad', exclude='bads') # Read epochs events = mne.find_events(raw) epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, picks=picks, preload=True) # Read forward operator and point to freesurfer subject directory fname_fwd = op.join(data_path, 'derivatives', 'sub-{}'.format(subject), 'sub-{}_task-{}-fwd.fif'.format(subject, task)) subjects_dir = op.join(data_path, 'derivatives', 'freesurfer', 'subjects') fwd = mne.read_forward_solution(fname_fwd) """ Explanation: Reading the raw data and creating epochs: End of explanation """ freqs = np.logspace(np.log10(12), np.log10(30), 9) """ Explanation: We are interested in the beta band. Define a range of frequencies, using a log scale, from 12 to 30 Hz. End of explanation """ csd = csd_morlet(epochs, freqs, tmin=-1, tmax=1.5, decim=20) csd_baseline = csd_morlet(epochs, freqs, tmin=-1, tmax=0, decim=20) # ERS activity starts at 0.5 seconds after stimulus onset csd_ers = csd_morlet(epochs, freqs, tmin=0.5, tmax=1.5, decim=20) """ Explanation: Computing the cross-spectral density matrix for the beta frequency band, for different time intervals. We use a decim value of 20 to speed up the computation in this example at the loss of accuracy. End of explanation """ filters = make_dics(epochs.info, fwd, csd.mean(), pick_ori='max-power') """ Explanation: Computing DICS spatial filters using the CSD that was computed on the entire timecourse. End of explanation """ baseline_source_power, freqs = apply_dics_csd(csd_baseline.mean(), filters) beta_source_power, freqs = apply_dics_csd(csd_ers.mean(), filters) """ Explanation: Applying DICS spatial filters separately to the CSD computed using the baseline and the CSD computed during the ERS activity. End of explanation """ stc = beta_source_power / baseline_source_power stc.subject = '01' # it's mis-coded in fwd['src'] message = 'DICS source power in the 12-30 Hz frequency band' brain = stc.plot(hemi='both', views='par', subjects_dir=subjects_dir, subject=subject, time_label=message) """ Explanation: Visualizing source power during ERS activity relative to the baseline power. End of explanation """
UWSEDS/LectureNotes
Spring2018/MNIST_classification.ipynb
bsd-2-clause
import numpy as np; import matplotlib import matplotlib.pyplot as plt mnist = np.load('mnist_data.npz') X_train = mnist['X_train'] X_test = mnist['X_test'] y_train = mnist['y_train'] y_test = mnist['y_test'] """ Explanation: MNIST classification This lecture demonstrates an example of a classification instance using Tensorflow. MNIST data ​ MNIST is a collection of images of handwritten numerical digits. Each image is 28x28 pixels and each has a grayscale value from 0-255. End of explanation """ print(X_train.shape) print(X_test.shape) """ Explanation: We have 60000 28x28 images in our training set and 10000 in the test set. End of explanation """ print(X_train[0]) plt.imshow(X_train[0],cmap='gray') plt.axis('off') plt.show() """ Explanation: The pixel value range is 0-255 End of explanation """ sz = 5; for i in range(sz*sz): plt.subplot(sz, sz, i+1) plt.imshow(X_train[i],cmap='gray') plt.axis('off') plt.show() """ Explanation: Let's see what they look like: End of explanation """ print(y_train[:sz*sz].reshape([sz,sz])) """ Explanation: The dataset also includes a label for each digit: End of explanation """ train_data = X_train.reshape([-1,28*28]) test_data = X_test.reshape([-1,28*28]) print(train_data.shape) print(test_data.shape) """ Explanation: Pre-processing We will flatten each digit into a 784-dimensional vector. End of explanation """ def normalize_data(x): flat_x = np.reshape(x,[-1]); L = np.min(x); H = np.max(x); return (x.astype(np.float32)-L)/(H-L); train_data = normalize_data(train_data) test_data = normalize_data(test_data) print(train_data[0]) """ Explanation: We will normalize the data to the [0,1] range: End of explanation """ def to_one_hot(labels,num): one_hot_labels = np.zeros((labels.shape[0],num)) one_hot_labels[np.arange(labels.shape[0]),labels] = 1.0 return one_hot_labels; train_labels = to_one_hot(y_train,10) test_labels = to_one_hot(y_test,10) print('Initial labels:') print(y_train[:5]) print('1-hot representation:') print(train_labels[:5]) """ Explanation: We also need to convert the labels into a 1-hot representation: End of explanation """ import tensorflow as tf """ Explanation: Building a model First let's import tensorflow: End of explanation """ x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) """ Explanation: The model will take the flattened digit as input. An input is declared as a "placeholder" variable meaning that the value of this tensor will be provided at run-time. For the computation of the loss function the class labels are also considered inputs to the model: End of explanation """ h1_sz = 64; W1 = tf.get_variable("W1", [784,h1_sz]) b1 = tf.Variable(tf.zeros([h1_sz])) h1 = tf.matmul(x,W1) + b1 h1 = tf.tanh(h1) W2 = tf.get_variable("W2", [h1_sz,10]) b2 = tf.Variable(tf.zeros([10])) h2 = tf.matmul(h1,W2) + b2 """ Explanation: We will feed the input into a two dense layers with a tanh() non-linearity. Each layer consists of the weight matrix W and the bias vector b. These have to be declared as variables: End of explanation """ class_probs = tf.nn.softmax(h2) """ Explanation: The activations of the layer are fed into a soft-max layer that outputs class probabilities: End of explanation """ cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(tf.nn.softmax(class_probs)),axis=[1])) """ Explanation: We will use the cross-entropy between the predicted and the actual labels as our loss function: End of explanation """ train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy_loss) """ Explanation: We also need to define what a training step looks like. The command below tells tensorflow to optimize the loss function using a Stochastic Gradient Descent (SGD) step with a learning rate of 0.5: End of explanation """ sess = tf.InteractiveSession() """ Explanation: We need to create a session that will run on the computational graph: End of explanation """ tf.global_variables_initializer().run() """ Explanation: We also need to initialize the variables of the model: End of explanation """ batch_x = train_data[:5] batch_y = train_labels[:5] vis_probs = sess.run([class_probs], feed_dict={x:batch_x}) print(vis_probs) """ Explanation: We can use the session to feed the input to the model and get the value of a specific node: End of explanation """ for j in range(200): [a,vis_probs] = sess.run([train_step,class_probs], feed_dict={x:batch_x,y:batch_y}) print(vis_probs) """ Explanation: Notice how we did not provide the labels since these are not part of the slice of the computational graph for the class probabilities. We can also perform an SGD step on this batch by running the session on the training step: End of explanation """ tf.global_variables_initializer().run() """ Explanation: Notice how re-running the command above shifts the output of the model towards the actual labels. Of course this instance of the model will be horribly overfit to these few digits. Let's re-initialize the model: End of explanation """ epochs = 5; batch_size = 32; N = train_data.shape[0]; hist_loss = []; for epoch in range(epochs): print("Epoch:", epoch) for index in range(int(N/(batch_size))): batch_x = train_data[index*batch_size:(index+1)*batch_size]; batch_y = train_labels[index*batch_size:(index+1)*batch_size]; [vis_loss,a] = sess.run([cross_entropy_loss,train_step], feed_dict={x:batch_x,y:batch_y}) hist_loss += [vis_loss] plt.plot(hist_loss) plt.show() """ Explanation: Instead we will cycle over the whole training dataset a few times. We will process the dataset in mini-batches and take an SGD step for each such mini-batch. End of explanation """ for j in range(5): digit = test_data[j].reshape([1,784]); actual_label = test_labels[j]; plt.imshow(digit.reshape([28,28]),cmap='gray') plt.show() print(actual_label) [vis_probs] = sess.run([class_probs], feed_dict={x:digit}) print(vis_probs) input() """ Explanation: Let's see what the model learns: End of explanation """ correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(class_probs, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) train_accuracy = sess.run(accuracy,feed_dict={x:train_data,y:train_labels}) test_accuracy = sess.run(accuracy,feed_dict={x:test_data,y:test_labels}) print("Accuracy on training data:",train_accuracy) print("Accuracy on test data:",test_accuracy) """ Explanation: To test the model more 'formally' we can compute the accuracy on the test dataset: End of explanation """
Boussau/Notebooks
Notebooks/Viromics/analysis_CirSeqAndCloneSamples.ipynb
gpl-2.0
from collections import Counter import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mticker from pylab import rcParams import seaborn as sns from array import array import numpy as np from scipy.stats import ttest_ind from scipy.stats import linregress from scipy.stats import mannwhitneyu import statistics %matplotlib inline """ Explanation: Imports End of explanation """ begins=[] ends=[] names =[] with open ("CommonData/sequence.gb") as f: in_pep = False for l in f: if "mat_peptide" in l: begins.append(int(l.split()[1].split("..")[0])) ends.append(int(l.split()[1].split("..")[1])) in_pep = True elif in_pep : names.append(l.split("=")[1]) in_pep = False print(begins) print(ends) print(names) # Interesting positions positions=[316,1670,1785,2340,5935,7172,8449,9165] def plot_positions(): for x in positions: plt.axvline(x=x, linewidth=1, linestyle=':') def plot_genes(): for i in range(len(begins)): plt.plot([begins[i], begins[i]], [0.99,1.0], linewidth=2, linestyle='-', color="black") if i%2==0: plt.text (begins[i] + ((ends[i] - begins[i])/10), 1.005, (names[i].replace('"', ''))[0:3], size='xx-small') else: plt.text (begins[i] + ((ends[i] - begins[i])/10), 1.015, (names[i].replace('"', ''))[0:3], size='xx-small') plt.plot([ends[-1], ends[-1]], [0.99,1.0], linewidth=2, linestyle='-', color="black") def synonymous (row): if row['null'] or (row['Consensus_aa']==row['Secondbase_aa'] ): return "synonymous" else: return "non-synonymous" def add_columns(table): table['null'] = (table['Secondbase_aa']).isnull() table['is_synonymous'] = table.apply (lambda row: synonymous (row),axis=1) table['1_major_variant_frequency'] = 1.0 - table['Major_variant_frequency_quality_corrected'] def is_increasing(minor_frequencies): #print(minor_frequencies) tolerance = 0.01 minimum_increase = 0.1 previous = minor_frequencies[0] if minor_frequencies[-1] - minor_frequencies[0] < minimum_increase: return False for m in range(1,len(minor_frequencies)): if previous < minor_frequencies[m] or previous < minor_frequencies[m] + tolerance: #print(str(previous) + " < " + str(minor_frequencies[m])) previous = minor_frequencies[m] else: return False return True # Strict definition of an increasing position def is_strictly_increasing(minor_frequencies): #print(minor_frequencies) previous = minor_frequencies[0] for m in range(1,len(minor_frequencies)): if previous < minor_frequencies[m]: #print(str(previous) + " < " + str(minor_frequencies[m])) previous = minor_frequencies[m] else: return False return True def get_variant_frequency(variant, table, i): sum_of_bases = table['As_quality_corrected'][i]+table['Cs_quality_corrected'][i]+table['Gs_quality_corrected'][i]+table['Ts_quality_corrected'][i]+table['Ns_quality_corrected'][i] if variant == "A": return table["As_quality_corrected"][i] / sum_of_bases elif variant == "C": return table["Cs_quality_corrected"][i] / sum_of_bases elif variant == "G": return table["Gs_quality_corrected"][i] / sum_of_bases elif variant == "T": return table["Ts_quality_corrected"][i] / sum_of_bases else: return np.nan def get_increasing_variants(tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) minor_frequencies = array('d',[0.0]*num_tables) increasingVariants = dict() for i in first["Position"]: major = first["Major_variant"][i] #print(last['Major_variant_frequency_quality_corrected'][i]) major_frequencies[0] = first['Major_variant_frequency_quality_corrected'][i] if major == last["Major_variant"][i]: minor = last["Second_variant"][i] else: minor = last["Major_variant"][i] minor_frequencies[0] = get_variant_frequency(minor, first, i) for table_id in range(1, num_tables): major_frequencies[table_id] = get_variant_frequency(major, tables[table_id], i) minor_frequencies[table_id] = get_variant_frequency(minor, tables[table_id], i) if is_increasing(minor_frequencies): increasingVariants[i] = [major_frequencies.tolist(), minor_frequencies.tolist()] return increasingVariants def printMajorFrequencyThroughSamples(tables, numPos): major = tables[0]['Major_variant'][numPos] last_major = tables[0]['Major_variant'][numPos] print("Position "+ str(numPos) +", Major variant in first sample: " + major) print("Position "+ str(numPos) +", Frequencies of "+major+" through the samples: ") for i in range(len(tables)): print("\t"+str(get_variant_frequency(major, tables[i], numPos))) print("Position "+ str(numPos) +", Major variant in last sample: " + tables[-1]['Major_variant'][numPos]) def printMajorFrequencyThroughSamples_2340_7172(tables): printMajorFrequencyThroughSamples(tables, 2340) printMajorFrequencyThroughSamples(tables, 7172) # Functions to think in terms of standard deviation of the frequency per site def get_varying_variants(tables): sd_threshold = 0.1 num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) minor_frequencies = array('d',[0.0]*num_tables) varyingVariants = dict() for i in first["Position"]: major = first["Major_variant"][i] #print(last['Major_variant_frequency_quality_corrected'][i]) major_frequencies[0] = first['Major_variant_frequency_quality_corrected'][i] for table_id in range(1, num_tables): major_frequencies[table_id] = get_variant_frequency(major, tables[table_id], i) sd_value = statistics.pstdev(major_frequencies) if sd_value > sd_threshold: varyingVariants[i] = sd_value print("There are "+str(len(varyingVariants))+" positions whose major variant varies a lot in frequency.") print("Those are:") print(varyingVariants.keys()) return varyingVariants """ Explanation: Useful functions End of explanation """ # Cirseq and clones cirseq = pd.read_csv ("PKG-DREUX_HV5GLBCXY/CutAdaptPearViroMapperMapped/HV5GLBCXY_ZIKV_17s006139-1-1_DREUX_lane1CirseqD3_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(cirseq) clone_12 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD12_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_12) clone_15 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD15_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_15) clone_19 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD19_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_19) tables_clone = [cirseq, clone_12, clone_15, clone_19] # All tables all_table_names = ["cirseq", "clone_12", "clone_15", "clone_19"] """ Explanation: Reading the data End of explanation """ def plotCoverage(tables, names): variable = 'Coverage' sample = list() posList = list() variableList = list() for i in range(len(names)): sample = sample + len(tables[i][variable]) * [names[i]] posList.append(tables[i]['Position']) variableList.append(tables[i][variable]) positions = pd.concat(posList) variableValues = pd.concat(variableList) overlay_table_concat = pd.DataFrame ({'Position':positions, variable:variableValues, 'sample':sample}) sns.lmplot( x="Position", y=variable, data=overlay_table_concat, fit_reg=False, hue='sample', legend=False, size=7, aspect=2, lowess=True,scatter_kws={"s": 20}) plt.legend(loc='lower right') plot_positions() plot_genes() plotCoverage(tables_clone, all_table_names) """ Explanation: Analysis of coverage End of explanation """ f, ax = plt.subplots(figsize=(15, 7)) lm=sns.kdeplot(np.log(tables_clone[0]["1_major_variant_frequency"]), label="cirseq") lm.set_ylabel('Density') lm.set_xlabel('Logarithm of the diversity per position') lm=sns.kdeplot(np.log(tables_clone[1]["1_major_variant_frequency"]), label="clone_12") lm=sns.kdeplot(np.log(tables_clone[2]["1_major_variant_frequency"]), label="clone_15") lm=sns.kdeplot(np.log(tables_clone[3]["1_major_variant_frequency"]), label="clone_19") axes = lm.axes axes.set_xlim(-8,-4) axes.set_ylim(0,1.2) """ Explanation: Diversity plot End of explanation """ increasing = get_increasing_variants(tables_clone) print("There are "+str(len(increasing))+" positions that rise in frequency.") print("Those are:") print(increasing.keys()) """ Explanation: Positions that increase in frequency in the different replicates and conditions End of explanation """ def plot_increasing_positions(increasing_pos, last_time_point) : sns.set_palette("hls") sns.set_context("poster") increasing_pos_keys = increasing_pos.keys() Is_increasing = [] for i in last_time_point['Position']: if i in increasing_pos_keys: Is_increasing.append("Increasing") else: Is_increasing.append("Not increasing") to_plot = pd.DataFrame ({'Position':last_time_point['Position'], 'Major_variant_frequency_quality_corrected':last_time_point ['Major_variant_frequency_quality_corrected'],'Is_increasing':Is_increasing, 'is_synonymous':last_time_point ['is_synonymous']}) ax=sns.lmplot( x="Position", y="Major_variant_frequency_quality_corrected", data=to_plot, fit_reg=False, hue='Is_increasing', row='is_synonymous', legend=False, size=7, aspect=2) ax.set(xlabel='Position along the genome', ylabel='Major variant frequency, last time point') plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plot_positions() plot_increasing_positions(increasing, clone_19) """ Explanation: Plotting only positions that consistently rise in frequency End of explanation """ def write_increasing_positions(increasing_pos, tables, exp_names, filename) : increasing_pos_table = pd.DataFrame() for d in tables: increasing_pos_table = pd.concat([increasing_pos_table,d[d['Position'].isin(increasing_pos)]]) num = len(increasing_pos) expnames_iterated = [] for i in exp_names : expnames_iterated.append([i]*num) expnames = [item for sublist in expnames_iterated for item in sublist] print(len(expnames)) increasing_pos_table['expName']=expnames increasing_pos_table.to_csv( filename ) write_increasing_positions(increasing, tables_clone, all_table_names, "increasing_clone.csv") printMajorFrequencyThroughSamples_2340_7172(tables_clone) """ Explanation: Write out the table End of explanation """ varying_clone = get_varying_variants(tables_clone) # Output positions of interest based on this analysis varying_pos = [253, 322, 418, 910, 926, 1043, 1312, 1474, 1903, 2340, 2455, 2783, 2852, 2903, 3565, 3592, 4192, 4201, 4552, 5125, 5155, 5230, 5314, 5675, 6334, 6628, 6670, 6991, 7093, 7228, 7441, 7636, 8093, 8410, 8776, 9025, 9241, 9295, 9556, 9736, 9952] write_increasing_positions(varying_pos, tables_clone, all_table_names, "varying_positions_clone_samples.csv") """ Explanation: Analysis of positions whose frequency varies a lot End of explanation """ def getInterestingVariants (tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) interestingVariants = list() for i in first["Position"]: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) if minor_frequencies[j] > 0.1: counter += 1 if counter >=2: interestingVariants.append(i) return interestingVariants interesting_clone = getInterestingVariants (tables_clone) interesting_clone for_output = [322, 418, 1043, 1312, 1474, 1903, 2340, 2455, 2783, 2852, 2903, 3565, 3592, 4192, 4201, 4552, 5125, 5155, 5230, 5314, 5675, 6334, 6628, 6670, 6991, 7093, 7228, 7441, 7636, 8093, 8410, 8776, 9025, 9241, 9295, 9556, 9736, 9952, 10801, 10802, 10803, 10804, 10805] write_increasing_positions(for_output, tables_clone, all_table_names, "positions_morethan01_clone_samples.csv") """ Explanation: Other selection method We want to select all the positions in which the minor variant reaches >0.1 in at least two time points, in two different replicates or experiments. To do so, we get the variant at time point 0, then we look at the following time points and see if one site has some minor variant >0.1 in 2 time points. We collect all the sites with this characteristic for this experiment. We do this for all experiments, then we take all sites that appear at least twice. End of explanation """ def test_positions (tables, positions): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) for i in positions: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 print(str(i)+" : ") for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) print("\texp "+str(j) +", variant "+minor + " : "+str(minor_frequencies[j])) if minor_frequencies[j] > 0.1: counter += 1 print("Counter of times > 0.1: "+ str(counter)) return def test_positions_1670_2193 (tables): test_positions(tables, [1670,2193]) return def test1670_2193 (tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) for i in [1670,2193]: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 print(str(i)+" : ") for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) print("\texp "+str(j) +", variant "+minor + " : "+str(minor_frequencies[j])) if minor_frequencies[j] > 0.1: counter += 1 print("Counter of times > 0.1: "+ str(counter)) return test_positions_1670_2193 (tables_clone) """ Explanation: Analysis of positions 1670 and 2193 End of explanation """ #positions=[316, 1785, 2340, 5662, 5935, 8449, 10006 ] positions = [1670, 1785, 2193, 2340, 5662, 7172, 10006] test_positions (tables_clone, positions) write_increasing_positions(positions, tables_clone, all_table_names, "positions_7_interesting_clone_samples.csv") """ Explanation: Focus on the 7 mutations that have been declared of interest End of explanation """
ijstokes/bokeh-blaze-tutorial
1.1 Charts - Timeseries.ipynb
mit
import pandas as pd from bokeh.charts import TimeSeries, output_notebook, show output_notebook() # Get data be = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv', parse_dates=[0]) be.head() be.datetime[:10] # Process data be.datetime = pd.to_datetime(be.datetime) be = be[['anomaly','datetime']] # Output option output_notebook() # Create timeseries chart t = TimeSeries(be, x='datetime', y='anomaly') # Show chart show(t) """ Explanation: <img src=images/continuum_analytics_b&w.png align="left" width="15%" style="margin-right:15%"> <h1 align='center'>Bokeh Tutorial</h1> 1.1 Charts - Timeseries Exercise: Visualize the evolution of the temperature anomaly monthly average over time with a timeseries chart Data: 'data/Land_Ocean_Monthly_Anomaly_Average.csv' Tips: import pandas as pd pd.read_csv() pd.to_datetime() End of explanation """ # Style your timeseries chart # Show new chart """ Explanation: Exercise: Style your plot Ideas: Add a title Add axis labels Change width and height Deactivate toolbox or customize available tools Change line color Charts arguments can be found: http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html#generic-arguments End of explanation """ # Compute moving average # Create chart with moving average # Show chart with moving average """ Explanation: Exercise: Add the moving annual average to your chart Tips: pd.rolling_mean() End of explanation """
simpeg/simpegmt
notebooks/MT Script-3D_layerTest-working.ipynb
mit
%%time es_px = Ainv*rhs_px es_py = Ainv*rhs_py # Need to sum the ep and es to get the total field. e_x = es_px #+ ep_px e_y = es_py #+ ep_py """ Explanation: We are using splu in scipy package. This is bit slow, but on the cluster you can use mumps, which might a lot faster. We can think about having better iterative solver. End of explanation """ Meinv = M.getEdgeInnerProduct(np.ones_like(sig), invMat=True) j_x = Meinv*Msig*e_x j_y = Meinv*Msig*e_x e_x.shape e_x_CC = M.aveE2CCV*e_x e_y_CC = M.aveE2CCV*e_y j_x_CC = M.aveE2CCV*j_x j_y_CC = M.aveE2CCV*j_y # j_x_CC = Utils.sdiag(np.r_[sig, sig, sig])*e_x_CC """ Explanation: I want to visualize electrical field, which is a vector, so I average them on to cell center. Also I want to see current density ($\vec{j} = \sigma \vec{e}$). End of explanation """ fig, ax = plt.subplots(1,2, figsize = (12, 5)) dat0 = M.plotSlice(abs(e_x_CC), vType='CCv', view='vec', streamOpts={'color': 'k'}, normal='Y', ax = ax[0]) cb0 = plt.colorbar(dat0[0], ax = ax[0]) dat1 = M.plotSlice(abs(j_x_CC), vType='CCv', view='vec', streamOpts={'color': 'k'}, normal='Y', ax = ax[1]) cb1 = plt.colorbar(dat1[0], ax = ax[1]) """ Explanation: Then use "plotSlice" function, to visualize 2D sections End of explanation """ # Calculate the data rx_x, rx_y = np.meshgrid(np.arange(-500,501,50),np.arange(-500,501,50)) rx_loc = np.hstack((simpeg.Utils.mkvc(rx_x,2),simpeg.Utils.mkvc(rx_y,2),elev+np.zeros((np.prod(rx_x.shape),1)))) # Get the projection matrices Qex = M.getInterpolationMat(rx_loc,'Ex') Qey = M.getInterpolationMat(rx_loc,'Ey') Qez = M.getInterpolationMat(rx_loc,'Ez') Qfx = M.getInterpolationMat(rx_loc,'Fx') Qfy = M.getInterpolationMat(rx_loc,'Fy') Qfz = M.getInterpolationMat(rx_loc,'Fz') e_x_loc = np.hstack([simpeg.Utils.mkvc(Qex*e_x,2),simpeg.Utils.mkvc(Qey*e_x,2),simpeg.Utils.mkvc(Qez*e_x,2)]) e_y_loc = np.hstack([simpeg.Utils.mkvc(Qex*e_y,2),simpeg.Utils.mkvc(Qey*e_y,2),simpeg.Utils.mkvc(Qez*e_y,2)]) Ciw = -C/(1j*omega(freq)*mu_0) h_x_loc = np.hstack([simpeg.Utils.mkvc(Qfx*Ciw*e_x,2),simpeg.Utils.mkvc(Qfy*Ciw*e_x,2),simpeg.Utils.mkvc(Qfz*Ciw*e_x,2)]) h_y_loc = np.hstack([simpeg.Utils.mkvc(Qfx*Ciw*e_y,2),simpeg.Utils.mkvc(Qfy*Ciw*e_y,2),simpeg.Utils.mkvc(Qfz*Ciw*e_y,2)]) # Make a combined matrix dt = np.dtype([('ex1',complex),('ey1',complex),('ez1',complex),('hx1',complex),('hy1',complex),('hz1',complex),('ex2',complex),('ey2',complex),('ez2',complex),('hx2',complex),('hy2',complex),('hz2',complex)]) combMat = np.empty((len(e_x_loc)),dtype=dt) combMat['ex1'] = e_x_loc[:,0] combMat['ey1'] = e_x_loc[:,1] combMat['ez1'] = e_x_loc[:,2] combMat['ex2'] = e_y_loc[:,0] combMat['ey2'] = e_y_loc[:,1] combMat['ez2'] = e_y_loc[:,2] combMat['hx1'] = h_x_loc[:,0] combMat['hy1'] = h_x_loc[:,1] combMat['hz1'] = h_x_loc[:,2] combMat['hx2'] = h_y_loc[:,0] combMat['hy2'] = h_y_loc[:,1] combMat['hz2'] = h_y_loc[:,2] def calculateImpedance(fieldsData): ''' Function that calculates MT impedance data from a rec array with E and H field data from both polarizations ''' zxx = (fieldsData['ex1']*fieldsData['hy2'] - fieldsData['ex2']*fieldsData['hy1'])/(fieldsData['hx1']*fieldsData['hy2'] - fieldsData['hx2']*fieldsData['hy1']) zxy = (-fieldsData['ex1']*fieldsData['hx2'] + fieldsData['ex2']*fieldsData['hx1'])/(fieldsData['hx1']*fieldsData['hy2'] - fieldsData['hx2']*fieldsData['hy1']) zyx = (fieldsData['ey1']*fieldsData['hy2'] - fieldsData['ey2']*fieldsData['hy1'])/(fieldsData['hx1']*fieldsData['hy2'] - fieldsData['hx2']*fieldsData['hy1']) zyy = (-fieldsData['ey1']*fieldsData['hx2'] + fieldsData['ey2']*fieldsData['hx1'])/(fieldsData['hx1']*fieldsData['hy2'] - fieldsData['hx2']*fieldsData['hy1']) return zxx, zxy, zyx, zyy zxx, zxy, zyx, zyy = calculateImpedance(combMat) ind = np.where(np.sum(np.power(rx_loc - np.array([0,0,elev]),2),axis=1)< 5) def appResPhs(freq,z): app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 app_phs = np.arctan2(z.imag,z.real)*(180/np.pi) return app_res, app_phs print appResPhs(freq,zyx[ind]) print appResPhs(freq,zxy[ind]) e0_1d = e0_1d.conj() Qex = mesh1d.getInterpolationMat(np.array([elev]),'Ex') Qfx = mesh1d.getInterpolationMat(np.array([elev]),'Fx') h0_1dC = -(mesh1d.nodalGrad*e0_1d)/(1j*omega(freq)*mu_0) h0_1d = mesh1d.getInterpolationMat(mesh1d.vectorNx,'Ex')*h0_1dC indSur = np.where(mesh1d.vectorNx==elev) print (Qfx*e0_1d),(Qex*h0_1dC)#e0_1d, h0_1d print appResPhs(freq,(Qfx*e0_1d)/(Qex*h0_1dC).conj()) import simpegMT as simpegmt sig1D = M.r(sig,'CC','CC','M')[0,0,:] anaEd, anaEu, anaHd, anaHu = simpegmt.Utils.MT1Danalytic.getEHfields(mesh1d,sig1D,freq,mesh1d.vectorNx) anaEtemp = anaEd+anaEu anaHtemp = anaHd+anaHu # Scale the solution anaE = (anaEtemp/anaEtemp[-1])#.conj() anaH = (anaHtemp/anaEtemp[-1])#.conj() anaZ = anaE/anaH indSur = np.where(mesh1d.vectorNx==elev) print anaZ print appResPhs(freq,anaZ[indSur]) print appResPhs(freq,-anaZ[indSur]) mesh1d.vectorNx """ Explanation: Is it reasonable?: Based on that you put resistive target that makes sense to me; current does not want to flow on resistive target so they just do roundabout:). And see air interface. It is continuous on current but not on electric field, which looks reasonable. End of explanation """
tensorflow/examples
courses/udacity_intro_to_tensorflow_for_deep_learning/l05c01_dogs_vs_cats_without_augmentation.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Authors. End of explanation """ import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator import os import matplotlib.pyplot as plt import numpy as np import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) """ Explanation: Dogs vs Cats Image Classification Without Image Augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c01_dogs_vs_cats_without_augmentation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c01_dogs_vs_cats_without_augmentation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> In this tutorial, we will discuss how to classify images into pictures of cats or pictures of dogs. We'll build an image classifier using tf.keras.Sequential model and load data using tf.keras.preprocessing.image.ImageDataGenerator. Specific concepts that will be covered: In the process, we will build practical experience and develop intuition around the following concepts Building data input pipelines using the tf.keras.preprocessing.image.ImageDataGenerator class — How can we efficiently work with data on disk to interface with our model? Overfitting - what is it, how to identify it? <hr> Before you begin Before running the code in this notebook, reset the runtime by going to Runtime -> Reset all runtimes in the menu above. If you have been working through several notebooks, this will help you avoid reaching Colab's memory limits. Importing packages Let's start by importing required packages: os — to read files and directory structure numpy — for some matrix math outside of TensorFlow matplotlib.pyplot — to plot the graph and display images in our training and validation data End of explanation """ _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' zip_dir = tf.keras.utils.get_file('cats_and_dogs_filterted.zip', origin=_URL, extract=True) """ Explanation: Data Loading To build our image classifier, we begin by downloading the dataset. The dataset we are using is a filtered version of <a href="https://www.kaggle.com/c/dogs-vs-cats/data" target="_blank">Dogs vs. Cats</a> dataset from Kaggle (ultimately, this dataset is provided by Microsoft Research). In previous Colabs, we've used <a href="https://www.tensorflow.org/datasets" target="_blank">TensorFlow Datasets</a>, which is a very easy and convenient way to use datasets. In this Colab however, we will make use of the class tf.keras.preprocessing.image.ImageDataGenerator which will read data from disk. We therefore need to directly download Dogs vs. Cats from a URL and unzip it to the Colab filesystem. End of explanation """ zip_dir_base = os.path.dirname(zip_dir) !find $zip_dir_base -type d -print """ Explanation: The dataset we have downloaded has the following directory structure. <pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" > <b>cats_and_dogs_filtered</b> |__ <b>train</b> |______ <b>cats</b>: [cat.0.jpg, cat.1.jpg, cat.2.jpg ...] |______ <b>dogs</b>: [dog.0.jpg, dog.1.jpg, dog.2.jpg ...] |__ <b>validation</b> |______ <b>cats</b>: [cat.2000.jpg, cat.2001.jpg, cat.2002.jpg ...] |______ <b>dogs</b>: [dog.2000.jpg, dog.2001.jpg, dog.2002.jpg ...] </pre> We can list the directories with the following terminal command: End of explanation """ base_dir = os.path.join(os.path.dirname(zip_dir), 'cats_and_dogs_filtered') train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') train_cats_dir = os.path.join(train_dir, 'cats') # directory with our training cat pictures train_dogs_dir = os.path.join(train_dir, 'dogs') # directory with our training dog pictures validation_cats_dir = os.path.join(validation_dir, 'cats') # directory with our validation cat pictures validation_dogs_dir = os.path.join(validation_dir, 'dogs') # directory with our validation dog pictures """ Explanation: We'll now assign variables with the proper file path for the training and validation sets. End of explanation """ num_cats_tr = len(os.listdir(train_cats_dir)) num_dogs_tr = len(os.listdir(train_dogs_dir)) num_cats_val = len(os.listdir(validation_cats_dir)) num_dogs_val = len(os.listdir(validation_dogs_dir)) total_train = num_cats_tr + num_dogs_tr total_val = num_cats_val + num_dogs_val print('total training cat images:', num_cats_tr) print('total training dog images:', num_dogs_tr) print('total validation cat images:', num_cats_val) print('total validation dog images:', num_dogs_val) print("--") print("Total training images:", total_train) print("Total validation images:", total_val) """ Explanation: Understanding our data Let's look at how many cats and dogs images we have in our training and validation directory End of explanation """ BATCH_SIZE = 100 # Number of training examples to process before updating our models variables IMG_SHAPE = 150 # Our training data consists of images with width of 150 pixels and height of 150 pixels """ Explanation: Setting Model Parameters For convenience, we'll set up variables that will be used later while pre-processing our dataset and training our network. End of explanation """ train_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our training data validation_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our validation data """ Explanation: Data Preparation Images must be formatted into appropriately pre-processed floating point tensors before being fed into the network. The steps involved in preparing these images are: Read images from the disk Decode contents of these images and convert it into proper grid format as per their RGB content Convert them into floating point tensors Rescale the tensors from values between 0 and 255 to values between 0 and 1, as neural networks prefer to deal with small input values. Fortunately, all these tasks can be done using the class tf.keras.preprocessing.image.ImageDataGenerator. We can set this up in a couple of lines of code. End of explanation """ train_data_gen = train_image_generator.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE), #(150,150) class_mode='binary') val_data_gen = validation_image_generator.flow_from_directory(batch_size=BATCH_SIZE, directory=validation_dir, shuffle=False, target_size=(IMG_SHAPE,IMG_SHAPE), #(150,150) class_mode='binary') """ Explanation: After defining our generators for training and validation images, flow_from_directory method will load images from the disk, apply rescaling, and resize them using single line of code. End of explanation """ sample_training_images, _ = next(train_data_gen) """ Explanation: Visualizing Training images We can visualize our training images by getting a batch of images from the training generator, and then plotting a few of them using matplotlib. End of explanation """ # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column. def plotImages(images_arr): fig, axes = plt.subplots(1, 5, figsize=(20,20)) axes = axes.flatten() for img, ax in zip(images_arr, axes): ax.imshow(img) plt.tight_layout() plt.show() plotImages(sample_training_images[:5]) # Plot images 0-4 """ Explanation: The next function returns a batch from the dataset. One batch is a tuple of (many images, many labels). For right now, we're discarding the labels because we just want to look at the images. End of explanation """ model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(2) ]) """ Explanation: Model Creation Define the model The model consists of four convolution blocks with a max pool layer in each of them. Then we have a fully connected layer with 512 units, with a relu activation function. The model will output class probabilities for two classes — dogs and cats — using softmax. End of explanation """ model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) """ Explanation: Compile the model As usual, we will use the adam optimizer. Since we output a softmax categorization, we'll use sparse_categorical_crossentropy as the loss function. We would also like to look at training and validation accuracy on each epoch as we train our network, so we are passing in the metrics argument. End of explanation """ model.summary() """ Explanation: Model Summary Let's look at all the layers of our network using summary method. End of explanation """ EPOCHS = 100 history = model.fit_generator( train_data_gen, steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))), epochs=EPOCHS, validation_data=val_data_gen, validation_steps=int(np.ceil(total_val / float(BATCH_SIZE))) ) """ Explanation: Train the model It's time we train our network. Since our batches are coming from a generator (ImageDataGenerator), we'll use fit_generator instead of fit. End of explanation """ acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(EPOCHS) plt.figure(figsize=(8, 8)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.savefig('./foo.png') plt.show() """ Explanation: Visualizing results of the training We'll now visualize the results we get after training our network. End of explanation """
SlipknotTN/udacity-deeplearning-nanodegree
image-classification-project/dlnd_image_classification.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile('cifar-10-python.tar.gz'): with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar: urlretrieve( 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', 'cifar-10-python.tar.gz', pbar.hook) if not isdir(cifar10_dataset_folder_path): with tarfile.open('cifar-10-python.tar.gz') as tar: tar.extractall() tar.close() tests.test_folder_path(cifar10_dataset_folder_path) """ Explanation: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images. Get the Data Run the following cell to download the CIFAR-10 dataset for python. End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) """ Explanation: Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog * horse * ship * truck Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch. Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions. End of explanation """ def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ # TODO: Implement Function return (x - np.min(x)) / (np.max(x) - np.min(x)) * (1 - 0) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_normalize(normalize) """ Explanation: Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. End of explanation """ from sklearn import preprocessing def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ # TODO: Implement Function lb = preprocessing.LabelBinarizer() lb.fit(range(0,9+1)) return lb.transform(x) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_one_hot_encode(one_hot_encode) """ Explanation: One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function. Hint: Look into LabelBinarizer in the preprocessing module of sklearn. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode) """ Explanation: Randomize Data As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save it Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb')) """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return tf.placeholder(tf.float32, shape=(None, *image_shape), name = "x") def neural_net_label_input(n_classes): """ Return a Tensor for a batch of label input : n_classes: Number of classes : return: Tensor for label input. """ # TODO: Implement Function return tf.placeholder(tf.int32, shape=(None, n_classes), name = "y") def neural_net_keep_prob_input(): """ Return a Tensor for keep probability : return: Tensor for keep probability. """ # TODO: Implement Function return tf.placeholder(tf.float32, name = "keep_prob") """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tf.reset_default_graph() tests.test_nn_image_inputs(neural_net_image_input) tests.test_nn_label_inputs(neural_net_label_input) tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input) """ Explanation: Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project. Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup. However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d. Let's begin! Input The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions * Implement neural_net_image_input * Return a TF Placeholder * Set the shape using image_shape with batch size set to None. * Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_label_input * Return a TF Placeholder * Set the shape using n_classes with batch size set to None. * Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_keep_prob_input * Return a TF Placeholder for dropout keep probability. * Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder. These names will be used at the end of the project to load your saved model. Note: None for shapes in TensorFlow allow for a dynamic size. End of explanation """ def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # TODO: Implement Function input_channels = x_tensor.shape[-1] conv_weights = tf.Variable(tf.truncated_normal(shape=(*conv_ksize, int(input_channels), conv_num_outputs), mean=0.0, stddev=0.01)) conv_stride = [1, *conv_strides, 1] conv_biases = tf.Variable(tf.zeros(conv_num_outputs)) padding = 'SAME' conv_result = tf.add(tf.nn.conv2d(x_tensor, conv_weights, conv_stride, padding), conv_biases) relu_result = tf.nn.relu(conv_result) max_pool_result = tf.nn.max_pool(relu_result, ksize=[1, *pool_ksize, 1], strides=[1,*pool_strides,1], padding=padding) return max_pool_result """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_con_pool(conv2d_maxpool) """ Explanation: Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor using weight and conv_strides. * We recommend you use same padding, but you're welcome to use any padding. * Add bias * Add a nonlinear activation to the convolution. * Apply Max Pooling using pool_ksize and pool_strides. * We recommend you use same padding, but you're welcome to use any padding. Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers. Hint: When unpacking values as an argument in Python, look into the unpacking operator. End of explanation """ def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function # With contrib return tf.contrib.layers.flatten(x_tensor) #With TF # flattened_dim = int(x_tensor.shape[1] * x_tensor.shape[2] * x_tensor.shape[3]) # return tf.reshape(x_tensor,shape=(-1, flattened_dim)) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_flatten(flatten) """ Explanation: Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function # With TF weights = tf.Variable(tf.truncated_normal(shape=(int(x_tensor.shape[1]), num_outputs), mean=0.0, stddev=0.01)) biases = tf.Variable(tf.zeros(num_outputs)) return tf.nn.relu(tf.add(tf.matmul(x_tensor, weights), biases)) # With contrib # return tf.nn.relu(tf.contrib.layers.fully_connected(x_tensor, num_outputs)) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_fully_conn(fully_conn) """ Explanation: Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function # With TF weights = tf.Variable(tf.truncated_normal(shape=(int(x_tensor.shape[1]), num_outputs), mean=0.0, stddev=0.01)) biases = tf.Variable(tf.zeros(num_outputs)) return tf.add(tf.matmul(x_tensor, weights), biases) # With contrib # return tf.contrib.layers.fully_connected(x_tensor, num_outputs) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_output(output) """ Explanation: Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Activation, softmax, or cross entropy should not be applied to this. End of explanation """ def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers # Play around with different number of outputs, kernel size and stride # Function Definition from Above: # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides) result = conv2d_maxpool(x, 32, (5,5), (1,1), (2,2), (2,2)) result = conv2d_maxpool(result, 64, (5,5), (1,1), (2,2), (2,2)) result = tf.nn.dropout(result, keep_prob) # TODO: Apply a Flatten Layer # Function Definition from Above: # flatten(x_tensor) result = flatten(result) # TODO: Apply 1, 2, or 3 Fully Connected Layers # Play around with different number of outputs # Function Definition from Above: # fully_conn(x_tensor, num_outputs) result = fully_conn(result, 128) # result = fully_conn(result, 128) result = tf.nn.dropout(result, keep_prob) # TODO: Apply an Output Layer # Set this to the number of classes # Function Definition from Above: # output(x_tensor, num_outputs) result = output(result, 10) # TODO: return output return result """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ ############################## ## Build the Neural Network ## ############################## # Remove previous weights, bias, inputs, etc.. tf.reset_default_graph() # Inputs x = neural_net_image_input((32, 32, 3)) y = neural_net_label_input(10) keep_prob = neural_net_keep_prob_input() # Model logits = conv_net(x, keep_prob) # Name logits Tensor, so that is can be loaded from disk after training logits = tf.identity(logits, name='logits') # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tests.test_conv_net(conv_net) """ Explanation: Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Fully Connected Layers Apply an Output Layer Return the output Apply TensorFlow's Dropout to one or more layers in the model using keep_prob. End of explanation """ def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data """ # TODO: Implement Function session.run(optimizer, feed_dict={x: feature_batch, y: label_batch, keep_prob: keep_probability}) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_train_nn(train_neural_network) """ Explanation: Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be called for each batch, so tf.global_variables_initializer() has already been called. Note: Nothing needs to be returned. This function is only optimizing the neural network. End of explanation """ def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy: TensorFlow accuracy function """ # TODO: Implement Function print(session.run(cost, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0})) print(session.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob: 1.0})) """ Explanation: Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. End of explanation """ # TODO: Tune Parameters epochs = 30 batch_size = 64 keep_probability = 0.5 """ Explanation: Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the probability of keeping a node using dropout End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) """ Explanation: Train on a Single CIFAR-10 Batch Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) """ Explanation: Fully Train the Model Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_classification' n_samples = 4 top_n_predictions = 3 def test_model(): """ Test the saved model against the test dataset """ test_features, test_labels = pickle.load(open('preprocess_training.p', mode='rb')) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(save_model_path + '.meta') loader.restore(sess, save_model_path) # Get Tensors from loaded model loaded_x = loaded_graph.get_tensor_by_name('x:0') loaded_y = loaded_graph.get_tensor_by_name('y:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_logits = loaded_graph.get_tensor_by_name('logits:0') loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0') # Get accuracy in batches for memory limitations test_batch_acc_total = 0 test_batch_count = 0 for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size): test_batch_acc_total += sess.run( loaded_acc, feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0}) test_batch_count += 1 print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count)) # Print Random Samples random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples))) random_test_predictions = sess.run( tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions), feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0}) helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions) test_model() """ Explanation: Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. End of explanation """
thom056/ada-parliament-ML
02-NLP_Sentiment/01-nlp_Gensim.ipynb
gpl-2.0
import pandas as pd import glob import os import numpy as np from time import time import logging import gensim import bz2 """ Explanation: 01. Topic Modelling using the Gensim Library Usual imports come first. End of explanation """ dataset = [] path = '../datas/treated_data/Transcript/' #path = 'datas/Vote/' allFiles = glob.glob(os.path.join(path, 'FR*.csv')) for file_ in allFiles: data = pd.read_csv(file_) dataset = dataset + list(data[(data['Text'] == data['Text'])]['Text'].values) #dataset = dataset + list(data[(data['BusinessTitle'] == data['BusinessTitle'])]['BusinessTitle'].values+' ') print('Length of the dataset', len(dataset)) #print(dataset[0],'\n',dataset[1]) #data.head() """ Explanation: 1. Load the data from the Transcript files At the moment, we only consider the entries for which the field LanguageOfText is FR, namely the ones in French. We will consider the text in German later on. We show below one example of the text we consider. End of explanation """ def stop_words(): """ Loads and concatenates the stop_words list of both french and german languages (due to the fact that there are some german words in the french transcript and vice-versa) """ #1. Load the custom French stop words dictionary with open ("../datas/stop_dictionaries/French_stop_words_changed.txt", "r") as myfile: stop_words_fr=myfile.read() stop_words_fr = stop_words_fr.split(',') #2. Load the custom German stop words dictionary with open ("../datas/stop_dictionaries/German_stop_words.txt", "r") as myfile: stop_words_de=myfile.read() stop_words_de = stop_words_de.split(', ') return stop_words_de+stop_words_fr stop_words = stop_words() """ Explanation: The length of the transcripts largely vary from an entry to another, but it reflects exactly what is discussed at the federal parliament. Processing them correctly will allow us to grasp the topic which are discussed at the parliament. 2. Format the data in order to use LDA with Gensim First of all, we load the stop_words, a list which refers all the common words for French, and that we must not take into accoung when doing the topic modelling, as they do not convey any useful information. The pipeline we follow is the following : 1. Load the stop_words (using the stop_words package) : We do not load the package as we loaded it once and save the resulting stop words into a .txt file. We do that in order to be able to add some stop words of our own. End of explanation """ import re from collections import defaultdict from nltk.stem.snowball import FrenchStemmer from nltk.stem import WordNetLemmatizer def format_text(dataset, stop_words, stemming = False): """ Here, we remove the common words in our document corpus and tokenize it, before """ # The re.split function takes as first arguments everything we split at. At the moment, this is # ' ' - '\'- '/' - ''' (apostrophe) - '\n' - '(', ')' - ',' - '.' - ':' - ';' -'[' - ']' and - '´' # We also filter the words which are shorter than 3 letters, as they are very unlikely #to provide any information, and finally, we remove the common words. texts = [[word for word in re.split(' |\'|\n|\(|\)|,|;|:|\.|\[|\]|\’|\/', document.lower()) if (len(word) > 4 and (word not in stop_words))] for document in dataset] # Thirdly we remove the words that appear only once in a text if stemming: #Consider the stemmed version FS = FrenchStemmer() frequency = defaultdict(int) for text in texts: for token in text: frequency[FS.stem(token)] += 1 texts = [[FS.stem(token) for token in text if frequency[FS.stem(token)] > 1] for text in texts] else: frequency = defaultdict(int) for text in texts: for token in text: frequency[token] += 1 texts = [[token for token in text if frequency[token] > 1] for text in texts] return texts texts = format_text(dataset,stop_words) """ Explanation: Remove those common words and tokenize our dataset (break it down into words) We count the frequency of the words and remove the ones that appear only once in total. (Implement the Stemming of the data (cf. a French stemming algorithm). (Done with the nltk library) ) -> Not implemented at the moment Remove all the words of length <= 2. N.B. THIS ALGORITHM IS VERY SLOW !!!! End of explanation """ dictionary = gensim.corpora.Dictionary(texts) # Converts a collection of words to its bag of word representation (list of word_id, word_frequency 2-tuples$) corpus = [dictionary.doc2bow(text) for text in texts] if not os.path.exists("../datas/lda"): os.makedirs("../datas/lda") dictionary.save('../datas/lda/ldaDictionaryFR.dict') """ Explanation: 3. Perform the LDA topic modelling and print the results. Formatting the data into a dictionnary and a corpus, necessary entries for the LdaModel function of Gensim. End of explanation """ %%time ldamodel = gensim.models.ldamodel.LdaModel(corpus,num_topics=11,id2word = dictionary)#, passes=1) #ldamodel = gensim.models.hdpmodel.HdpModel(corpus, id2word=dictionary, T=50) import pyLDAvis.gensim as gensimvis import pyLDAvis vis_data = gensimvis.prepare(ldamodel, corpus, dictionary) pyLDAvis.display(vis_data) ldamodel.save('../datas/lda/ldamodelFR.model') """ Explanation: Note that in the algorithm below, we need to choose the number of topics, which is the number of clusters of data that we want to find. Note that the accuracy of our algorithm depends a lot on picking a good number of topics. End of explanation """
QinetiQ-datascience/Docker-Data-Science
WooWeb-Presentation/Workspace/Widgets/Widget List.ipynb
mit
import ipywidgets as widgets """ Explanation: Index - Back - Next Widget List End of explanation """ widgets.IntSlider( value=7, min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='i' ) """ Explanation: Numeric widgets There are 10 widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers and floats, both bounded and unbounded. The integer widgets share a similar naming scheme to their floating point counterparts. By replacing Float with Int in the widget name, you can find the Integer equivalent. IntSlider End of explanation """ widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) """ Explanation: FloatSlider End of explanation """ widgets.FloatSlider( value=7.5, min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='vertical', readout=True, readout_format='.1f', ) """ Explanation: Sliders can also be displayed vertically. End of explanation """ widgets.IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='i', ) """ Explanation: IntRangeSlider End of explanation """ widgets.FloatRangeSlider( value=[5, 7.5], min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='i', ) """ Explanation: FloatRangeSlider End of explanation """ widgets.IntProgress( value=7, min=0, max=10, step=1, description='Loading:', bar_style='', # 'success', 'info', 'warning', 'danger' or '' orientation='horizontal' ) """ Explanation: IntProgress End of explanation """ widgets.FloatProgress( value=7.5, min=0, max=10.0, step=0.1, description='Loading:', bar_style='info', orientation='horizontal' ) """ Explanation: FloatProgress End of explanation """ widgets.BoundedIntText( value=7, min=0, max=10, step=1, description='Text:', disabled=False ) """ Explanation: The numerical text boxes that impose some limit on the data (range, integer-only) impose that restriction when the user presses enter. BoundedIntText End of explanation """ widgets.BoundedFloatText( value=7.5, min=0, max=10.0, step=0.1, description='Text:', disabled=False ) """ Explanation: BoundedFloatText End of explanation """ widgets.IntText( value=7, description='Any:', disabled=False ) """ Explanation: IntText End of explanation """ widgets.FloatText( value=7.5, description='Any:', disabled=False ) """ Explanation: FloatText End of explanation """ widgets.ToggleButton( value=False, description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='check' ) """ Explanation: Boolean widgets There are three widgets that are designed to display a boolean value. ToggleButton End of explanation """ widgets.Checkbox( value=False, description='Check me', disabled=False ) """ Explanation: Checkbox End of explanation """ widgets.Valid( value=False, description='Valid!', disabled=False ) """ Explanation: Valid The valid widget provides a read-only indicator. End of explanation """ widgets.Dropdown( options=['1', '2', '3'], value='2', description='Number:', disabled=False, ) """ Explanation: Selection widgets There are several widgets that can be used to display single selection lists, and two that can be used to select multiple values. All inherit from the same base class. You can specify the enumeration of selectable options by passing a list (options are either (label, value) pairs, or simply values for which the labels are derived by calling str). You can also specify the enumeration as a dictionary, in which case the keys will be used as the item displayed in the list and the corresponding value will be used when an item is selected (in this case, since dictionaries are unordered, the displayed order of items in the widget is unspecified). Dropdown End of explanation """ widgets.Dropdown( options={'One': 1, 'Two': 2, 'Three': 3}, value=2, description='Number:', ) """ Explanation: The following is also valid: End of explanation """ widgets.RadioButtons( options=['pepperoni', 'pineapple', 'anchovies'], # value='pineapple', description='Pizza topping:', disabled=False ) """ Explanation: RadioButtons End of explanation """ widgets.Select( options=['Linux', 'Windows', 'OSX'], value='OSX', # rows=10, description='OS:', disabled=False ) """ Explanation: Select End of explanation """ widgets.SelectionSlider( options=['scrambled', 'sunny side up', 'poached', 'over easy'], value='sunny side up', description='I like my eggs ...', disabled=False, continuous_update=False, orientation='horizontal', readout=True ) """ Explanation: SelectionSlider End of explanation """ import datetime dates = [datetime.date(2015,i,1) for i in range(1,13)] options = [(i.strftime('%b'), i) for i in dates] widgets.SelectionRangeSlider( options=options, index=(0,11), description='Months (2015)' ) """ Explanation: SelectionRangeSlider The value, index, and label keys are 2-tuples of the min and max values selected. The options must be nonempty. End of explanation """ widgets.ToggleButtons( options=['Slow', 'Regular', 'Fast'], description='Speed:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Description of slow', 'Description of regular', 'Description of fast'], # icons=['check'] * 3 ) """ Explanation: ToggleButtons End of explanation """ widgets.SelectMultiple( options=['Apples', 'Oranges', 'Pears'], value=['Oranges'], #rows=10, description='Fruits', disabled=False ) """ Explanation: SelectMultiple Multiple values can be selected with <kbd>shift</kbd> and/or <kbd>ctrl</kbd> (or <kbd>command</kbd>) pressed and mouse clicks or arrow keys. End of explanation """ widgets.Text( value='Hello World', placeholder='Type something', description='String:', disabled=False ) """ Explanation: String widgets There are several widgets that can be used to display a string value. The Text and Textarea widgets accept input. The HTML and HTMLMath widgets display a string as HTML (HTMLMath also renders math). The Label widget can be used to construct a custom control label. Text End of explanation """ widgets.Textarea( value='Hello World', placeholder='Type something', description='String:', disabled=False ) """ Explanation: Textarea End of explanation """ widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()]) """ Explanation: Label The Label widget is useful if you need to build a custom description next to a control using similar styling to the built-in control descriptions. End of explanation """ widgets.HTML( value="Hello <b>World</b>", placeholder='Some HTML', description='Some HTML', disabled=False ) """ Explanation: HTML End of explanation """ widgets.HTMLMath( value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$", placeholder='Some HTML', description='Some HTML', disabled=False ) """ Explanation: HTML Math End of explanation """ file = open("images/WidgetArch.png", "rb") image = file.read() widgets.Image( value=image, format='png', width=300, height=400, ) """ Explanation: Image End of explanation """ widgets.Button( description='Click me', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me', icon='check' ) """ Explanation: Button End of explanation """ play = widgets.Play( # interval=10, value=50, min=0, max=100, step=1, description="Press play", disabled=False ) slider = widgets.IntSlider() widgets.jslink((play, 'value'), (slider, 'value')) widgets.HBox([play, slider]) """ Explanation: Play (Animation) widget The Play widget is useful to perform animations by iterating on a sequence of integers with a certain speed. The value of the slider below is linked to the player. End of explanation """ widgets.DatePicker( description='Pick a Date' ) """ Explanation: Date picker The date picker widget works in Chrome and IE Edge, but does not currently work in Firefox or Safari because they do not support the HTML date input field. End of explanation """ widgets.ColorPicker( concise=False, description='Pick a color', value='blue' ) """ Explanation: Color picker End of explanation """ widgets.Controller( index=0, ) """ Explanation: Controller The Controller allows a game controller to be used as an input device. End of explanation """ items = [widgets.Label(str(i)) for i in range(4)] widgets.Box(items) """ Explanation: Container/Layout widgets These widgets are used to hold other widgets, called children. Each has a children property that may be set either when the widget is created or later. Box End of explanation """ items = [widgets.Label(str(i)) for i in range(4)] widgets.HBox(items) """ Explanation: HBox End of explanation """ items = [widgets.Label(str(i)) for i in range(4)] left_box = widgets.VBox([items[0], items[1]]) right_box = widgets.VBox([items[2], items[3]]) widgets.HBox([left_box, right_box]) """ Explanation: VBox End of explanation """ accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()]) accordion.set_title(0, 'Slider') accordion.set_title(1, 'Text') accordion """ Explanation: Accordion End of explanation """ tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4'] children = [widgets.Text(description=name) for name in tab_contents] tab = widgets.Tab() tab.children = children for i in range(len(children)): tab.set_title(i, str(i)) tab """ Explanation: Tabs In this example the children are set after the tab is created. Titles for the tabes are set in the same way they are for Accordion. End of explanation """
vravishankar/Jupyter-Books
pandas/05.Pandas - Combining and Reshaping Data.ipynb
mit
# import pandas, numpy and datetime import numpy as np import pandas as pd import datetime # set some pandas options for controlling output pd.set_option('display.notebook_repr_html',False) pd.set_option('display.max_columns',10) pd.set_option('display.max_rows',10) """ Explanation: Combining and Reshaping Data Combination of data in pandas is performed by concatenating two sets of data, where data is combined simply along either axes but without regard to relationships in the data. Or data can be combined using relationships in the data by using a pandas capability referred to as merging, which provides join operations that are similar to those in many relational databases. Reshaping - There are three primary means of reshaping the data. Pivoting - restructure pandas data similarly to how spreadsheets pivot data by creating new index levels and moving data into columns based upon values. Stacking and Unstacking - Similar to pivoting but allow us to pivot data organised with multiple level of indexes Melting - Allows to restructure data into unique ID-variable-measurement combinations that are required for many statistical analyses. Setting up the Jupyter Notebook End of explanation """ # two series objects to concatenate s1 = pd.Series(np.arange(0,3)) s2 = pd.Series(np.arange(5,8)) s1 s2 """ Explanation: Concatenating Data End of explanation """ # concatenate them pd.concat([s1,s2]) # dataframe objects can also be concatenated # create two dataframe objects to concatenate # using the same index labels and column names # but different values df1 = pd.DataFrame(np.arange(9).reshape(3,3), columns=['a','b','c']) df2 = pd.DataFrame(np.arange(9,18).reshape(3,3),columns=['a','b','c']) pd.concat([df1,df2]) # demonstrate concatenating two dataframe objects # with different columns df1 = pd.DataFrame(np.arange(9).reshape(3,3), columns=['a','b','c']) df2 = pd.DataFrame(np.arange(9,18).reshape(3,3),columns=['a','c','d']) pd.concat([df1,df2]) # concat the two objects, but create an index using the given keys c = pd.concat([df1,df2],keys=['df1','df2']) c # we can extract data originating from the first or second source dataframe c.loc['df2'] """ Explanation: concat method End of explanation """ # concat df1 and df2 along columns # aligns on row labels, has duplicate columns pd.concat([df1,df2],axis=1) # a new dataframe to merge with df1 # this has two common row labels(2,3) # common columns (a) and one disjoint column # in each (b in df1 and d in df2) df3 = pd.DataFrame(np.arange(20,26).reshape(3,2),columns=['a','d'],index=[2,3,4]) df3 # concat them. Alignment is along row labels # columns first from df1 and then df3, with duplicates. # NaN filled in where those columns do not exist in the source pd.concat([df1,df3],axis=1) """ Explanation: The pd.concat() function also allows you to specify the axis on which to apply the concatenation. End of explanation """ # do an inner join instead of outer # results in one row pd.concat([df1,df3],axis=1,join='inner') # add keys to the columns df = pd.concat([df1,df2],axis=1,keys=['df1','df2']) df # retrieve the data that originated from the # DataFrame with key = df2 df.loc[:,'df2'] """ Explanation: A concatenation of two or more DataFrame objects actually performs an outer join operation along the index labels on the axis opposite to the one specified. This makes the result of the concatenation similar to having performed a union of those index labels, and then data is filled based on the alignment of those labels to the source objects. The type of join can be changed to an inner join and can be performed by specifying join='inner' as the parameter. The inner join then logically performs an intersection instead of a union. End of explanation """ # append does a concatenate along axis = 0 # duplicate row index labels can result df1.append(df2) # remove duplicates in the result index by ignoring the # index labels in the source DataFrame objects df1.append(df2,ignore_index=True) """ Explanation: append method End of explanation """ # these are customers data customers = {'CustomerID':[10,11],'Name':['Mike','Marcia'],'Address':['Address for Mike','Address for Marcia']} customers = pd.DataFrame(customers) customers # and these are the orders made by our customers # they are related to customers by CustomerID orders = {'CustomerID':[10,11,10],'OrderDate':[datetime.date(2014,12,1),datetime.date(2014,12,1),datetime.date(2014,12,1)]} orders = pd.DataFrame(orders) orders # merge customers and orders so we can ship the items customers.merge(orders) """ Explanation: Merging and Joining Data pandas allows the merging of pandas objects with database-like join operations using the pd.merge() function and the .merge() method of a DataFrame object. These joins are high performance and are performed in memory. A merge combines the data of two pandas objects by finding matching values in one or more columns or row indexes. End of explanation """ # sample data left_data = {'Key1':['a','b','c'],'Key2':['x','y','z'],'lval1':[0,1,2]} right_data = {'Key1':['a','b','c'],'Key2':['x','a','z'],'rval1':[6,7,8]} left = pd.DataFrame(left_data,index=[0,1,2]) right = pd.DataFrame(right_data,index=[1,2,3]) left right # demonstrate merge without specifying columns to merge # this will implicitly merge on all common columns left.merge(right) # demonstrate merge using an explicit column # on needs the value to be in both DataFrame objects left.merge(right,on='Key1') # merge explicitly using two columns left.merge(right,on=['Key1','Key2']) # join on the row indices of both matrices pd.merge(left,right,left_index=True,right_index=True) """ Explanation: pandas has done something magical for us here by being able to accomplish this with such a simple piece of code. What pandas has done is realized that our customers and orders objects both have a column named CustomerID. With this knowledge, it uses common values found in that column of both DataFrame objects to related the data in both and form the merged data based on inner join semantics. Determines the columns in both customers and orders with common labels. These columns are treated as the keys to perform the join. It creates a new DataFrame whose columns are the labels from the keys identified in step 1, followed by all of the non-key labels from both objects. It matches values in the key columns of both DataFrame objects. It then creates a row in the result for each set of matching labels. It then copies the data from those matching rows from each source object into that respective row and columns of the result. It assigns a new Int64Index to the result. End of explanation """ # outer join, merges all matched data # and fills unmatched items with NaN left.merge(right,how='outer') # left join, merges all matched data and only fills unmatched # items from the left dataframe with NaN filled for the # unmatched items in the result # rows with labels 0 and 2 # match on key1 and key2 the row with label 1 is from left left.merge(right,how="left") # right join, merges all matched data and only fills unmatched # items from the right with NaN filled for the unmatched items # in the result # rows with labels 0 and 1 match on key1 and key2 # the row with label 2 is from right left.merge(right, how='right') # join left with right (default method is outer) # and since these DataFrame objects have duplicate column names # we just specify lsuffix and rsuffix left.join(right,lsuffix='_left',rsuffix='_right') # join left with right with an inner join left.join(right, lsuffix='_left',rsuffix='_right',how='inner') """ Explanation: This has identified that the index labels in common are 1 and 2, so the resulting DataFrame has two rows with these values and label in the index. pandas then creates a column in the result for every column in both objects and then copies the values. As both DataFrame objects had a column with a identifcal name, key, the columns in the result have the _x and _y suffixes appended to them to identify the DataFrame they originated from. Specifying the join semantics of a merge operation The default type of join performed by pd.merge() is an inner join. To use another join method, the method of join to be used can be specified using the how parameter of the pd.merge() function. The valid options are: * inner - This is the intersection of keys from both DataFrame objects * outer - This is the union of keys from both DataFrame objects * left - This only uses keys from the left DataFrame * right - This only uses keys from the right DataFrame End of explanation """ # read in accellerometer data sensor_readings = pd.read_csv('../../data/accel.csv') sensor_readings # extract X-axis readings sensor_readings[sensor_readings['axis'] == 'X'] # pivot the data. Interval becomes the index, the columns are # the current axes values and use the readings as values sensor_readings.pivot(index='interval',columns='axis',values='reading') """ Explanation: Pivoting Data is often stored in a stacked format, which is also referred to as record format; this is common in databases, .csv files and Excel spreadsheets. In a stacked format, the data is often not normalized and has repeated values in many columns, or values that should logically exists in other tables. End of explanation """ # simple DataFrame with one column df = pd.DataFrame({'a':[1,2]}, index={'one','two'}) df """ Explanation: This has taken all of the distinct values from the axis column, and pivoted them into columns on the new DataFrame, while filling in values for the new columns from the appropriate rows and columns of the original DataFrame. Stacking and Unstacking Stacking pivots a level of column labels to the row index. Unstacking pivots a level of the row index into the column index. One of the differences between stacking/unstacking and peforming a pivot is that unlike pivots the stack and unstack functions will be able to pivot specific levels of a hierarchical index. Also, where a pivot retains the same number of levels on an index, a stack and unstack will always increase the levels on the index of one of the axes and decrease the levels on the other axis. End of explanation """ # push the column to another level of the index # the result is a Series where values are looked up through # a multi-index stacked1 = df.stack() stacked1 # lookup one / a using just index via a tuple stacked1[('one','a')] # DataFrame with two columns df = pd.DataFrame({'a':[1,2],'b':[3,4]},index={'one','two'}) df # push the two columns into a single level of index stacked2 = df.stack() stacked2 # lookup value with index one / b stacked2[('two','b')] """ Explanation: Stacking will move one level of the columns index into a new level of the rows index. As our DataFrame only has one level, this collapses a DataFrame object into a Series object with a hierarchical row index: End of explanation """ # make two copies of the sensor data, one for each user user1 = sensor_readings.copy() user2 = sensor_readings.copy() # add names to the two copies user1['who'] = 'Mike' user2['who'] = 'Mikael' # for demonstration, lets scale user2's readings user2['reading'] *= 100 # and reorganize this to have a hierarchical row index multi_user_sensor_data = pd.concat([user1,user2]).set_index(['who','interval','axis']) multi_user_sensor_data # look up user data for Mike using just the index multi_user_sensor_data.loc['Mike'] # readings for all users and axes at interval 1 multi_user_sensor_data.xs(1,level='interval') """ Explanation: Unstacking End of explanation """ # unstack axis multi_user_sensor_data.unstack() # unstack at level=0 multi_user_sensor_data.unstack(level=0) """ Explanation: Unstacking will move the last level of the row index into a new level of the columns index resulting in columns having MultiIndex. End of explanation """ # unstack who and axis levels unstacked = multi_user_sensor_data.unstack(['who','axis']) unstacked # and we can of course stack what we have unstacked # this re-stacks who unstacked.stack(level='who') """ Explanation: Multiple levels can be unstacked simultaneously by passing a list of the level to .unstack(). Additionally if the levels are named, they can be specified by name instead of location. End of explanation """ # we will demonstrate melting in this DataFrame data = pd.DataFrame({'Name':['Mike','Mikael'],'Height':[6.1,5.9], 'Weight':[220,185]}) data # melt it, use Name as the id, # Height and Weight columns as the variables pd.melt(data,id_vars=['Name'],value_vars=['Height','Weight']) """ Explanation: There are couple of points to be noticed here: * Stacking and unstacking always move the levels into the last levels of the other index. Note that the who level is now the last level of the row index, but started out earlier as the first level. This would have ramifications on the code to access elements via that index as it has changed to another level. If you want to put a level back into another position you need to reorganise the indexes with other means than stacking and unstacking. * With all this moving around of data, stacking and unstacking do not lose any information. They simply change the means by which it is organized and accessed. Melting Melting is a type of unpivoting, and is often referred as changing a DataFrame object from wide format to long format. Technically, it is the process of reshaping a DataFrame into a format where two or more columns, referred to as variable and value are created by unpivoting column lables in the variable column and then moving the data from these columns into the appropriate location in the value column. End of explanation """ # stacked scalar access can be a lot faster than # column access # time the different methods import timeit t = timeit.Timer("stacked1[('one','a')]","from __main__ import stacked1, df") r1 = timeit.timeit(lambda: stacked1.loc[('one','a')],number=10000) r2 = timeit.timeit(lambda: df.loc['one']['a'],number=10000) r3 = timeit.timeit(lambda: df.iloc[1,0],number=10000) # and the results are r1,r2,r3 """ Explanation: The data is now structured so that it is easy to extract the value for any combination of variable and Name. Additionally, when in this format it is easier to add a new variable and measurement as the data can simply be added as a new row instead of requiring a change of structure to DataFrame by adding a new column. Performance Benefits End of explanation """
peteWT/cec_apl
Biomass/ReadFromDBv2.ipynb
mit
import pandas as pd from sqlalchemy import create_engine """ Explanation: This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch and create geospatial coordinate and indexes. Install using pip or any other package manager pandas, sqlalchemy and pg8000. The later one is the driver to connect to the db. End of explanation """ def connection(user,passwd,dbname, echo_i=False): str1 = ('postgresql+pg8000://' + user +':' + passw + '@switch-db2.erg.berkeley.edu:5432/' + dbname + '?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') engine = create_engine(str1,echo=echo_i,isolation_level='AUTOCOMMIT') return engine user = 'jdlara' passw = 'Amadeus-2010' dbname = 'apl_cec' engine_db= connection(user,passw,dbname) """ Explanation: After importing the required packages, first create the engine to connect to the DB. The approach I generally use is to create a string based on the username and password. The code is a function, you just need to fill in with the username, password and the dbname. It allows you to create different engines to connect to serveral dbs. End of explanation """ #excel_file = 'substations_table.xlsx' #tab_name = 'sheet1' csv_name = ['LEMMA_ADS_AllSpp_2016_Turbo_01252016.csv'] schema_for_upload = 'lemma2016' for name in csv_name: pd_data = pd.read_csv(name, encoding='UTF-8') pd_data.to_sql(name, engine_db, schema=schema_for_upload, if_exists='replace',chunksize=1000) """ Explanation: Afterwards, use pandas to import the data from Excel files or any other text file format. Make sure that the data in good shape before trying to push it into the server. In this example I use previous knowledge of the structure of the tabs in the excel file to recursively upload each tab and match the name of the table with the tab name. If you are using csv files just change the commands to pd.read_csv() in this link you can find the documentation. Before doing this I already checked that the data is properly organized, crate new cells to explore the data beforehand if needed excel_file = 'substations_table.xlsx' tab_name = 'sheet1' schema_for_upload = 'geographic_data' pd_data.to_sql(name, engine_db, schema=schema_for_upload, if_exists='replace',chunksize=100) End of explanation """ def create_geom(table,schema,engine, projection=5070): k = engine.connect() query = ('set search_path = "'+ schema +'"'+ ', public;') print query k.execute(query) query = ('alter table ' + table + ' drop column if exists geom;') print query k.execute(query) query = 'SELECT AddGeometryColumn (\''+ schema + '\',\''+ table + '\',\'geom\''+',5070,\'POINT\',2);' print query k.execute(query) query = ('UPDATE ' + table + ' set geom = ST_SetSRID(st_makepoint(' + table + '.x, ' + table + '.y),' + str(projection) + ')::geometry;') k.execute(query) print query k = engine.dispose() return 'geom column added with SRID ' + str(projection) table = 'results_approach1' schema = 'lemma2016' create_geom(table,schema,engine_db) """ Explanation: Once the data is updated, it is possible to run the SQL commands to properly create geom columns in the tables, this can be done as follows. The ojective is to run an SQL querie like this: PGSQL set search_path = SCHEMA, public; alter table vTABLE drop column if exists geom; SELECT AddGeometryColumn ('SCHEMA','vTABLE','geom',4326,'POINT',2); UPDATE TABLE set geom = ST_SetSRID(st_makepoint(vTABLE.lon, vTABLE.lat), 4326)::geometry; where SCHEMA and vTABLE are the variable portions. Also note, that this query assumes that your columns with latitude and longitude are named lat and lon respectively; moreover, it also assumes that the coordinates are in the 4326 projection. The following function runs the query for you, considering again that the data is clean and nice. End of explanation """ def create_pk(table,schema,column,engine): k = engine.connect() query = ('set search_path = "'+ schema +'"'+ ', public;') print query k.execute(query) query = ('alter table ' + table + ' ADD CONSTRAINT '+ table +'_pk PRIMARY KEY (' + column + ')') print query k.execute(query) k = engine.dispose() return 'Primary key created with column' + column col = '' create_pk(table,schema,col,engine_db) """ Explanation: The function created the geom column, the next step is to define a function to create the Primary-Key in the db. Remember that the index from the data frame is included as an index in the db, sometimes an index is not really neded and might need to be dropped. End of explanation """ def create_gidx(table,schema,engine,column='geom'): k = engine.connect() query = ('set search_path = "'+ schema +'"'+ ', public;') k.execute(query) print query query = ('CREATE INDEX ' + table + '_gix ON ' + table + ' USING GIST (' + column + ');') k.execute(query) print query query = ('VACUUM ' + table + ';') k.execute(query) print query query = ('CLUSTER ' + table + ' USING ' + table + '_gix;') k.execute(query) print query query = ('ANALYZE ' + table + ';') k.execute(query) print query k = engine.dispose() return k create_gidx(table,schema,engine_db) """ Explanation: The reason why we use postgis is to improve geospatial queries and provide a better data structure for geospatial operations. Many of the ST_ functions have improved performance when a geospatial index is created. The process implemented here comes from this workshop. This re-creates the process using python functions so that it can be easily replicated for many tables. The query to create a geospatial index is as follows: SQL set search_path = SCHEMA, public; CREATE INDEX vTABLE_gix ON vTABLE USING GIST (geom); This assumes that the column name with the geometry is named geom. If the process follows from the previous code, it will work ok. The following step is to run a VACUUM, creating an index is not enough to allow PostgreSQL to use it effectively. VACUUMing must be performed when ever a new index is created or after a large number of UPDATEs, INSERTs or DELETEs are issued against a table. SQL VACUUM ANALYZE vTABLE; The final step corresponds to CLUSTERING, this process re-orders the table according to the geospatial index we created. This ensures that records with similar attributes have a high likelihood of being found in the same page, reducing the number of pages that must be read into memory for some types of queries. When a query to find nearest neighbors or within a certain are is needed, geometries that are near each other in space are near each other on disk. The query to perform this clustering is as follows: CLUSTER vTABLE USING vTABLE_gix; ANALYZE vTABLE; End of explanation """
jsnajder/StrojnoUcenje
notebooks/SU-2015-4-BayesovKlasifikator.ipynb
cc0-1.0
import scipy as sp import scipy.stats as stats import matplotlib.pyplot as plt import pandas as pd %pylab inline """ Explanation: Sveučilište u Zagrebu<br> Fakultet elektrotehnike i računarstva Strojno učenje <a href="http://www.fer.unizg.hr/predmet/su">http://www.fer.unizg.hr/predmet/su</a> Ak. god. 2015./2016. Bilježnica 4: Bayesov klasifikator (c) 2015 Jan Šnajder <i>Verzija: 0.7 (2015-10-31)</i> End of explanation """ q101 = pd.read_csv("http://www.fer.unizg.hr/_download/repository/questions101-2014.csv", comment='#') q101[:20] """ Explanation: Sadržaj: Bayesovska klasifikacija Naivan Bayesov klasifikator Primjer: 101 Questions Polunaivan Bayesov klasifikator* Bayesov klasifikator za kontinuirane značajke Bayesov klasifikator: komponente algoritma Sažetak Bayesovska klasfikacija Bayesovo pravilo $$ P(\mathcal{C}j|\mathbf{x}) = \frac{P(\mathbf{x},\mathcal{C}_j)}{P(\mathbf{x})} = \frac{p(\mathbf{x}|\mathcal{C}_j) P(\mathcal{C}_j)}{p(\mathbf{x})} = \frac{p(\mathbf{x}|\mathcal{C}_j)P(\mathcal{C}_j)}{\sum{k=1}^K p(\mathbf{x}|\mathcal{C}_k)P(\mathcal{C}_k)} $$ Apriorna vjerojatnost klase $\mathcal{C}_j$: Binarna ($K=2)$ klasifikacija: Bernoullijeva razdioba Višeklasna ($K>2$) klasifikacija: kategorička razdioba Izglednost klase $p(\mathbf{x}|\mathcal{C}_j)$: Diskretne značajke: Bernoullijeva/kategorička razdioba Kontinuirane značajke: Gaussova razdioba Ovo je parametarski i generativni model Q: Zašto? Klasifikacijska odluka MAP-hipoteza: \begin{align} h : \mathcal{X} &\to {\mathcal{C}1, \mathcal{C}_2,\dots, \mathcal{C}_K}\ h(\mathbf{x})&=\displaystyle\mathrm{argmax}{\mathcal{C}_k}\ p(\mathbf{x}|\mathcal{C}_k) P(\mathcal{C}_k) \end{align} Pouzdanost klasifikacije u $\mathcal{C}_j$: \begin{align} h_j : \mathcal{X} &\to [0,\infty)\ h_j(\mathbf{x})&=p(\mathbf{x}|\mathcal{C}_k) P(\mathcal{C}_k) \end{align} Vjerojatnost klasifikacije u $\mathcal{C}_j$: \begin{align} h_j : \mathcal{X} &\to [0,1]\ h_j(\mathbf{x})&=P(\mathcal{C}_k|\mathbf{x}) \end{align} Primjer $P(\mathcal{C}_1) = P(\mathcal{C}_2)=0.3$, $P(\mathcal{C}_3)=0.4$ Za neki primjer $\mathbf{x}$ imamo: $p(\mathbf{x}|\mathcal{C}_1)=0.9$, $p(\mathbf{x}|\mathcal{C}_2)=p(\mathbf{x}|\mathcal{C}_3)=0.4$ U koju klasu klasificiramo $\mathbf{x}$? Minimizacija pogreške klasifikacije* Pretpostavimo da primjeri u stvarnosti dolaze iz dva područja: $\mathcal{R}_1={\mathbf{x}\in\mathcal{X}\mid h_1(\mathbf{x})=1}$ $\mathcal{R}_2=\mathcal{X}\setminus\mathcal{R}_1$ Vjerojatnost pogrešne klasifikacije: \begin{align} P(\mathbf{x}\in\mathcal{R}1,\mathcal{C}_2) &+ P(\mathcal{x}\in\mathcal{R}_2,\mathcal{C}_1)\ \int{\mathbf{x}\in\mathcal{R}1} p(\mathbf{x},\mathcal{C}_2)\,\mathrm{d}\mathbf{x} &+ \int{\mathbf{x}\in\mathcal{R}_2} p(\mathbf{x},\mathcal{C}_1)\,\mathrm{d}\mathbf{x} \end{align} [Skica] Pogreška je minimizirana kada $\mathcal{C}j = \mathrm{argmax}{\mathcal{C}\in{\mathcal{C_1},\mathcal{C_2}}} P(\mathbf{x},\mathcal{C}_j) $ Alternativa: Minimizacija rizika* $L_{kj}$ - gubitak uslijed pogrešne klasifikacije primjera iz klase $\mathcal{C}_k$ u klasu $\mathcal{C}_j$ Očekivani gubitak (funkcija rizika): $$ \mathbb{E}[L] = \sum_{k=1}^K\sum_{j=1}^K \int_{\mathbf{x}\in\mathcal{R}j} L{kj}\,p(\mathbf{x},\mathcal{C}_k)\,\mathrm{d}\mathbf{x} $$ Očekivani rizik pri klasifikaciji $\mathbf{x}$ u $\mathcal{C}_j$: $$ R(\mathcal{C}j|\mathbf{x}) = \sum{k=1}^K L_{kj}P(\mathcal{C}_k|\mathbf{x}) $$ Optimalna klasifikacijska odluka: $$ h(\mathbf{x}) = \mathrm{argmin}_{\mathcal{C}_k} R(\mathcal{C}_k|\mathbf{x}) $$ Primjer $P(\mathcal{C}_1|\mathbf{x}) = 0.25$, $P(\mathcal{C}_2|\mathbf{x}) = 0.6$, $P(\mathcal{C}_3|\mathbf{x}) = 0.15$ $$ L = {\small \begin{pmatrix} 0 & 1 & 5 \ 1 & 0 & 5 \ 10 & 100 & 0 \end{pmatrix}} $$ Naivan Bayesov klasifikator $\mathcal{D}={(\mathbf{x}^{(i)},y^{(i)})}_{i=1}^N$ $y^{(i)}\in{\mathcal{C}_1,\dots,\mathcal{C}_K}$ Model: \begin{align} P(\mathcal{C}j|x_1,\dots,x_n)\ &\propto\ P(x_1,\dots,x_n|\mathcal{C}_j)P(\mathcal{C}_j)\ h(\mathbf{x}=x_1,\dots,x_n) &= \mathrm{argmax}{j}\ P(\mathbf{x}=x_1,\dots,x_n|y=\mathcal{C}_j)P(y = \mathcal{C}_j) \end{align} ML-procjena za $P(y)$ (kategorička razdioba): $$ \hat{P}(\mathcal{C}j)=\frac{1}{N}\sum{i=1}^N\mathbf{1}{y^{(i)}=\mathcal{C}_j} = \frac{N_j}{N} $$ Q: Broj parametara za $\hat{P}(\mathcal{C}_j)$, $j=1,\dots,K$ ? Procjena parametara za $P(x_1,\dots,x_n|\mathcal{C}_j)$? Tretirati $\mathbf{x} = (x_1,\dots,x_n)$ kao kategoričku varijablu (njezine vrijednosti su sve kombinacije vrijednosti $x_i$) ? Broj parametara? Generalizacija? Pravilo lanca (uz uvjetnu varijablu $\mathcal{C}_j$): \begin{equation} P(x_1,\dots,x_n|\mathcal{C}j) = \prod{k=1}^n P(x_k|x_1,\dots,x_{k-1},\mathcal{C}_j) \end{equation} Pretpostavka: $\color{red}{x_i\bot x_k|\mathcal{C}_j\ (i\neq k)} \ \Leftrightarrow \ \color{red}{P(x_i|x_k,\mathcal{C}_j) = P(x_i|\mathcal{C}_j)}$ \begin{equation} P(x_1,\dots,x_n|\mathcal{C}j) = \prod{k=1}^n P(x_k|x_1,\dots,x_{k-1},\mathcal{C}j) = \prod{k=1}^n P(x_k|\mathcal{C}_j) \end{equation} Naivan Bayesov klasifikator: $$ h(x_1,\dots,x_n) = \mathrm{argmax}j\ P(\mathcal{C}_j)\prod{k=1}^n P(x_k|\mathcal{C}_j) $$ ML-procjena: $$ \hat{P}(x_k|\mathcal{C}j)=\frac{\sum{i=1}^N\mathbf{1}\big{x^{(i)}k=x_k \land y^{(i)}=\mathcal{C}_j\big}} {\sum{i=1}^N \mathbf{1}{y^{(i)} = \mathcal{C}j}} = \frac{N{kj}}{N_j} $$ Laplaceov procjenitelj: $$ \hat{P}(x_k|\mathcal{C}j)=\frac{\sum{i=1}^N\mathbf{1}\big{x^{(i)}k=x_k \land y^{(i)}=\mathcal{C}_j\big} + \lambda} {\sum{i=1}^N \mathbf{1}{y^{(i)} = \mathcal{C}j} + \lambda K_k} = \frac{N{kj}+\lambda}{N_j+\lambda K_k} $$ Broj parametara: $\sum_{k=1}^n(K_k-1)K$ Binarne značajke: $nK$ Uvjetna nezavisnost? Vrijedi li općenito nezavisnost $x_i\bot x_k|\mathcal{C}_j\ (i\neq k)$? Primjer: Klasifikacija teksta Kategorija $\mathcal{C} = \text{Sport}$ $D$: tekstni dokument Značajke: $x_1=\mathbf{1}{\text{Zagreb}\in D}$, $x_2 = \mathbf{1}{\text{lopta}\in D}$, $x_3=\mathbf{1}{\text{gol}\in D}$ Q: $x_1 \bot x_2 | \mathcal{C}$ ? Q: $x_2 \bot x_3 | \mathcal{C}$ ? Primjer: Dobar SF-film $$ \begin{array}{r c c c c c } \hline & x_1 & x_2 & x_3 & x_4 & y\ i & \text{Mjesto radnje} & \text{Glavni lik} & \text{Vrijeme radnje} & \text{Vanzemaljci} & \text{Dobar film}\ \hline 1 & \text{svemir} & \text{znanstvenica} & \text{sadašnjost} & \text{da} & \text{ne} \ 2 & \text{Zemlja} & \text{kriminalac} & \text{budućnost} & \text{ne} & \text{ne} \ 3 & \text{drugdje} & \text{dijete} & \text{prošlost} & \text{da} & \text{ne} \ 4 & \text{svemir} & \text{znanstvenica} & \text{sadašnjost} & \text{ne} & \text{da} \ 5 & \text{svemir} & \text{kriminalac} & \text{prošlost} & \text{ne} & \text{ne} \ 6 & \text{Zemlja} & \text{dijete} & \text{prošlost} & \text{da} & \text{da} \ 7 & \text{Zemlja} & \text{policajac} & \text{budućnost} & \text{da} & \text{ne} \ 8 & \text{svemir} & \text{policajac} & \text{budućnost} & \text{ne} & \text{da} \ \hline \end{array} $$ Q: Koja je klasifikacija novog primjera $\mathbf{x} = (\text{svemir}, \text{dijete}, \text{sadašnjost}, \text{da})$ ? Primjer: 101 Questions End of explanation """ q101[['Q7','Q101','Q97','Q4']][:20] X = q101[['Q7','Q101','Q97']][:20].as_matrix() y = q101['Q4'][:20].as_matrix() # Apriorna vjerojatnost klase: P(C_j) def class_prior(y, label): N = len(y) return len(y[y==label]) / float(len(y)) # Izglednost klase: P(x_i|C_j) def class_likelihood(X, y, feature_ix, value, label): N = len(X) y_ix = y==label Nj = len(y[y_ix]) Nkj = len(X[sp.logical_and(y_ix, X[:,feature_ix]==value)]) return (Nkj + 1) / (float(Nj) + 2) # Laplace smoothed p_Psi = class_prior(y, 'Psi') p_Psi p_Macke = class_prior(y, 'Mačke') p_Macke p_Messi_Psi = class_likelihood(X, y, 0, 'Messi', 'Psi') p_Messi_Psi p_Ronaldo_Psi = class_likelihood(X, y, 0, 'Ronaldo', 'Psi') p_Ronaldo_Psi """ Explanation: Q: Voli li onaj tko preferira Messija, Batmana i Tenisice više pse ili mačke? End of explanation """ class_prior(y, 'Psi') \ * class_likelihood(X, y, 0, 'Messi', 'Psi') \ * class_likelihood(X, y, 1, 'Batman', 'Psi') \ * class_likelihood(X, y, 2, 'Tenisice', 'Psi') \ class_prior(y, 'Mačke') \ * class_likelihood(X, y, 0, 'Messi', 'Mačke') \ * class_likelihood(X, y, 1, 'Batman', 'Mačke') \ * class_likelihood(X, y, 2, 'Tenisice', 'Mačke') \ """ Explanation: Q: Klasifikacija za $\mathbf{x} = (\text{Messi}, \text{Batman}, \text{Tenisice})$ End of explanation """ from sklearn.metrics import mutual_info_score X = stats.bernoulli.rvs(0.5, size=100) Y = stats.bernoulli.rvs(0.2, size=100) mutual_info_score(X, Y) mutual_info_score(X, X) X = stats.bernoulli.rvs(0.5, size=100) Y = [(sp.random.randint(2) if x==1 else 0) for x in X ] mutual_info_score(X, Y) """ Explanation: Polunaivan klasifikator* Ideja Ako, na primjer, ne vrijedi $x_2\bot x_3|\mathcal{C}_j$, onda je bolje umjesto: $$ P(\mathcal{C}_j|x_1,x_2,x_3)\ \propto\ P(x_1|\mathcal{C}_j)P(\color{red}{x_2}|\mathcal{C}_j)P(\color{red}{x_3}|\mathcal{C}_j)P(\mathcal{C}_j) $$ faktorizirati kao: $$ P(\mathcal{C}_j|x_1,x_2,x_3)\ \propto\ P(x_1|\mathcal{C}_j)P(\color{red}{x_2,x_3}|\mathcal{C}_j)P(\mathcal{C}_j) $$ što je jednako: $$ P(\mathcal{C}_j|x_1,x_2,x_3)\ \propto\ P(x_1|\mathcal{C}_j)P(x_2|\mathcal{C}_j)P(\color{red}{x_3|x_2},\mathcal{C}_j)P(\mathcal{C}_j) $$ Q: Prednosti? Q: Broj parametara? Koje varijable združiti? Problem pretraživanja prostora stanja: $$ \begin{align} &{ {a}, {b}, {c} }\ &{ {a}, {b, c} }\ &{ {b}, {a, c} }\ &{ {c}, {a, b} }\ &{ {a, b, c} } \end{align} $$ Bellov broj: $B_3=5, B_{4} = 15, B_{5} = 52, \dots, B_{10} = 115975, \dots$ Treba nam heurističko pretraživanje koje će naći optimalno združivanje (broj stanja = broj particija) Kriterij združivanja varijabli? Dvije mogućnosti: Mjerimo zavisnost varijabli i združujemo one varijable koje su najviše zavisne Algoritmi TAN i $k$-DB Unakrsna provjera: Isprobavamo točnost modela na skupu za provjeru i združujemo one varijable koje povećavaju točnost Algoritam FSSJ Q: Veza s odabirom modela? Mjerenje zavisnosti varijabli: Uzajamna informacija Mjera uzajamne informacije (uzajamnog sadržaja informacije) (engl. mutual information) Entropija $$ H(P) = -\sum_x P(x) \ln P(x) $$ Unakrsna entropija: $$ H(P,Q) = -\sum_x P(x) \ln Q(x) $$ Relativa entropija $P(x)$ u odnosu na $Q(x)$: $$ \begin{align} H(P,Q) - H(P) =& -\sum_x P(x)\ln Q(x) - \big(-\sum_x P(x)\ln P(x) \big) =\ &-\sum_x P(x)\ln Q(x) + \sum_x P(x)\ln P(x) =\ &-\sum_x P(x)\ln \frac{P(x)}{Q(x)} = \color{red}{D_{\mathrm{KL}}(P||Q)}\ \end{align} $$ $\Rightarrow$ Kullback-Leiblerova divergencija Uzajamna informacija ili uzajamni sadržaj informacije (engl. mutual information): $$ I(x,y) = D_\mathrm{KL}\big(P(x,y) || P(x) P(y)\big) = \sum_{x,y} P(x,y) \ln\frac{P(x,y)}{P(x)P(y)} $$ $I(x, y) = 0$ akko su $x$ i $y$ nezavisne varijable, inače $I(x,y) > 0$ End of explanation """ likelihood_c1 = stats.norm(110, 5) likelihood_c2 = stats.norm(150, 20) likelihood_c3 = stats.norm(180, 10) xs = linspace(70, 200, 200) plt.plot(xs, likelihood_c1.pdf(xs), label='p(x|C_1)') plt.plot(xs, likelihood_c2.pdf(xs), label='p(x|C_2)') plt.plot(xs, likelihood_c3.pdf(xs), label='p(x|C_3)') plt.legend() plt.show() """ Explanation: Uzajamnu informaciju lako možemo proširiti na uvjetnu uzajamnu informaciju (engl. conditional mutual information): $$ I(x,y\color{red}{|z}) = \sum_z P(z_k) I(x,y|z) = \color{red}{\sum_z}\sum_x\sum_y P(x,y,\color{red}{z}) \ln\frac{P(x,y\color{red}{|z})}{P(x\color{red}{|z})P(y\color{red}{|z})} $$ Bayesov klasifikator za kontinuirane značajke Jednodimenzijski slučaj Izglednost klase $p(\mathbf{x}|\mathcal{C}_j)$ modeliramo Gaussovom razdiobom: $$ \mathbf{x}|\mathcal{C}_j \sim \mathcal{N}(\mu_j,\sigma^2_j) $$ \begin{equation} p(x|\mathcal{C}_j) = \frac{1}{\sqrt{2\pi}\sigma_j}\exp\Big{-\frac{(x-\mu_j)^2}{2\sigma^2_j}\Big} \end{equation} End of explanation """ likelihood_c1 = stats.norm(100, 5) likelihood_c2 = stats.norm(150, 20) plt.plot(xs, likelihood_c1.pdf(xs), label='p(x|C_1)') plt.plot(xs, likelihood_c2.pdf(xs), label='p(x|C_2)') plt.legend() plt.show() p_c1 = 0.3 p_c2 = 0.7 def joint_x_c1(x) : return likelihood_c1.pdf(x) * p_c1 def joint_x_c2(x) : return likelihood_c2.pdf(x) * p_c2 plt.plot(xs, joint_x_c1(xs), label='p(x, C_1)') plt.plot(xs, joint_x_c2(xs), label='p(x, C_2)') plt.legend() plt.show() def p_x(x) : return joint_x_c1(x) + joint_x_c2(x) plt.plot(xs, p_x(xs), label='p(x)') plt.legend() plt.show() def posterior_c1(x) : return joint_x_c1(x) / p_x(x) def posterior_c2(x) : return joint_x_c2(x) / p_x(x) plt.plot(xs, posterior_c1(xs), label='p(C_1|x)') plt.plot(xs, posterior_c2(xs), label='p(C_2|x)') plt.legend() plt.show() """ Explanation: NB: Pretpostavljamo da je razdioba primjera unutar svake klase unimodalna (modelirana jednom Gaussovom razdiobom) Inače nam treba mješavina Gaussovih razdiobi (GMM) Model: $$ h_j(x) = p(x,\mathcal{C}_j) = p(x|\mathcal{C}_j)P(\mathcal{C}_j) $$ Radi matematičke jednostavnosti, prelazimo u logaritamsku domenu: \begin{align*} h_j(x) & = \ln p(x|\mathcal{C}_j) + \ln P(\mathcal{C}_j)\ &= \color{gray}{-\frac{1}{2}\ln 2\pi} \ln\sigma_j \frac{(x-\mu_j)^2}{2\sigma^2_j} + \ln P(\mathcal{C}_j)\ \end{align*} Uklanajnje konstante (ne utječe na maksimizaciju): $$ h_j(x|\boldsymbol{\theta}_j) = - \ln\hat{\sigma}_j \frac{(x-\hat{\mu}_j)^2}{2\hat{\sigma}^2_j} + \ln\hat{P}(\mathcal{C}_j) $$ gdje je vektor parametara jednak $$ \boldsymbol{\theta}_j=(\mu_j, \sigma_j, P(\mathcal{C}_j)) $$ ML-procjene parametara: \begin{align} \hat{\mu}j &= \frac{1}{N_j}\sum{i=1}^N \mathbf{1}{y^{(i)} = \mathcal{C}j} x^{(i)}\ \hat{\sigma}^2_j &= \frac{1}{N_j}\sum{i=1}^N\mathbf{1}{y^{(i)} = \mathcal{C}_j}(x^{(i)}-\hat{\mu}_j)^2 \ \hat{P}(\mathcal{C}_j) &= \frac{N_j}{N}\ \end{align} End of explanation """ mu_1 = [-2, 1] mu_2 = [2, 0] covm_1 = sp.array([[1, 1], [1, 3]]) covm_2 = sp.array([[2, -0.5], [-0.5, 1]]) p_c1 = 0.4 p_c2 = 0.6 likelihood_c1 = stats.multivariate_normal(mu_1, covm_1) likelihood_c2 = stats.multivariate_normal(mu_2, covm_2) x = np.linspace(-5, 5) y = np.linspace(-5, 5) X, Y = np.meshgrid(x, y) XY = np.dstack((X,Y)) plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1) plt.contour(X, Y, likelihood_c2.pdf(XY) * p_c2); """ Explanation: Višedimenzijski slučaj Izglednost klase: \begin{equation} p(\mathbf{x}|\mathcal{C}_j) = \frac{1}{(2\pi)^{n/2}|\boldsymbol{\Sigma}_j|^{1/2}} \exp\Big{-\frac{1}{2}(\mathbf{x}^{(i)}-\boldsymbol{\mu}_j)^{\mathrm{T}}\boldsymbol{\Sigma}_j^{-1}(\mathbf{x}^{(i)}-\boldsymbol{\mu}_j)\Big} \end{equation} Model: $$ \begin{align*} h_j(\mathbf{x}) &= \ln p(\mathbf{x}|\mathcal{C}_j) + \ln P(\mathcal{C}_j)\ &= \color{gray}{-\frac{n}{2}\ln 2\pi} \frac{1}{2}\ln|\boldsymbol{\Sigma}_j| \frac{1}{2}(\mathbf{x}-\boldsymbol{\mu}_j)^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}(\mathbf{x}-\boldsymbol{\mu}_j) + \ln P(\mathcal{C}_j)\ &\Rightarrow \frac{1}{2}\ln|\boldsymbol{\Sigma}_j| \frac{1}{2}(\mathbf{x}-\boldsymbol{\mu}_j)^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}(\mathbf{x}-\boldsymbol{\mu}_j) + \ln P(\mathcal{C}_j)\ \end{align*} $$ Interpretacija za $\boldsymbol{\mu}$ i $\boldsymbol{\Sigma}$: $\boldsymbol{\mu}_j$ - prototipna vrijednost primjera u klasi $\mathcal{C}_j$ $\boldsymbol{\Sigma}_j$ - količina šuma i korelacija između izvora šuma unutar $\mathcal{C}_j$ Q: Broj parametara? ML-procjene parametara: \begin{align} \hat{\boldsymbol{\mu}}j &= \frac{1}{N_j}\sum{i=1}^N\mathbf{1}{y^{(i)}=\mathcal{C}j}\mathbf{x}^{(i)}\ \hat{\boldsymbol{\Sigma}}_j &= \frac{1}{N_j}\sum{i=1}^N \mathbf{1}{y^{(i)}=\mathcal{C}_j}(\mathbf{x}^{(i)}-\hat{\boldsymbol{\mu}}_j)(\mathbf{x}^{(i)}-\hat{\boldsymbol{\mu}}_j)^\mathrm{T}\ \hat{P}(\mathcal{C}_j) &= \frac{N_j}{N} \end{align} O kovarijacijskoj matrici \begin{equation} \boldsymbol{\Sigma} = \begin{pmatrix} \mathrm{Var}(x_1) & \mathrm{Cov}(x_1, x_2) & \dots & \mathrm{Cov}(x_1,x_n)\ \mathrm{Cov}(x_2, x_1) & \mathrm{Var}(x_2) & \dots & \mathrm{Cov}(x_2,x_n)\ \vdots & \vdots & \ddots & \vdots \ \mathrm{Cov}(x_n,x_1) & \mathrm{Cov}(x_n,x_2) & \dots & \mathrm{Var}(x_n)\ \end{pmatrix} \end{equation} $\boldsymbol{\Sigma}$ je simetrična $\boldsymbol{\Sigma}$ uvijek pozitivno semidefinitna $\Delta^2 = \mathbf{x}^{\mathrm{T}}\boldsymbol{\Sigma}\mathbf{x}\geq 0$ za Mahalanobisovu udaljenost vrijedi $\Delta\geq 0$ Ali, da bi PDF bila dobro definirana, $\boldsymbol{\Sigma}$ mora biti pozitivno definitna: $\Delta^2 = \mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}\mathbf{x} > 0$ za ne-nul vektor $\mathbf{x}$ $\boldsymbol{\Sigma}$ je pozitivno definitna $\Rightarrow$ $\boldsymbol{\Sigma}$ je nesingularna: $|\boldsymbol{\Sigma}|>0$ i postoji $\boldsymbol{\Sigma}^{-1}$ (obrat ne vrijedi!) Ako $\boldsymbol{\Sigma}$ nije pozitivno definitna, najčešći uzroci su $\mathrm{Var}(x_i)=0$ (beskorisna značajka) $\mathrm{Cov}(x_i,x_j)=1$ (redundantan par značajki) End of explanation """ plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1, cmap='gray_r') plt.contour(X, Y, likelihood_c2.pdf(XY) * p_c2, cmap='gray_r') plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1 - likelihood_c2.pdf(XY) * p_c2, levels=[0], colors='r', linewidths=2); """ Explanation: Granica između klasa $\mathcal{C}_1$ i $\mathcal{C}_2$ je: $$ h_1(\mathbf{x}) = h_2(\mathbf{x}) $$ tj. $$ h_1(\mathbf{x}) - h_2(\mathbf{x}) = 0 $$ End of explanation """ mu_1 = [-2, 1] mu_2 = [2, 0] covm_1 = sp.array([[1, 1], [1, 3]]) covm_2 = sp.array([[2, -0.5], [-0.5, 1]]) p_c1 = 0.4 p_c2 = 0.6 covm_shared = (p_c1 * covm_1 + p_c2 * covm_2) / 2 likelihood_c1 = stats.multivariate_normal(mu_1, covm_shared) likelihood_c2 = stats.multivariate_normal(mu_2, covm_shared) plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1, cmap='gray_r') plt.contour(X, Y, likelihood_c2.pdf(XY) * p_c2, cmap='gray_r') plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1 - likelihood_c2.pdf(XY) * p_c2, levels=[0], colors='r', linewidths=2); """ Explanation: Granca je nelinearna jer postoji član koji kvadratno ovisi o $\mathbf{x}$ (i taj član ne iščezava kada računamo razliku $h_1(x)-h_2(x)$): \begin{align} h_j(\mathbf{x}) &= \color{gray}{-\frac{n}{2}\ln 2\pi} - \frac{1}{2}\ln|\boldsymbol{\Sigma}_j| - \frac{1}{2}(\mathbf{x}-\boldsymbol{\mu}_j)^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}(\mathbf{x}-\mathbf{\mu}_j) + \ln P(\mathcal{C}_j)\ &\Rightarrow - \frac{1}{2}\ln|\boldsymbol{\Sigma}_j| - \frac{1}{2}\big(\color{red}{\mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}\mathbf{x}} -2\mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}\boldsymbol{\mu}_j +\boldsymbol{\mu}_j^\mathrm{T}\boldsymbol{\Sigma}_j^{-1}\boldsymbol{\mu}_j\big) + \ln P(\mathcal{C}_j) \end{align} Kvadratni model ima previše parametara: $\mathcal{O}(n^2)$ Pojednostavljenja $\Rightarrow$ dodatne induktivne pretpostavke? 1. pojednostavljenje: dijeljena kovarijacijska matrica $$ \hat{\boldsymbol{\Sigma}} = \sum_j \hat{P}(\mathcal{C}_j)\hat{\boldsymbol{\Sigma}}_j $$ \begin{align} h_j(\mathbf{x}) &= \color{gray}{- \frac{1}{2}\ln|\boldsymbol{\Sigma}|} - \frac{1}{2}(\color{gray}{\mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}^{-1}\mathbf{x}} -2\mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_j +\boldsymbol{\mu}_j^\mathrm{T}\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_j) + \ln P(\mathcal{C}_j)\ &\Rightarrow \mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_j -\frac{1}{2}\boldsymbol{\mu}_j^\mathrm{T}\boldsymbol{\Sigma}^{-1}\boldsymbol{\mu}_j + \ln P(\mathcal{C}_j) \end{align} Član $\mathbf{x}^\mathrm{T}\boldsymbol{\Sigma}^{-1}\mathbf{x}$ isti je za svaki $h_j$, pa iščezava kada računamo granicu između klasa Dakle, dobivamo linearan model! Broj parametara? End of explanation """ mu_1 = [-2, 1] mu_2 = [2, 0] p_c1 = 0.4 p_c2 = 0.6 covm_shared_diagonal = [[2,0],[0,1]] likelihood_c1 = stats.multivariate_normal(mu_1, covm_shared_diagonal) likelihood_c2 = stats.multivariate_normal(mu_2, covm_shared_diagonal) plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1, cmap='gray_r') plt.contour(X, Y, likelihood_c2.pdf(XY) * p_c2, cmap='gray_r') plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1 - likelihood_c2.pdf(XY) * p_c2, levels=[0], colors='r', linewidths=2); """ Explanation: 2. pojednostavljenje: dijagonalna kovarijacijska matrica $$ \boldsymbol{\Sigma} = \mathrm{diag}(\sigma_i^2) \quad \Rightarrow \quad |\boldsymbol{\Sigma}|=\prod_i\sigma_i,\quad \boldsymbol{\Sigma}^{-1}=\mathrm{diag}(1/\sigma_i^2) $$ Izglednost klase: \begin{align} p(\mathbf{x}|\mathcal{C}j) &= \frac{1}{(2\pi)^{n/2}|\boldsymbol{\Sigma}|^{1/2}} \exp\Big{-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu}_j)^\mathrm{T}\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu}_j)\Big}\ &= \frac{1}{(2\pi)^{n/2}\color{red}{\prod{i=1}^n\sigma_i}} \exp\Big{-\frac{1}{2}\sum_{i=1}^n\Big(\frac{x_i-\mu_{ij}}{\color{red}{\sigma_i}}\Big)^2\Big}\ &= \prod_{i=1}^n \frac{1}{\sqrt{2\pi}\sigma_i} \exp\Big{-\frac{1}{2}(\frac{x_i-\mu_{ij}}{\sigma_i}\Big)^2\Big} = \prod_{i=1}^n\mathcal{N}(\mu_{ij},\sigma_i^2) \end{align} Dobili smo umnožak univarijatnih Gaussovih distribucija NB: Ovo je naivan Bayesov klasifikator (za kontinuirane značajke)! $x_i\bot x_k|\mathcal{C}_j\ \Rightarrow\ \mathrm{Cov}(x_i|\mathcal{C}_j, x_k|\mathcal{C}_j)=0$ $p(x|\mathcal{C}_j) = \prod_i p(x_i|\mathcal{C}_j)$ Model: \begin{align} h_j(\mathbf{x}) &= \ln p(\mathbf{x}|\mathcal{C}j) + \ln P(\mathcal{C}_j)\ &\Rightarrow -\frac{1}{2}\sum{i=1}^n\Big(\frac{x_i-\mu_{ij}}{\sigma_i}\Big)^2 + \ln \Pr{\mathcal{C}_j} \end{align} NB: Računamo normirane euklidske udaljenosti (normirane sa $\sigma_i$) Q: Broj parametara? End of explanation """ mu_1 = [-2, 1] mu_2 = [2, 0] p_c1 = 0.4 p_c2 = 0.6 covm_shared_diagonal = [[1,0],[0,1]] likelihood_c1 = stats.multivariate_normal(mu_1, covm_shared_diagonal) likelihood_c2 = stats.multivariate_normal(mu_2, covm_shared_diagonal) plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1, cmap='gray_r') plt.contour(X, Y, likelihood_c2.pdf(XY) * p_c2, cmap='gray_r') plt.contour(X, Y, likelihood_c1.pdf(XY) * p_c1 - likelihood_c2.pdf(XY) * p_c2, levels=[0], colors='r', linewidths=2); """ Explanation: 3. pojednostavljenje: izotropna kovarijacijska matrica $$ \boldsymbol{\Sigma}=\sigma^2\mathbf{I} $$ \begin{equation} h_j(\mathbf{x}) = -\frac{1}{2\sigma^2}\sum_{i=1}^n(x_i-\mu_{ij})^2 + \ln P(\mathcal{C}_j) \end{equation} Broj parametara? End of explanation """
GoogleCloudPlatform/training-data-analyst
courses/machine_learning/deepdive/03_tensorflow/c_dataset.ipynb
apache-2.0
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst # Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.5 from google.cloud import bigquery import tensorflow as tf import numpy as np import shutil print(tf.__version__) """ Explanation: <h1> 2c. Loading large datasets progressively with the tf.data.Dataset </h1> In this notebook, we continue reading the same small dataset, but refactor our ML pipeline in two small, but significant, ways: Refactor the input to read data from disk progressively. Refactor the feature creation so that it is not one-to-one with inputs. The Pandas function in the previous notebook first read the whole data into memory -- on a large dataset, this won't be an option. End of explanation """ CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key'] DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']] def read_dataset(filename, mode, batch_size = 512): def decode_csv(row): columns = tf.compat.v1.decode_csv(row, record_defaults = DEFAULTS) features = dict(zip(CSV_COLUMNS, columns)) features.pop('key') # discard, not a real feature label = features.pop('fare_amount') # remove label from features and store return features, label # Create list of file names that match "glob" pattern (i.e. data_file_*.csv) filenames_dataset = tf.data.Dataset.list_files(filename, shuffle=False) # Read lines from text files textlines_dataset = filenames_dataset.flat_map(tf.data.TextLineDataset) # Parse text lines as comma-separated values (CSV) dataset = textlines_dataset.map(decode_csv) # Note: # use tf.data.Dataset.flat_map to apply one to many transformations (here: filename -> text lines) # use tf.data.Dataset.map to apply one to one transformations (here: text line -> feature list) if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # loop indefinitely dataset = dataset.shuffle(buffer_size = 10 * batch_size, seed=2) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) return dataset def get_train_input_fn(): return read_dataset('./taxi-train.csv', mode = tf.estimator.ModeKeys.TRAIN) def get_valid_input_fn(): return read_dataset('./taxi-valid.csv', mode = tf.estimator.ModeKeys.EVAL) """ Explanation: <h2> 1. Refactor the input </h2> Read data created in Lab1a, but this time make it more general, so that we can later handle large datasets. We use the Dataset API for this. It ensures that, as data gets delivered to the model in mini-batches, it is loaded from disk only when needed. End of explanation """ INPUT_COLUMNS = [ tf.feature_column.numeric_column('pickuplon'), tf.feature_column.numeric_column('pickuplat'), tf.feature_column.numeric_column('dropofflat'), tf.feature_column.numeric_column('dropofflon'), tf.feature_column.numeric_column('passengers'), ] def add_more_features(feats): # Nothing to add (yet!) return feats feature_cols = add_more_features(INPUT_COLUMNS) """ Explanation: <h2> 2. Refactor the way features are created. </h2> For now, pass these through (same as previous lab). However, refactoring this way will enable us to break the one-to-one relationship between inputs and features. End of explanation """ tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) OUTDIR = 'taxi_trained' shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time model = tf.compat.v1.estimator.LinearRegressor( feature_columns = feature_cols, model_dir = OUTDIR) model.train(input_fn = get_train_input_fn, steps = 200) """ Explanation: <h2> Create and train the model </h2> Note that we train for num_steps * batch_size examples. End of explanation """ metrics = model.evaluate(input_fn = get_valid_input_fn, steps = None) print('RMSE on dataset = {}'.format(np.sqrt(metrics['average_loss']))) """ Explanation: <h3> Evaluate model </h3> As before, evaluate on the validation data. We'll do the third refactoring (to move the evaluation into the training loop) in the next lab. End of explanation """
mne-tools/mne-tools.github.io
0.23/_downloads/1537c1215a3e40187a4513e0b5f1d03d/eeg_csd.ipynb
bsd-3-clause
# Authors: Alex Rockhill <aprockhill@mailbox.org> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() """ Explanation: Transform EEG data using current source density (CSD) This script shows an example of how to use CSD :footcite:PerrinEtAl1987,PerrinEtAl1989,Cohen2014,KayserTenke2015. CSD takes the spatial Laplacian of the sensor signal (derivative in both x and y). It does what a planar gradiometer does in MEG. Computing these spatial derivatives reduces point spread. CSD transformed data have a sharper or more distinct topography, reducing the negative impact of volume conduction. End of explanation """ raw = mne.io.read_raw_fif(data_path + '/MEG/sample/sample_audvis_raw.fif') raw = raw.pick_types(meg=False, eeg=True, eog=True, ecg=True, stim=True, exclude=raw.info['bads']).load_data() events = mne.find_events(raw) raw.set_eeg_reference(projection=True).apply_proj() """ Explanation: Load sample subject data End of explanation """ raw_csd = mne.preprocessing.compute_current_source_density(raw) raw.plot() raw_csd.plot() """ Explanation: Plot the raw data and CSD-transformed raw data: End of explanation """ raw.plot_psd() raw_csd.plot_psd() """ Explanation: Also look at the power spectral densities: End of explanation """ event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3, 'visual/right': 4, 'smiley': 5, 'button': 32} epochs = mne.Epochs(raw, events, event_id=event_id, tmin=-0.2, tmax=.5, preload=True) evoked = epochs['auditory'].average() """ Explanation: CSD can also be computed on Evoked (averaged) data. Here we epoch and average the data so we can demonstrate that. End of explanation """ times = np.array([-0.1, 0., 0.05, 0.1, 0.15]) evoked_csd = mne.preprocessing.compute_current_source_density(evoked) evoked.plot_joint(title='Average Reference', show=False) evoked_csd.plot_joint(title='Current Source Density') """ Explanation: First let's look at how CSD affects scalp topography: End of explanation """ fig, ax = plt.subplots(4, 4) fig.subplots_adjust(hspace=0.5) fig.set_size_inches(10, 10) for i, lambda2 in enumerate([0, 1e-7, 1e-5, 1e-3]): for j, m in enumerate([5, 4, 3, 2]): this_evoked_csd = mne.preprocessing.compute_current_source_density( evoked, stiffness=m, lambda2=lambda2) this_evoked_csd.plot_topomap( 0.1, axes=ax[i, j], outlines='skirt', contours=4, time_unit='s', colorbar=False, show=False) ax[i, j].set_title('stiffness=%i\nλ²=%s' % (m, lambda2)) """ Explanation: CSD has parameters stiffness and lambda2 affecting smoothing and spline flexibility, respectively. Let's see how they affect the solution: End of explanation """
StevenPeutz/myDataProjects
SQL/SQLquerySizeCalculator.ipynb
cc0-1.0
# import the python helper package for bigqueey (thank you Rachael Tatman e.a.) import bq_helper # create the helper object open_aq = bq_helper.BigQueryHelper(active_project="bigquery-public-data", dataset_name="openaq") #print the tables in the dataset to check everthing went ok so far open_aq.list_tables() # print the first couple of rows to look at the structure of the dataset # not this is somewhat different from the usual way with dataframes; datafram_name.head(number_of_rows_to_show) ... # you can still only show e.g. 3 rows by tpying: open_aq.head("global_air_quality", num_rows=3) open_aq.head("global_air_quality") """ Explanation: Kaggle works great with Google Big Query. Especially when using the 'bq_helper' package (python). <br> // Credits and a big thanks to Rachael Tatman e.a. <br> However, there is a caveat. There is a 5TB query limit. This refers to the scanning of the dataset not the size of the 'response'. This kernel uses the openAQ dataset and the bq_helper package (python) to demonstrate how to see the 'scan' size of your SQL query before actually sending it. End of explanation """ query = """SELECT value FROM `bigquery-public-data.openaq.global_air_quality` WHERE value > 0""" # ! the quotations marks around 'bigquery..._quality' are NOT quotation marks, they are and have to be 'backticks': ` ! open_aq.estimate_query_size(query) """ Explanation: Measuring SQL bigquery size before acrtually executing it with the bq_helper package; End of explanation """ query2 = """SELECT value FROM `bigquery-public-data.openaq.global_air_quality` WHERE country = 'NL'""" # ! the quotations marks around 'bigquery..._quality' are NOT quotation marks, they are and have to be 'backticks': ` ! open_aq.estimate_query_size(query2) """ Explanation: this means the SQL query above would take 0.000124 TB to run. End of explanation """ #or in megabyte; open_aq.estimate_query_size(query2) * 1000 """ Explanation: and this one would cost 0.000186TB End of explanation """
turbomanage/training-data-analyst
courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/3_keras_sequential_api.ipynb
apache-2.0
# Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.0 || pip install tensorflow==2.0 """ Explanation: Introducing the Keras Sequential API Learning Objectives 1. Build a DNN model using the Keras Sequential API 1. Learn how to use feature columns in a Keras model 1. Learn how to train a model with Keras 1. Learn how to save/load, and deploy a Keras model on GCP 1. Learn how to deploy and make predictions with at Keras model Introduction The Keras sequential API allows you to create Tensorflow models layer-by-layer. This is useful for building most kinds of machine learning models but it does not allow you to create models that share layers, re-use layers or have multiple inputs or outputs. In this lab, we'll see how to build a simple deep neural network model using the keras sequential api and feature columns. Once we have trained our model, we will deploy it using AI Platform and see how to call our model for online prediciton. End of explanation """ import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt from tensorflow import keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, DenseFeatures from tensorflow.keras.callbacks import TensorBoard print(tf.__version__) %matplotlib inline """ Explanation: Start by importing the necessary libraries for this lab. End of explanation """ !ls -l ../data/*.csv !head ../data/taxi*.csv """ Explanation: Load raw data We will use the taxifare dataset, using the CSV files that we created in the first notebook of this sequence. Those files have been saved into ../data. End of explanation """ CSV_COLUMNS = [ 'fare_amount', 'pickup_datetime', 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', 'key' ] LABEL_COLUMN = 'fare_amount' DEFAULTS = [[0.0], ['na'], [0.0], [0.0], [0.0], [0.0], [0.0], ['na']] UNWANTED_COLS = ['pickup_datetime', 'key'] def features_and_labels(row_data): label = row_data.pop(LABEL_COLUMN) features = row_data for unwanted_col in UNWANTED_COLS: features.pop(unwanted_col) return features, label def create_dataset(pattern, batch_size=1, mode=tf.estimator.ModeKeys.EVAL): dataset = tf.data.experimental.make_csv_dataset( pattern, batch_size, CSV_COLUMNS, DEFAULTS) dataset = dataset.map(features_and_labels) if mode == tf.estimator.ModeKeys.TRAIN: dataset = dataset.shuffle(buffer_size=1000).repeat() # take advantage of multi-threading; 1=AUTOTUNE dataset = dataset.prefetch(1) return dataset """ Explanation: Use tf.data to read the CSV files We wrote these functions for reading data from the csv files above in the previous notebook. End of explanation """ INPUT_COLS = [ 'pickup_longitude', 'pickup_latitude', 'dropoff_longitude', 'dropoff_latitude', 'passenger_count', ] # Create input layer of feature columns # TODO 2 feature_columns = { colname: tf.feature_column.numeric_column(colname) for colname in INPUT_COLS } """ Explanation: Build a simple keras DNN model We will use feature columns to connect our raw data to our keras DNN model. Feature columns make it easy to perform common types of feature engineering on your raw data. For example, you can one-hot encode categorical data, create feature crosses, embeddings and more. We'll cover these in more detail later in the course, but if you want to a sneak peak browse the official TensorFlow feature columns guide. In our case we won't do any feature engineering. However, we still need to create a list of feature columns to specify the numeric values which will be passed on to our model. To do this, we use tf.feature_column.numeric_column() We use a python dictionary comprehension to create the feature columns for our model, which is just an elegant alternative to a for loop. End of explanation """ # Build a keras DNN model using Sequential API # TODO 1 model = Sequential([ DenseFeatures(feature_columns=feature_columns.values()), Dense(units=32, activation="relu", name="h1"), Dense(units=8, activation="relu", name="h2"), Dense(units=1, activation="linear", name="output") ]) """ Explanation: Next, we create the DNN model. The Sequential model is a linear stack of layers and when building a model using the Sequential API, you configure each layer of the model in turn. Once all the layers have been added, you compile the model. End of explanation """ # Create a custom evalution metric def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) # Compile the keras model model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"]) """ Explanation: Next, to prepare the model for training, you must configure the learning process. This is done using the compile method. The compile method takes three arguments: An optimizer. This could be the string identifier of an existing optimizer (such as rmsprop or adagrad), or an instance of the Optimizer class. A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function from the Losses class (such as categorical_crossentropy or mse), or it can be a custom objective function. A list of metrics. For any machine learning problem you will want a set of metrics to evaluate your model. A metric could be the string identifier of an existing metric or a custom metric function. We will add an additional custom metric called rmse to our list of metrics which will return the root mean square error. End of explanation """ TRAIN_BATCH_SIZE = 1000 NUM_TRAIN_EXAMPLES = 10000 * 5 # training dataset will repeat, wrap around NUM_EVALS = 50 # how many times to evaluate NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample trainds = create_dataset( pattern='../data/taxi-train*', batch_size=TRAIN_BATCH_SIZE, mode=tf.estimator.ModeKeys.TRAIN) evalds = create_dataset( pattern='../data/taxi-valid*', batch_size=1000, mode=tf.estimator.ModeKeys.EVAL).take(NUM_EVAL_EXAMPLES//1000) """ Explanation: Train the model To train your model, Keras provides three functions that can be used: 1. .fit() for training a model for a fixed number of epochs (iterations on a dataset). 2. .fit_generator() for training a model on data yielded batch-by-batch by a generator 3. .train_on_batch() runs a single gradient update on a single batch of data. The .fit() function works well for small datasets which can fit entirely in memory. However, for large datasets (or if you need to manipulate the training data on the fly via data augmentation, etc) you will need to use .fit_generator() instead. The .train_on_batch() method is for more fine-grained control over training and accepts only a single batch of data. The taxifare dataset we sampled is small enough to fit in memory, so can we could use .fit to train our model. Our create_dataset function above generates batches of training examples, so we could also use .fit_generator. In fact, when calling .fit the method inspects the data, and if it's a generator (as our dataset is) it will invoke automatically .fit_generator for training. We start by setting up some parameters for our training job and create the data generators for the training and validation data. We refer you the the blog post ML Design Pattern #3: Virtual Epochs for further details on why express the training in terms of NUM_TRAIN_EXAMPLES and NUM_EVALS and why, in this training code, the number of epochs is really equal to the number of evaluations we perform. End of explanation """ %time # TODO 3 steps_per_epoch = NUM_TRAIN_EXAMPLES // (TRAIN_BATCH_SIZE * NUM_EVALS) LOGDIR = "./taxi_trained" history = model.fit(x=trainds, steps_per_epoch=steps_per_epoch, epochs=NUM_EVALS, validation_data=evalds, callbacks=[TensorBoard(LOGDIR)]) """ Explanation: There are various arguments you can set when calling the .fit method. Here x specifies the input data which in our case is a tf.data dataset returning a tuple of (inputs, targets). The steps_per_epoch parameter is used to mark the end of training for a single epoch. Here we are training for NUM_EVALS epochs. Lastly, for the callback argument we specify a Tensorboard callback so we can inspect Tensorboard after training. End of explanation """ model.summary() """ Explanation: High-level model evaluation Once we've run data through the model, we can call .summary() on the model to get a high-level summary of our network. We can also plot the training and evaluation curves for the metrics we computed above. End of explanation """ RMSE_COLS = ['rmse', 'val_rmse'] pd.DataFrame(history.history)[RMSE_COLS].plot() LOSS_COLS = ['loss', 'val_loss'] pd.DataFrame(history.history)[LOSS_COLS].plot() """ Explanation: Running .fit (or .fit_generator) returns a History object which collects all the events recorded during training. Similar to Tensorboard, we can plot the training and validation curves for the model loss and rmse by accessing these elements of the History object. End of explanation """ model.predict(x={"pickup_longitude": tf.convert_to_tensor([-73.982683]), "pickup_latitude": tf.convert_to_tensor([40.742104]), "dropoff_longitude": tf.convert_to_tensor([-73.983766]), "dropoff_latitude": tf.convert_to_tensor([40.755174]), "passenger_count": tf.convert_to_tensor([3.0])}, steps=1) """ Explanation: Making predictions with our model To make predictions with our trained model, we can call the predict method, passing to it a dictionary of values. The steps parameter determines the total number of steps before declaring the prediction round finished. Here since we have just one example, we set steps=1 (setting steps=None would also work). Note, however, that if x is a tf.data dataset or a dataset iterator, and steps is set to None, predict will run until the input dataset is exhausted. End of explanation """ # TODO 4 OUTPUT_DIR = "./export/savedmodel" shutil.rmtree(OUTPUT_DIR, ignore_errors=True) EXPORT_PATH = os.path.join(OUTPUT_DIR, datetime.datetime.now().strftime("%Y%m%d%H%M%S")) tf.saved_model.save(model, EXPORT_PATH) # with default serving function !saved_model_cli show \ --tag_set serve \ --signature_def serving_default \ --dir {EXPORT_PATH} !find {EXPORT_PATH} os.environ['EXPORT_PATH'] = EXPORT_PATH """ Explanation: Export and deploy our model Of course, making individual predictions is not realistic, because we can't expect client code to have a model object in memory. For others to use our trained model, we'll have to export our model to a file, and expect client code to instantiate the model from that exported file. We'll export the model to a TensorFlow SavedModel format. Once we have a model in this format, we have lots of ways to "serve" the model, from a web application, from JavaScript, from mobile applications, etc. End of explanation """ %%bash # TODO 5 PROJECT= # TODO: Change this to your PROJECT BUCKET=${PROJECT} REGION=us-east1 MODEL_NAME=taxifare VERSION_NAME=dnn if [[ $(gcloud ai-platform models list --format='value(name)' | grep $MODEL_NAME) ]]; then echo "$MODEL_NAME already exists" else echo "Creating $MODEL_NAME" gcloud ai-platform models create --regions=$REGION $MODEL_NAME fi if [[ $(gcloud ai-platform versions list --model $MODEL_NAME --format='value(name)' | grep $VERSION_NAME) ]]; then echo "Deleting already existing $MODEL_NAME:$VERSION_NAME ... " echo yes | gcloud ai-platform versions delete --model=$MODEL_NAME $VERSION_NAME echo "Please run this cell again if you don't see a Creating message ... " sleep 2 fi echo "Creating $MODEL_NAME:$VERSION_NAME" gcloud ai-platform versions create --model=$MODEL_NAME $VERSION_NAME \ --framework=tensorflow --python-version=3.5 --runtime-version=1.14 \ --origin=$EXPORT_PATH --staging-bucket=gs://$BUCKET %%writefile input.json {"pickup_longitude": -73.982683, "pickup_latitude": 40.742104,"dropoff_longitude": -73.983766,"dropoff_latitude": 40.755174,"passenger_count": 3.0} # TODO 5 !gcloud ai-platform predict --model taxifare --json-instances input.json --version dnn """ Explanation: Deploy our model to AI Platform Finally, we will deploy our trained model to AI Platform and see how we can make online predicitons. End of explanation """
GoogleCloudPlatform/training-data-analyst
courses/ai-for-finance/solution/intro_tf_data_keras_sequential_solution.ipynb
apache-2.0
# Ensure the right version of Tensorflow is installed. !pip freeze | grep tensorflow==2.1 || pip install tensorflow==2.1 from __future__ import absolute_import, division, print_function, unicode_literals import pathlib import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) """ Explanation: Training a classification model for wine production quality Objective: In this lab, you will use the Keras Sequential API to create a classification model. You will learn how to use the tf.data API for creating input pipelines and use feature columns to prepare the data to be consumed by a neural network. Lab Scope: This lab does not cover how to make predictions on the model or deploy it to Cloud AI Platform. Learning objectives: Apply techniques to clean and inspect data. Split dataset into training, validation and test datasets. Use the tf.data.Dataset to create an input pipeline. Use feature columns to prepare the data to be tained by a neural network. Define, compile and train a model using the Keras Sequential API. In a classification problem, we aim to select the output from a limited set of discrete values, like a category or a class. Contrast this with a regression problem, where we aim to predict a value from a continuos range of values. This notebook uses the Wine Production Quality Dataset and builds a model to predict the production quality of wine given a set of attributes such as its citric acidity, density, and others. To do this, we'll provide the model with examples of different wines produced, that received a rating from an evaluator. The ratings are provided by the numbers 0 - 10 (0 being of very poor quality and 10 being of great quality). We will then try and use this model to predict the rate a new wine will receive by infering towards the trained model. Since we are learning how to use the Tensorflow 2.x API, this example uses the tf.keras API. Please see this guide for details. End of explanation """ dataset_path = "gs://cloud-training-demos/wine_quality/winequality-white.csv" """ Explanation: The Wine Quality Dataset The dataset is available in the UCI Machine Learning Repository. Get the data There is a copy of the White Wine dataset available on Google Cloud Storage (GCS). The cell below shows the location of the CSV file. End of explanation """ column_names = ['fixed_acidity','volatile_acidity','citric_acid','residual_sugar', 'chlorides','free_sulfur_dioxide','total_sulfur_dioxide','density', 'pH','sulphates','alcohol','quality'] raw_dataframe = pd.read_csv(dataset_path, names=column_names, header = 0, na_values = " ", comment='\t', sep=";", skipinitialspace=True) raw_dataframe = raw_dataframe.astype(float) raw_dataframe['quality'] = raw_dataframe['quality'].astype(int) dataframe= raw_dataframe.copy() """ Explanation: To visualize and manipulate the data, we will use pandas. First step is to import the data. We should list the columns that will be used to train our model. These column names will define what data will compose the dataframe object in pandas. End of explanation """ dataframe.isna().sum() """ Explanation: Clean the data Datasets sometimes can have null values. Running the next cell counts how many null values exist on each one of the columns. Note: There are many other steps to make sure the data is clean, but this is out of the scope of this exercise. End of explanation """ dataframe.tail() data_stats = dataframe.describe() data_stats = data_stats.transpose() data_stats """ Explanation: We can see that, on this dataset, there are no null values. If there were any, we could run dataframe = dataframe.dropna() to drop them and make this tutorial simpler. Inspect the data Let's take a look at the dataframe content. The tail() method, when ran on a dataframe, shows the last n roles (n is 5 by default). End of explanation """ import seaborn as sns sns.pairplot(dataframe[["quality", "citric_acid", "residual_sugar", "alcohol"]], diag_kind="kde") """ Explanation: Have a quick look at the joint distribution of a few pairs of columns from the training set: End of explanation """ from sklearn.model_selection import train_test_split train, test = train_test_split(dataframe, test_size=0.2) train, val = train_test_split(train, test_size=0.2) print(len(train), 'train examples') print(len(val), 'validation examples') print(len(test), 'test examples') """ Explanation: --- Some considerations --- Did you notice anything when looking at the stats table? One useful piece of information we can get from those are, for example, min and max values. This allows us to understand ranges in which these features fall in. Based on the description of the dataset and the task we are trying to achieve, do you see any issues with the examples we have available to train on? Did you notice that the ratings on the dataset range from 3 to 9? In this dataset, there is no wine rated with a 10 or a 0 - 2 rating. This will likely produce a poor model that is not able to generalize well to examples of fantastic tasting wine (nor to the ones that taste pretty bad!). One way to fix this is to make sure your dataset represents all possible classes well. Another analysis, that we do not do on this exercise, is check if the data is balanced. Having a balanced dataset produces fair model, and that is always a good thing! Split the data into train, validation and test Now split the dataset into a training, validation, and test set. Test sets are used for a final evaluation of the trained model. There are more sophisticated ways to make sure that your splitting methods are repeatable. Ideally, the sets would always be the same after splitting to avoid randomic results, which makes experimentation difficult. End of explanation """ def df_to_dataset(dataframe, epochs=10, shuffle=True, batch_size=64): dataframe = dataframe.copy() labels = tf.keras.utils.to_categorical(dataframe.pop('quality'), num_classes=11) #extracting the column which contains the training label ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(dataframe)) ds = ds.repeat(epochs).batch(batch_size) return ds """ Explanation: Use the tf.data.Dataset The tf.data.Dataset allows for writing descriptive and efficient input pipelines. Dataset usage follows a common pattern: Create a source dataset from your input data. Apply dataset transformations to preprocess the data. Iterate over the dataset and process the elements. Iteration happens in a streaming fashion, so the full dataset does not need to fit into memory. The df_to_dataset method below creates a dataset object from a pandas dataframe. End of explanation """ train_ds = df_to_dataset(train) val_ds = df_to_dataset(val, shuffle=False) test_ds = df_to_dataset(test, shuffle=False) """ Explanation: Next step is to create batches from train, validation and test datasets that we split earlier. Let's use a batch size of 5 for demonstration purposes. End of explanation """ for feature_batch, label_batch in train_ds.take(1): print('Every feature:', list(feature_batch.keys())) print('A batch of citric acid:', feature_batch['citric_acid']) print('A batch of quality:', label_batch ) """ Explanation: Let's look at one batch of the data. The example below prints the content of a batch (column names, elements from the citric_acid column and elements from the quality label. End of explanation """ from tensorflow import feature_column feature_columns = [] fixed_acidity = tf.feature_column.numeric_column('fixed_acidity') bucketized_fixed_acidity = tf.feature_column.bucketized_column( fixed_acidity, boundaries=[3., 5., 7., 9., 11., 13., 14.]) feature_columns.append(bucketized_fixed_acidity) volatile_acidity = tf.feature_column.numeric_column('volatile_acidity') bucketized_volatile_acidity = tf.feature_column.bucketized_column( volatile_acidity, boundaries=[0., 0.2, 0.4, 0.6, 0.8, 1.]) feature_columns.append(bucketized_volatile_acidity) citric_acid = tf.feature_column.numeric_column('citric_acid') bucketized_citric_acid = tf.feature_column.bucketized_column( citric_acid, boundaries=[0., 0.4, 0.7, 1.0, 1.3, 1.8]) feature_columns.append(bucketized_citric_acid) residual_sugar = tf.feature_column.numeric_column('residual_sugar') bucketized_residual_sugar = tf.feature_column.bucketized_column( residual_sugar, boundaries=[0.6, 10., 20., 30., 40., 50., 60., 70.]) feature_columns.append(bucketized_residual_sugar) chlorides = tf.feature_column.numeric_column('chlorides') bucketized_chlorides = tf.feature_column.bucketized_column( chlorides, boundaries=[0., 0.1, 0.2, 0.3, 0.4]) feature_columns.append(bucketized_chlorides) free_sulfur_dioxide = tf.feature_column.numeric_column('free_sulfur_dioxide') bucketized_free_sulfur_dioxide = tf.feature_column.bucketized_column( free_sulfur_dioxide, boundaries=[1., 50., 100., 150., 200., 250., 300.]) feature_columns.append(bucketized_free_sulfur_dioxide) total_sulfur_dioxide = tf.feature_column.numeric_column('total_sulfur_dioxide') bucketized_total_sulfur_dioxide = tf.feature_column.bucketized_column( total_sulfur_dioxide, boundaries=[9., 100., 200., 300., 400., 500.]) feature_columns.append(bucketized_total_sulfur_dioxide) density = tf.feature_column.numeric_column('density') bucketized_density = tf.feature_column.bucketized_column( density, boundaries=[0.9, 1.0, 1.1]) feature_columns.append(bucketized_density) pH = tf.feature_column.numeric_column('pH') bucketized_pH = tf.feature_column.bucketized_column( pH, boundaries=[2., 3., 4.]) feature_columns.append(bucketized_pH) sulphates = tf.feature_column.numeric_column('sulphates') bucketized_sulphates = tf.feature_column.bucketized_column( sulphates, boundaries=[0.2, 0.4, 0.7, 1.0, 1.1]) feature_columns.append(bucketized_sulphates) alcohol = tf.feature_column.numeric_column('alcohol') bucketized_alcohol = tf.feature_column.bucketized_column( alcohol, boundaries=[8., 9., 10., 11., 12., 13., 14.]) feature_columns.append(bucketized_alcohol) feature_columns # Create a feature layer from the feature columns feature_layer = tf.keras.layers.DenseFeatures(feature_columns) """ Explanation: Create feature columns TensorFlow provides many types of feature columns. In this exercise, all the feature columns are of type numeric. If there were any text or categorical values, transformations would need to take place to make the input all numeric. However, you often don't want to feed a number directly into the model, but instead split its value into different categories based on numerical ranges. To do this, use the bucketized_column method of feature columns. This allows for the network to represent discretized dense input bucketed by boundaries. Feature columns are the object type used to create feature layers, which we will feed to the Keras model. End of explanation """ model = tf.keras.Sequential([ feature_layer, layers.Dense(8, activation='relu'), layers.Dense(8, activation='relu'), layers.Dense(11, activation='softmax') ]) model.compile(optimizer='adam', loss=tf.keras.losses.CategoricalCrossentropy(from_logits=False), metrics=['accuracy']) model.fit(train_ds, validation_data=val_ds, epochs=5) """ Explanation: Define, compile and train the Keras model We will be using the Keras Sequential API to create the logistic regression model for the classification of the wine quality. The model will be composed of the input layer (feature_layer created above), a single dense layer with two neural nodes, and the output layer, which will allow the model to predict the rating (1 - 10) of each instance being inferred. When compiling the model, we define a loss function, an optimizer and which metrics to use to evaluate the model. CategoricalCrossentropy is a type of loss used in classification tasks. Losses are a mathematical way of measuring how wrong the model predictions are. Optimizers tie together the loss function and model parameters by updating the model in response to the output of the loss function. In simpler terms, optimizers shape and mold your model into its most accurate possible form by playing with the weights. The loss function is the guide to the terrain, telling the optimizer when it’s moving in the right or wrong direction. We will use Adam as our optimizer for this exercise. Adam is an optimization algorithm that can be used instead of the classical stochastic gradient descent procedure to update network weights iterative based in training data. There are many types of optimizers one can chose from. Ideally, when creating an ML model, try and identify an optimizer that has been empirically adopted on similar tasks. End of explanation """
DOV-Vlaanderen/pydov
docs/notebooks/search_quartaire_stratigrafie.ipynb
mit
%matplotlib inline import os, sys import inspect # check pydov path import pydov """ Explanation: Example of DOV search methods for quartaire stratigrafie Use cases: Select records in a bbox Select records in a bbox with selected properties Select records within a distance from a point Select records in a municipality Get records using info from wfs fields, not available in the standard output dataframe End of explanation """ from pydov.search.interpretaties import QuartairStratigrafieSearch # information about the QuartairStratigrafie type (In Dutch): ip_quart = QuartairStratigrafieSearch() ip_quart.get_description() # information about the available fields for a QuartairStratigrafie object fields = ip_quart.get_fields() # print available fields for f in fields.values(): print(f['name']) # print information for a certain field fields['Type_proef'] """ Explanation: Get information about code base End of explanation """ from pydov.util.location import Within, Box # Get all interpretations in a bounding box (llx, lly, ulx, uly) # the pkey_boring link is not available below, but is in the df df = ip_quart.search(location=Within(Box(132815, 191700, 133815, 192700))) df.head() """ Explanation: The cost is an arbitrary attribute to indicate if the information is retrieved from a wfs query (cost = 1), or from an xml (cost = 10) Try-out of use cases Select interpretations in a bbox End of explanation """ # list available query methods methods = [i for i,j in inspect.getmembers(sys.modules['owslib.fes'], inspect.isclass) if 'Property' in i] methods from owslib.fes import PropertyIsGreaterThanOrEqualTo """ Explanation: Select interpretations in a bbox with selected properties End of explanation """ # Get deep boreholes in a bounding box from owslib.fes import PropertyIsLike # the propertyname can be any of the fields of the interpretations object that belong to the wfs source # the literal is always a string, no matter what its definition is in the boring object (string, float...) query = PropertyIsLike( propertyname='betrouwbaarheid_interpretatie', literal='onbekend') df = ip_quart.search(location=Within(Box(132815, 191700, 133815, 192700)), query=query ) df.head() """ Explanation: The property feature methodes listed above are available from the owslib module. These were not adapted for use in pydov. End of explanation """ from pydov.util.location import Point, WithinDistance # Get all interpretations within a defined distance from a point location = WithinDistance(location=Point(133000, 192000), distance=1000, distance_unit='meter') df = ip_quart.search(location=location) df.head() """ Explanation: Select records within a distance from a point End of explanation """ from owslib.fes import PropertyIsEqualTo query = PropertyIsEqualTo(propertyname='gemeente', literal='Hamme') df = ip_quart.search(query=query) df.head() """ Explanation: Select interpretations in a municipality End of explanation """ # import the necessary modules (not included in the requirements of pydov!) import folium from folium.plugins import MarkerCluster from pyproj import Transformer # for windows 10 users, we could not get it working with Microsoft Edge # change the browser to Chrome in the Notebook config file instead # convert the coordinates to lat/lon for folium def convert_latlon(x1, y1): transformer = Transformer.from_crs("epsg:31370", "epsg:4326", always_xy=True) x2,y2 = transformer.transform(x1, y1) return x2, y2 df['lon'], df['lat'] = zip(*map(convert_latlon, df['x'], df['y'])) # convert to list loclist = df[['lat', 'lon']].values.tolist() # initialize the Folium map on the centre of the selected locations, play with the zoom until ok fmap = folium.Map(location=[df['lat'].mean(), df['lon'].mean()], zoom_start=12) marker_cluster = MarkerCluster().add_to(fmap) for loc in range(0, len(loclist)): folium.Marker(loclist[loc], popup=df['lid1'][loc]).add_to(marker_cluster) fmap """ Explanation: Visualize results Using Folium, we can display the results of our search on a map. End of explanation """
MSeeker/Notebook-Collections
Monte Carlo Simulation of the Ising Model.ipynb
mit
def dice_samples(trials): prob = {1: 1/2, 2: 1/4, 3: 1/8, 4: 1/16, 5: 1/32, 6: 1/32} samples = np.zeros(trials + 1, dtype=int) samples[0] = 1 for i in range(trials): a = samples[i] b = np.random.random_integers(1, 6) # uniform a priori distribution pa = prob[a] pb = prob[b] if pb >= pa or np.random.rand() < pb / pa: samples[i + 1] = b else: samples[i + 1] = a return samples def summarize(samples): ''' Return the percentage of every face in the samples ''' num_samples = len(samples) distribution = {i: (samples == i).sum() * 100 / num_samples for i in [1, 2, 3, 4, 5 ,6]} # 百分数 return distribution """ Explanation: 1. Review of the Ising Model $N$ particles/molecules/magnetic dipoles with $\sigma = \pm 1$ "Nearest neighbor" interaction Hamiltonian $$ E=-J\sum_{ [i,j] }\sigma_i\sigma_j-H\sum_i\sigma_i \quad (1)$$ where $[i, j]$ denotes summation over nearest-neighbor pairs -- topology dependent! 1D Ising Model No phase transition above 0K (Ising) 2D Ising Model (aka square-lattice Ising model) at $H=0$ Analytic solution by Onsager: Transition temperature: $$ T_C = \frac{1}{k_B}\frac{2J}{\ln(1+\sqrt{2})} \approx 2.269\frac{J}{k_B} \quad (2)$$ Spontaneous magnization: $$ |\bar{\sigma}| = \Big{ \begin{array} ((1 - \sinh^{-4}(\frac{2J}{k_B T}))^{1/8} & (T < T_C) \ 0 & (T \geq T_C) \end{array} \quad (3) $$ Due to its simplicity and interesting analytic behavior, the 2D Ising Model is frequently used as a "testing stone" for Molecular Dynamics/Monte Carlo algorithms We will only consider the case of $H=0$ in this notebook 2. Monte Carlo Simulation 2.1 Importance sampling The total number of microstates, $\Omega$, approaches astronomical magnitudes even for a small system with $N \sim 10^4$ However, when $N$ is sufficiently large most of the microstates have extremely low probability compared to those in the vincinity of the most probable states. Metropolis (pioneer of the MC methods): ...instead of choosing configurations randomly, then weighting them with $\exp(-E/k_BT)$, we choose configurations with a probability $\exp(-E/k_BT)$ and weight them evenly.[1] This is called importance sampling. How samples are gathered: Molecular dynamics simulation (MD): start from first principles and simulate the time evolution of the system. For thermodynamic systems at equilibrium, points along any phase trajectories should be a good representation of the ensemble (ergodicity) Monte Carlo simulation (MC): Carry out a hypothetical "random walk" on the phase space, in effect creating a Markov Chain. Since the term Monte Carlo is used ubiquitously to represent anything that involve some degrees of uncertainty, these methods are sometimes differentiated from others by the name Markov chain Monte Carlo (MCMC) The most widely used MC sampling algorithm is the Metropolis-Hastings algorithm. 2.2 The Metropolis-Hastings Algorithm Markov Chain 101 A markov chain consists of discrete states (labeled from 1 through $\Omega$). The state of the systme at time step $n$ is denoted $x_{n}$ The chain evolves according to the rule $$ Pr[x_{n+1}=j|x_n=i] = t_{ij} \quad (i,j=1,2,\ldots,\Omega) \quad (4)$$ The $t_{ij}$ are called transition probabilities and $T=(t_{ij})$ is the transition matrix. Stationary distribution ${\pi_i}$: $$ \pi_j = \sum_{i=1}^{\Omega}t_{ij}\pi_i(j = 1, 2, \ldots, \Omega) \quad (5)$$ It can be proven that a markov chain converges to a unique stationary distribution if the ergodicity condition is satiesfied (this notion of "ergodicity" is different from that used in statistical mechanics). Ergodicity is assumed throughout our discussions (for a detailed discussion see [2]). Detailed balance: For all $i$ and $j$, $t_{ij}\pi_i = t_{ji}\pi_j$. Intuitively, this means there's no net "probability flow" between any two states. It's easy to see that a system under detailed balance must also be in a stationary distribution. The M-H algorithm generates its samples by constructing a chain in detailed balance To sample the probability distribution $\pi(n) \, (n = 1,2,\ldots,\Omega)$, the algorithm goes as follows. Suppose the system is currently in state $a$: Propose a state $b$ different from $a$ using a predefined a priori distribution $A(a \rightarrow b)$ (More on this later). Carry out a Bernoulli trial with probability $$ p(a \rightarrow b) := \min[1,\frac{\pi(b)}{\pi(a)}\frac{A(b \rightarrow a)}{A(a \rightarrow b)}] \quad (6)$$ Accept state $b$ if the trial succeeds (this means updating the system to state $b$ as well as recording $b$ to the list of samples). Else, reject it and stays in $a$ (also recording $a$ in the list of samples). Check for yourself that the system defined above is in fact a markov chain with transition probability $t(a \rightarrow b) = A(a \rightarrow b)p(a \rightarrow b)$. Its stationary distribution is no other than $\pi(n)$. In addition, detailed balance is satiesfied upon reaching equilibrium. Note that in (6) only the quotient between $\pi(b)$ and $\pi(a)$ are required for the algorithm to work. This means we can specify $\pi(n)$ within an uncertainty of a multiplicative constant. In the case of statistical mechanics, we can ditch the partition function $Z$ altogether and only compute the Boltzman factor $\exp(-E(a)/k_BT)$ of the various states. 2.3 Example: a Metropolis-Hastings dice Consider a loaded dice. Upon throwing, the results have the following distribution: $\pi(1)=1/2$,$\pi(2)=1/4$,$\pi(3)=1/8$,$\pi(4)=1/16$,$\pi(5)=\pi(6)=1/32$ Choose a unifrom a priori distribution: $A(i \rightarrow j) = 1/6$ End of explanation """ samples = dice_samples(1000000) ns = np.array(np.logspace(1, 6, num=50), dtype=int) distributions = {i: np.zeros(50) for i in [1, 2, 3, 4 ,5 ,6]} for index in range(50): n = ns[index] distribution = summarize(samples[:n]) for i in [1, 2, 3, 4, 5, 6]: distributions[i][index] = distribution[i] for i in [1, 2, 3, 4, 5, 6]: plt.plot(ns, distributions[i], label='Face {}'.format(i)) plt.xlabel('MC iterations') plt.ylabel('Percentage') plt.ylim(0, 100) plt.semilogx() plt.legend() plt.grid() plt.title("The Metropolis-Hastings dice") """ Explanation: We change the number of MC steps to give a view to the time evolution of the M-H chain: End of explanation """ # First, we need helper function to transform between the (i, j) coordinate of a 2D lattice and a serial one # a: length of the square lattice's side def flatten_2d(i, j, a): return i * a + j # serial No. = row No. * lenght + colum No. def unflatten_2d(n, a): j = n % a i = (n - j) // a return i, j # Generate the adjacency list def gen_neighbors_1d(N): neighbors = np.zeros((N, 2), dtype=int) for n in range(N): neighbors[n][0] = (n - 1) % N # left neighbors[n][1] = (n + 1) % N # right return neighbors def gen_neighbors_2d(a): neighbors = np.zeros((a*a, 4), dtype=int) for n in range(a*a): i, j = unflatten_2d(n, a) neighbors[n][0] = flatten_2d(i, (j - 1) % a, a) # left neighbors[n][1] = flatten_2d(i, (j + 1) % a, a) # right neighbors[n][2] = flatten_2d((i - 1) % a, j, a) # up neighbors[n][3] = flatten_2d((i + 1) % a, j, a) # down return neighbors """ Explanation: So the constructed chains do converto our desired value. But notice the length of transient steps: it took as much as 10000 steps for us to obtain a reasonably accurate value! As we will see below, this "high accuracy, low precision" characteristic of MC methods (a slow convergence to an exact value) is ubiquitous. It remains a problem til this day to find a MC method that have fast convergence. 3. MC Simulation of the Ising Model 3.1 The "single-flip" MC A uniform representation for both the 1D and 2D Ising Model The modern language of nearest-neighbor interation topology is graph theory. We use the most popular graph storage format --- the adjacency list format --- to record the structure of 1D (chain) and 2D (square lattice) Ising Models: End of explanation """ def MH_single_flip(neighbors_list, T, iterations): ''' This function performs single flip MC iterations for an Ising system with arbitrary topology, given by the adjaceny list `neighbors_list`. The inital state is chosen randomly. Returns ======= `magnetization`: magnetization (average molecular spin) at each MC step `energy`: total energy of the system at each MC step ''' # Initialization size = neighbors_list.shape[0] spins = np.random.random_integers(0, 1, size) spins[spins == 0] = -1 # Allocation magnetization = np.zeros(iterations + 1) energy = np.zeros(iterations + 1) magnetization[0] = spins.sum() energy[0] = -spins.dot(spins[neighbors_list].sum(axis=1)) / 2 for step in range(iterations): n = np.random.randint(0, size) # Choose next state according to the a priori distribution delta_E = 2 * spins[n] * spins[neighbors_list[n]].sum() if delta_E < 0 or np.random.rand() < np.exp(-delta_E / T): # Acceptance spins[n] = -spins[n] magnetization[step + 1] = magnetization[step] + 2 * spins[n] energy[step + 1] = energy[step] + delta_E else: # Rejection magnetization[step + 1] = magnetization[step] energy[step + 1] = energy[step] return magnetization / size, energy """ Explanation: Let $J=1$,$k_B=1$ in the following discussion: State of the markov chain = microstate of the Ising Model $\vec{\sigma} := (\sigma_1\ldots\sigma_N)^T$ A priori probability: choose uniformly from any state that relates to the current state by a single spin flip Energy difference resulting from a single flip: $\delta E= 2\sigma_i\sum_{[i,j]}\sigma_j $ Acceptance probability $ P=\min(1, \exp(-\delta E/T)) $ The "single flip" mechanism makes the previously defined adjacency list particularly useful. End of explanation """ def plot_magnetization(dimension): if dimension == 1: neighbors_list = gen_neighbors_1d(400) elif dimension == 2: neighbors_list = gen_neighbors_2d(20) T_list = [0.5, 1.0, 1.5, 1.8, 2.0, 2.2, 2.4, 3.0, 3.5] fig = plt.figure(figsize=(12, 40)) for i in range(9): T = T_list[i] magnetization, _ = MH_single_flip(neighbors_list, T, 100000) # Random walk history fig.add_subplot(9, 2, 2 * i + 1) plt.plot(magnetization) plt.ylim(-1, 1) plt.ylabel('Magnetization') plt.xlabel('Iterations') plt.annotate('T = {}'.format(T), (10000,0.8)) plt.grid() # Sample distribution histogram fig.add_subplot(9, 2, 2 * i + 2) plt.hist(magnetization, bins=np.linspace(-1, 1, num=20), orientation='horizontal') plt.ylim(-1, 1) plt.xlabel('Counts') plt.grid() plt.suptitle("Monte Carlo simulation history & distribution to the {:d}D Ising Model".format(dimension)) plot_magnetization(1) plot_magnetization(2) """ Explanation: Let's see the result for 1D and 2D Ising Models: End of explanation """ def spin_correlation(spins, a): M = spins.mean() spins_2d = spins.reshape((a, a)) rs = np.arange(-a/2, a/2 + 1, dtype=int) num_rs = len(rs) correlations = np.zeros((num_rs, num_rs)) for i, y in enumerate(rs): for j, x in enumerate(rs): correlations[i, j] = (spins_2d * np.roll(np.roll(spins_2d, x, axis=1), y, axis=0)).mean() + M**2 return correlations """ Explanation: Remarks: No spontaneous Magnetization is seen in the 1D case, in agreement with the result from Ising. The 2D case displays spontaneous behavior roughly for $T$ smaller than the theoretical critical temperature $T_C$. However, instead of a two-peak distribution as prescribed by the canocical distribution, only one peak is observed. Convergence of the markow chain is very slow for $T \approx T_C$. We can prove theoretically that the number of steps required actually diverges as $T \rightarrow T_C$. This is called the critical slowing down behavior. Interesting results! But why? 3.2 Theoretical interlude: the clustering of spins near $T_C$ Recall the definition of the spin correlation function: $$ g(x, y) := E[\sigma(m + x, n + y)\sigma(m, n)] - E[\sigma(m + x, m + y)]E[\sigma(m, n)] \quad (7)$$ where the expectation is taken for all grid points $(m, n)$. The above formula can be simplified if we assume periodic boundary consitions for all sides: $$ g(x, y) = E[\sigma(m + x, n + y)\sigma(m, n)] - M^2 \quad (8) $$ where $M := E[\sigma(n)]$. The spin correlation function can tell us more about what happens when $T \approx T_C$. End of explanation """ def gen_snapshots(time_stamps, a, T): iterations = time_stamps[-1] snapshots = {} neighbors_list = gen_neighbors_2d(a) size = neighbors_list.shape[0] spins = np.random.random_integers(0, 1, size) spins[spins == 0] = -1 for step in range(iterations): n = np.random.randint(0, size) delta_E = 2 * spins[n] * spins[neighbors_list[n]].sum() if delta_E < 0 or np.random.rand() < np.exp(-delta_E / T): spins[n] = -spins[n] if step + 1 in time_stamps: snapshots[step + 1] = { 'spins': spins.copy().reshape((a, a)), 'magnetization': spins.mean(), 'correlation': spin_correlation(spins, a) } return snapshots """ Explanation: We modify the single-flip MC code a bit to have it output snapshots of the system at the given time stamps: End of explanation """ a = 40 T = 2.2 time_stamps = np.array([1, 10, 100, 1000, 10000, 20000, 40000, 60000, 80000, 100000]) snapshots = gen_snapshots(time_stamps, a, T) fig, axes = plt.subplots(10, 2, figsize=(12, 6 * 10)) for i, t in enumerate(time_stamps): axes[i][0].matshow(snapshots[t]['spins'], interpolation='none') axes[i][0].set_ylabel('MC step {}, M = {:.3f}'.format(t, snapshots[t]['magnetization'])) axes[i][0].set_xlabel('Spins') axes[i][1].matshow(snapshots[t]['correlation']) axes[i][1].set_xlabel('Spin correlation function') axes[i][1].set_xticks([0, 10, 20, 30, 40]) axes[i][1].set_xticklabels([-20, -10, 0, 10, 20]) axes[i][1].set_yticks([0, 10, 20, 30, 40]) axes[i][1].set_yticklabels([-20, -10, 0, 10, 20]) """ Explanation: This is what happens when $T = 2.2$: End of explanation """ def cluster_MC(neighbors_list, T, iterations): p = 1 - np.exp(-2 / T) # "magic number" # Initialization size = neighbors_list.shape[0] spins = np.random.random_integers(0, 1, size) spins[spins == 0] = -1 # Allocation magnetization = np.zeros(iterations + 1) magnetization[0] = spins.sum() energy = np.zeros(iterations + 1) energy[0] = -spins.dot(spins[neighbors_list].sum(axis=1)) for step in range(iterations): # Use a deque to implement breadth-first search n0 = np.random.randint(0, size) sign = spins[n0] cluster = set([n0]) pockets = deque([n0]) finished = False while not finished: try: n = pockets.popleft() neighbors = neighbors_list[n] for neighbor in neighbors: if spins[neighbor] == sign and neighbor not in cluster and np.random.rand() < p: cluster.add(neighbor) pockets.append(neighbor) except IndexError: finished = True # Flip the cluster cluster = np.fromiter(cluster, dtype=int) spins[cluster] = -sign magnetization[step + 1] = magnetization[step] - 2 * sign * len(cluster) energy[step + 1] = -spins.dot(spins[neighbors_list].sum(axis=1)) return magnetization / size, energy / 2 # Every pair is counted two times """ Explanation: So the markov chain, instead of converging, actually goes into an ordered stated with considerable correlation between the spins. The spin clusters formed in the process makes it more difficult for future states to be accepted, as a randomly picked molecule is more like to be inside a cluster than at the boundary between two clusters. Flipping this molecule would thus increase the system's energy, so it's more likely to be rejected. This is the explanation for the above mentioned critical slowing down behavior. The same argument can be applied to the spontaneous magnitization state for $T \ll T_C$. In this case, once the system enter the ordered state the giant cluster makes further flipping very difficult to accept. Because we have arbitrarily constrained the system to move only a small step in configuration space per MC step, it would take forever for it to move from one steady state to another. 3.3 Cluster MC To address the problems mentioned above, the cluster Monte Carlo method is proposed to allow for large configuration space hopping between two MC steps. Specifically: A "seed" is chosen randomly at the start of each MC step. A breadth-first search is performed in the lattice starting from the "seed". Whenever a molecule with the same spin as the seed is encountered, it is added to the breadth-first queue with probability p. The search is carried on until the queue is exhausted, generating a cluster of same-spin molecules from the breadth-first tree. A new state is proposed by flipping all molecules within the cluster. The acceptance/rejection procedure is identical to that given by Metropolis-Hastings. To carry out cluster MC, we need to calculated the effective a priori distribution from the procedures described above. We state the result without proving (refer to Ref [2] for a complete discussion): If we set $p$ to the "magic number" $1-e^{2/T}$, then $p(a \rightarrow b) \equiv 1$, which means the next state will always be accepted. We can already see that under this choice MC iterations can be carried out way quicker than the single-flip scheme. End of explanation """ def plot_magnetization_cluster(dimension): if dimension == 1: neighbors_list = gen_neighbors_1d(400) elif dimension == 2: neighbors_list = gen_neighbors_2d(20) T_list = [0.5, 1.0, 1.5, 1.8, 2.0, 2.2, 2.4, 3.0, 3.5] fig = plt.figure(figsize=(12, 40)) for i in range(9): T = T_list[i] magnetization, _ = cluster_MC(neighbors_list, T, 1000) # 随机行走历史 fig.add_subplot(9, 2, 2 * i + 1) plt.plot(magnetization) plt.ylim(-1, 1) plt.ylabel('Magnetization') plt.xlabel('Iterations') plt.annotate('T = {}'.format(T), (50,0.8)) # 样本分布直方图 fig.add_subplot(9, 2, 2 * i + 2) plt.hist(magnetization, bins=np.linspace(-1, 1, num=20), orientation='horizontal') plt.ylim(-1, 1) plt.xlabel('Counts') plt.suptitle("Monte Carlo simulation history & distribution to the {:d}D Ising Model".format(dimension)) plot_magnetization_cluster(2) """ Explanation: Cluster MC vs. single-flip MC in the field: End of explanation """ def averages(magnetization, energy, T): '''计算各量的系综平均''' M = np.abs(magnetization).mean() E = energy.mean() CV = energy.var() / T return M, E, CV # The code below runs VERY SLOWLY points = 31 dimension = 64 iterations = 5000 neighbors_list = gen_neighbors_2d(dimension) Ts = np.linspace(1.0, 4.0, points) Ms = np.zeros(points) for i in range(points): T = Ts[i] magnetization, _ = cluster_MC(neighbors_list, T, iterations) Ms[i] = np.abs(magnetization).mean() # print("Iteration for T = {:.3f} complete".format(T)) # Uncomment to print progress as the simulation goes Onsager_Tc = 2.269 Ts_plot = np.linspace(1.0, 4.0, num=200) Onsager_Ms = np.zeros(len(Ts_plot)) for i, T in enumerate(Ts_plot): if T <= 2.269: Onsager_Ms[i] = (1 - (np.sinh(2/T))**(-4))**(1/8) plt.plot(Ts, Ms, '^', label='simulation') plt.plot(Ts_plot, Onsager_Ms, '--', label='theoretical') plt.ylim(0, 1) plt.legend() plt.xlabel('Temperature') plt.ylabel('Magnetization') plt.grid() plt.title("Theoretical vs. Numerical values for spontaneous magnitization") """ Explanation: 3.4 Comparison to theoretical results We compare results from cluster MC to the ones given by Onsager in (3): End of explanation """ import sys print("Python version = ", sys.version) print("Numpy version = ", np.version.version) print("Matplotlib version = ", matplotlib.__version__) """ Explanation: 4. Development of MC methods Different choice of a priori distributions; Hybrid MC/MD simulations; Better sample generation: correlation, buring and thinning; MCMC applied to Hierarchichal Bayesian Models in the field of statistics. An excellent material is Probabilistic Programming and Bayesian Methods for Hackers References [1] N.Metropolis, A.W.Rosenbluth, M.N.Rosenbluth, A.H.Teller, E.Teller, Equation of State Calculations by Fast Computing Machines, The Journal of Chemial Physics 21(1953), pp.1087 [2] K.Werner, Statistical Mechanics: Algorithms and Computations, Oxford(2006) End of explanation """
WomensCodingCircle/CodingCirclePython
Lesson02_Conditionals/Conditional Execution.ipynb
mit
cleaned_room = True took_out_trash = False print(cleaned_room) print(type(took_out_trash)) """ Explanation: Conditional Execution Boolean Expressions We introduce a new value type, the boolean. A boolean can have one of two values: True or False End of explanation """ print(5 == 6) print("Coke" != "Pepsi") # You can compare to variables too allowance = 5 print(5 >= allowance) print(allowance is True) """ Explanation: Comparison Operators You can compare values together and get a boolean result | Operator | Meaning| |------|------| | x == y | x equal to y | | x != y | x not equal to y | | x > y | x greater than y | | x < y | x less than y | | x >= y | x greater than or equal to y | | x <= y | x less than or equal to y | | x is y | x is the same as y | | x is not y | x is not the same as y | By using the operators in an expression the result evaluates to a boolean. x and y can be any type of value End of explanation """ # cleaned_room is true if cleaned_room: print("Good kid! You can watch TV.") # took_out_trash if false if took_out_trash: print("Thank you!") print(took_out_trash) """ Explanation: TRY IT See if 5.0000001 is greater than 5 Conditional Execution We can write programs that change their behavior depending on the conditions. We use an if statement to run a block of code if a condition is true. It won't run if the condition is false. if (condition): code_to_execute # if condition is true In python indentation matters. The code to execute must be indented (4 spaces is best, though I like tabs) more than the if condition. End of explanation """ # cleaned_room is true if cleaned_room: print("Good job! You can watch TV.") print("Or play outside") # took_out_trash is false if took_out_trash: print("Thank you!") print("You are a good helper") print("It is time for lunch") """ Explanation: You can include more than one statement in the block of code in the if statement. You can tell python that this code should be part of the if statement by indenting it. This is called a 'block' of code if (condition): statement1 statement2 statement3 You can tell python that the statement is not part of the if block by dedenting it to the original level if (condition): statement1 statement2 statement3 # statement3 will run even if condition is false End of explanation """ candies_taken = 4 if candies_taken < 3: print('Enjoy!') else: print('Put some back') """ Explanation: In alternative execution, there are two possibilities. One that happens if the condition is true, and one that happens if it is false. It is not possible to have both execute. You use if/else syntax if (condition): code_runs_if_true else: code_runs_if_false Again, note the colons and spacing. These are necessary in python. End of explanation """ did_homework = True took_out_trash = True cleaned_room = False allowance = 0 if cleaned_room: allowance = 10 elif took_out_trash: allowance = 5 elif did_homework: allowance = 4 else: allowance = 2 print(allowance) """ Explanation: Chained conditionals allow you to check several conditions. Only one block of code will ever run, though. To run a chained conditional, you use if/elif/else syntax. You can use as many elifs as you want. if (condition1): run_this_code1 elif (condition2): run_this_code2 elif (condition3): run_this_code3 else: run_this_code4 You are not required to have an else block. if (condition1): run_this_code1 elif (condition2): run_this_code2 Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes. End of explanation """ print(True and True) print(False or True) print(not False) """ Explanation: TRY IT Check if did_homework is true, if so, print out "You can play a video game", otherwise print out "Go get your backpack" Logical Operators Logical operators allow you to combine two or more booleans. They are and, or, not and Truth table (only true if both values are true) | val1 | val2 | val1 and val2 | |-- |------|------| | true | true | true | | true | false | false | | false | true | false | | false | false | false | or Truth table (true if at least 1 value is true) | val1 | val2 | val1 or val2 | |------|------|------| | true | true | true | | true | false | true | | false | true | true | | false | false | false | not Truth table (the opposite of the value) | val1 | not val1 | |------|------| | true | false | | false | true | End of explanation """ cleaned_room = True took_out_trash = False if cleaned_room and took_out_trash: print("Let's go to Chuck-E-Cheese's.") else: print("Get to work!") if not did_homework: print("You're going to get a bad grade.") """ Explanation: You can use the logical operators in if statements End of explanation """ allowance = 5 if allowance > 2: if allowance >= 8: print("Buy toys!") else: print("Buy candy!") else: print("Save it until I have enough to buy something good.") """ Explanation: TRY IT Check if the room is clean or the trash is taken out and if so print "Here is your allowance" Nested Conditionals You can nest conditional branches inside another. You just indent each level more. if (condition): run_this else: if (condition2): run_this2 else: run_this3 Avoid nesting too deep, it becomes difficult to read. End of explanation """ try: print("Before") y = 5/0 print("After") except: print("I'm sorry, the universe doesn't work that way...") """ Explanation: Catching exceptions using try and except You can put code into a try/except block. If the code has an error in the try block, it will stop running and go to the except block. If there is no error, the try block completes and the except block never runs. try: code except: code_runs_if_error End of explanation """ try: print("Before") y = 5/0 print("After") except: print("I'm sorry, the universe doesn't work that way...") finally: print("Even if you break python, you still have to do your chores") """ Explanation: A finally statment can be added to the try/except block and it executes at the end whether or not there is an error. This can be useful for cleaning up resources. try: code except: code_runs_if_error finally: code runs at end with or without error End of explanation """ inp = input('Enter Fahrenheit Temperature:') try: fahr = float(inp) cel = (fahr - 32.0) * 5.0 / 9.0 print(cel) except: print('Please enter a number') """ Explanation: This can be useful when evaluating a user's input, to make sure it is what you expected. End of explanation """ if (1 < 2) or (5/0): print("How did we do that?") """ Explanation: TRY IT Try converting the string 'candy' into an integer. If there is an error, print "What did you think would happen?" Short-circuit evaluation of logical expressions Python (and most other languages) are very lazy about logical expressions. As soon as it knows the value of the whole expression, it stops evaluating the expression. if (condition1 and condition2): run_code In the above example, if condition1 is false then condition2 is never evaluated. End of explanation """
AllenDowney/MarriageNSFG
survival.ipynb
mit
from __future__ import print_function, division import marriage import thinkstats2 import thinkplot import pandas import numpy from lifelines import KaplanMeierFitter from collections import defaultdict import itertools import math import matplotlib.pyplot as pyplot from matplotlib import pylab %matplotlib inline """ Explanation: This notebook contains examples related to survival analysis, based on Chapter 13 of Think Stats, 2nd Edition, by Allen Downey, available from thinkstats2.com End of explanation """ resp8 = marriage.ReadFemResp2013() resp7 = marriage.ReadFemResp2010() resp6 = marriage.ReadFemResp2002() resp5 = marriage.ReadFemResp1995() resp4 = marriage.ReadFemResp1988() resp3 = marriage.ReadFemResp1982() resps = [resp1, resp2, resp3, resp4] """ Explanation: The following code looks at examining the survival until marriage of women from the United States from different age brackets and cohorts. End of explanation """ #For each data set, find the number of people who married and the number who have not yet t_complete = [] t_ongoing = [] for resp in resps: complete = resp[resp.evrmarry == 1].agemarry ongoing = resp[resp.evrmarry == 0].age t_complete.append(complete) t_ongoing.append(ongoing) """ Explanation: For complete cases, we know the respondent's age at first marriage. For ongoing cases, we have the respondent's age when interviewed. End of explanation """ t_nan = [] for complete in t_complete: nan = [numpy.isnan(complete)] len(nan) """ Explanation: There are only a few cases with unknown marriage dates. End of explanation """ resps = [resp1, resp2, resp3, resp4, resp5] data_set_names = [2010, 2002, 1995, 1982, 1988] for i in range(len(resps)): married = resps[i].agemarry valued = [m for m in married if str(m) != 'nan'] #print proportion of people who have a value for this print(data_set_names[i], len(valued)/len(resps[i])) """ Explanation: Here we are investigating the percent of poeple who are married compared to the total data set to make sure that there is not something weird going on with the data. From this it seems like there is definitely something going on with the 1988 data. End of explanation """ survival.PlotResampledByDecade(resps, weighted=True) thinkplot.Config(xlabel='age (years)', ylabel='probability unmarried', legend=True, pos=2) survival.PlotResampledByDecade(resps, weighted=False) thinkplot.Config(xlabel='age (years)', ylabel='probability unmarried', legend=True, pos=2) """ Explanation: EstimateHazardFunction is an implementation of Kaplan-Meier estimation. With an estimated hazard function, we can compute a survival function. End of explanation """ def PlotResampledByAge(resps, n=6, **options): """ Takes in a list of the groups of respondents and the number of desired age brackets dsiplays a plot comparing the probability a woman is married against her cohort for n number of age groups resps -- list of dataframes n -- number of age brackets """ # for i in range(11): # samples = [thinkstats2.ResampleRowsWeighted(resp) # for resp in resps] sample = pandas.concat(resps, ignore_index=True) groups = sample.groupby('fives') #number of years per group if there are n groups group_size = 30/n #labels age brackets depending on # divs labels = ['{} to {}'.format(int(15 + group_size * i), int(15+(i+1)*group_size)) for i in range(n)] # 0 representing 15-24, 1 being 25-34, and 2 being 35-44 #initilize dictionary of size n, with empty lists prob_dict = {i: [] for i in range(n)} #TODO: Look into not hardcoding this decades = [30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] for _, group in groups: #calcualates the survival function for each decade _, sf = survival.EstimateSurvival(group) if len(sf.ts) > 1: #iterates through all n age groups to find the probability of marriage for that group for group_num in range(0,n): temp_prob_list = sf.Probs([t for t in sf.ts if (15 + group_size*group_num) <= t <= (15 + (group_num+1)*group_size)]) if len(temp_prob_list) != 0: prob_dict[group_num].append(1-sum(temp_prob_list)/len(temp_prob_list)) else: pass #set up subplots iteration = 0 num_plots = numpy.ceil(n/6.0) for key in prob_dict: iteration += 1 xs = decades[0:len(prob_dict[key])] pyplot.subplot(num_plots, 1, numpy.ceil(iteration/6)) thinkplot.plot(xs, prob_dict[key], label=labels[key], **options) #add labels/legend thinkplot.Config(xlabel='cohort (decade birth)', ylabel='probability married', legend=True, pos=2) pylab.legend(loc=1, bbox_to_anchor=(1.35, 0.75)) """ Explanation: Here we use the surviavl function to look at how the percent of people marries as a function of decade and cohort. End of explanation """ def PlotResampledHazardByAge(resps, n=6, **options): """ Takes in a list of the groups of respondents and the number of desired age brackets dsiplays a plot comparing the probability a woman is married against her cohort for n number of age groups resps -- list of dataframes n -- number of age brackets """ # for i in range(20): # samples = [thinkstats2.ResampleRowsWeighted(resp) # for resp in resps] # print(len(resps[1])) sample = pandas.concat(resps, ignore_index=True) groups = sample.groupby('decade') #number of years per group if there are n groups group_size = 30/n #labels age brackets depending on # divs labels = ['{} to {}'.format(int(15 + group_size * i), int(15+(i+1)*group_size)) for i in range(n)] # 0 representing 15-24, 1 being 25-34, and 2 being 35-44 #initilize dictionary of size n, with empty lists prob_dict = {i: [] for i in range(n)} #TODO: Look into not hardcoding this decades = [30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90] for _, group in groups: #calcualates the survival function for each decade _, sf = survival.EstimateSurvival(group) if len(sf.ts) > 1: #iterates through all n age groups to find the probability of marriage for that group for group_num in range(0,n): temp_prob_list = numpy.diff(sf.Probs([t for t in sf.ts if (15 + group_size*group_num) <= t <= (15 + (group_num+1)*group_size)])) if len(temp_prob_list) != 0: prob_dict[group_num].append(sum(temp_prob_list)/len(temp_prob_list)) else: pass #Set up subplots iteration = 0 num_plots = numpy.ceil(n/6.0) for key in prob_dict: iteration += 1 xs = decades[0:len(prob_dict[key])] pyplot.subplot(num_plots, 1, numpy.ceil(iteration/6)) thinkplot.plot(xs, prob_dict[key], label=labels[key], **options) #plot labels/legend thinkplot.Config(xlabel='cohort (decade birth)', ylabel='Hazard of Marriage', legend=True, pos=2) pylab.legend(loc=1, bbox_to_anchor=(1.35, 0.75)) """ Explanation: This function will do a similar thing to the above function, but uses the derivative of the hazard function to investigate how the hazard of marriage changes as a function of age and cohort. End of explanation """ pyplot.hold(True) PlotResampledHazardByAge(resps, 6) """ Explanation: Plotting the hazard to see trends across cohorts End of explanation """ pyplot.hold(True) PlotResampledHazardByAge(resps, 10) """ Explanation: Here we plot how the hazard of marriage changes across cohort using a finer break down of age groups. Doing this allows us to see a little more clearly the change in how people of each age group are at hazard in subsequent generations. End of explanation """ pyplot.hold(True) PlotResampledByAge(resps, 6) pyplot.hold(True) PlotResampledByAge(resps, 10) """ Explanation: Here we do a similar analysis looking at survival. End of explanation """
flaviostutz/datascience-snippets
study/udacity-deep-learning/assignment2-neuralnetworks.ipynb
mit
# These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range """ Explanation: Deep Learning Assignment 2 Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset. The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow. End of explanation """ pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) """ Explanation: First reload the data we generated in 1_notmnist.ipynb. End of explanation """ image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) """ Explanation: Reformat into a shape that's more adapted to the models we're going to train: - data as a flat matrix, - labels as float 1-hot encodings. End of explanation """ # With gradient descent training, even this much data is prohibitive. # Subset the training data for faster turnaround. train_subset = 10000 graph = tf.Graph() with graph.as_default(): # Input data. # Load the training, validation and test data into constants that are # attached to the graph. tf_train_dataset = tf.constant(train_dataset[:train_subset, :]) tf_train_labels = tf.constant(train_labels[:train_subset]) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. # These are the parameters that we are going to be training. The weight # matrix will be initialized using random values following a (truncated) # normal distribution. The biases get initialized to zero. weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation. # We multiply the inputs with the weight matrix, and add biases. We compute # the softmax and cross-entropy (it's one operation in TensorFlow, because # it's very common, and it can be optimized). We take the average of this # cross-entropy across all training examples: that's our loss. logits = tf.matmul(tf_train_dataset, weights) + biases loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits)) # Optimizer. # We are going to find the minimum of this loss using gradient descent. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. # These are not part of training, but merely here so that we can report # accuracy figures as we train. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf_valid_dataset, weights) + biases) test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) """ Explanation: We're first going to train a multinomial logistic regression using simple gradient descent. TensorFlow works like this: * First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description is all contained within the block below: with graph.as_default(): ... Then you can run the operations on this graph as many times as you want by calling session.run(), providing it outputs to fetch from the graph that get returned. This runtime operation is all contained in the block below: with tf.Session(graph=graph) as session: ... Let's load all the data into TensorFlow and build the computation graph corresponding to our training: End of explanation """ num_steps = 1000 def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) with tf.Session(graph=graph) as session: # This is a one-time operation which ensures the parameters get initialized as # we described in the graph: random weights for the matrix, zeros for the # biases. tf.global_variables_initializer().run() print('Initialized') for step in range(num_steps): # Run the computations. We tell .run() that we want to run the optimizer, # and get the loss value and the training predictions returned as numpy # arrays. _, l, predictions = session.run([optimizer, loss, train_prediction]) if (step % 100 == 0): print('Loss at step %d: %f' % (step, l)) print('Training accuracy: %.1f%%' % accuracy( predictions, train_labels[:train_subset, :])) # Calling .eval() on valid_prediction is basically like calling run(), but # just to get that one numpy array. Note that it recomputes all its graph # dependencies. print('Validation accuracy: %.1f%%' % accuracy( valid_prediction.eval(), valid_labels)) print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels)) """ Explanation: Let's run this computation and iterate: End of explanation """ batch_size = 128 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation. logits = tf.matmul(tf_train_dataset, weights) + biases loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits)) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf_valid_dataset, weights) + biases) test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) """ Explanation: Let's now switch to stochastic gradient descent training instead, which is much faster. The graph will be similar, except that instead of holding all the training data into a constant node, we create a Placeholder node which will be fed actual data at every call of session.run(). End of explanation """ num_steps = 10001 with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = (step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run( [optimizer, loss, train_prediction], feed_dict=feed_dict) if (step % 500 == 0): print("Minibatch loss at step %d: %f" % (step, l)) print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) print("Validation accuracy: %.1f%%" % accuracy( valid_prediction.eval(), valid_labels)) print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) """ Explanation: Let's run it: End of explanation """ pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) # Network Parameters n_hidden_1 = 1024 # 1st layer number of features #n_hidden_2 = 256 # 2nd layer number of features #n_hidden_3 = 256 # 3nd layer number of features n_input = 784 # notMNIST data input (img shape: 28*28) n_classes = 10 # notMNIST total classes (0-9 digits) # tf Graph input x = tf.placeholder("float", [None, n_input]) y = tf.placeholder("float", [None, n_classes]) # Create model def multilayer_perceptron(x, weights, biases): # Hidden layer with RELU activation layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Hidden layer with RELU activation # layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) # layer_2 = tf.nn.relu(layer_2) # Hidden layer with RELU activation # layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3']) # layer_3 = tf.nn.relu(layer_3) # Output layer with linear activation out_layer = tf.matmul(layer_1, weights['out']) + biases['out'] return out_layer # Parameters learning_rate = 0.001 # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), # 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), # 'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3])), 'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), # 'b2': tf.Variable(tf.random_normal([n_hidden_2])), # 'b3': tf.Variable(tf.random_normal([n_hidden_3])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Construct model pred = multilayer_perceptron(x, weights, biases) # Define loss and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) #Parameters training_epochs = 20 batch_size = 100 display_step = 1 # Launch the graph with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(train_dataset.shape[0]/batch_size) # Loop over all batches for i in range(total_batch): offset = (i * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_x = train_dataset[offset:(offset + batch_size), :] batch_y = train_labels[offset:(offset + batch_size), :] # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y}) # Compute average loss avg_cost += c / total_batch # Display logs per epoch step if epoch % display_step == 0: print("Epoch %d: cost=%.1f valid_accuracy=%.1f%% train_accuracy=%.1f%%" % (epoch+1, avg_cost, (accuracy.eval({x: valid_dataset, y: valid_labels})*100), (accuracy.eval({x: train_dataset, y: train_labels})*100))) print("Optimization Finished!") print("test_accuracy: %.1f%%" % (accuracy.eval({x: test_dataset, y: test_labels})*100)) """ Explanation: Problem Turn the logistic regression example with SGD into a 1-hidden layer neural network with rectified linear units nn.relu() and 1024 hidden nodes. This model should improve your validation / test accuracy. End of explanation """ #pickle_file = 'notMNIST_sanitized.pickle' pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) batch_size = 128 hidden_nodes = 1024 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights_1 = tf.Variable( tf.truncated_normal([image_size * image_size, hidden_nodes])) biases_1 = tf.Variable(tf.zeros([hidden_nodes])) weights_2 = tf.Variable( tf.truncated_normal([hidden_nodes, num_labels])) biases_2 = tf.Variable(tf.zeros([num_labels])) # Training computation. def forward_prop(input): h1 = tf.nn.relu(tf.matmul(input, weights_1) + biases_1) return tf.matmul(h1, weights_2) + biases_2 def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) logits = forward_prop(tf_train_dataset) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) # Optimizer. optimizer = tf.train.AdamOptimizer(learning_rate=0.002).minimize(loss) # optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax(forward_prop(tf_valid_dataset)) test_prediction = tf.nn.softmax(forward_prop(tf_test_dataset)) num_steps = 5001 with tf.Session(graph=graph) as session: init = tf.global_variables_initializer() session.run(init) print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = (step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict) if (step % 500 == 0): print("Minibatch loss at step %d: %f" % (step, l)) print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels)) print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) """ Explanation: Problem - second version End of explanation """
LSSTC-DSFP/LSSTC-DSFP-Sessions
Sessions/Session13/Day0/LeastSquaresAssumptions.ipynb
mit
y = np.array([203, 58, 210, 202, 198, 158, 165, 201, 157, 131, 166, 160, 186, 125, 218, 146]) x = np.array([495, 173, 479, 504, 510, 416, 393, 442, 317, 311, 400, 337, 423, 334, 533, 344]) """ Explanation: The Assumptions of Least Squares ======== Version 0.1 By AA Miller (Northwestern/CIERA) 2018 Nov 04 Today we will focus on a relatively simple problem, while highlighting several challenges for the standard astronomical workflow, as a way of setting up the various lectures that will happen over the course of this week. A lot of the lessons in this lecture are inspired by the paper Data Analysis Recipes: Fitting a Model to Data by Hogg, Bovy, & Lang. [This paper has been mentioned previously in the DSFP, though today we will only be able to scratch the surface of its content.] In some sense - the goal right now is to make you really nervous about the work that you've previously done. (Though this lecture should not be met with too much consternation –– we will discuss new approaches to fitting a line) Problem 1) Data At the core of everything we hope to accomplish with the DSFP stands a single common connection: data. There are many things we (may) want to do with these data: reduce them, visualize them, model them, develop predictions from them, use them to infer fundamental properties of the universe (!). Before we dive into that really fun stuff, we should start with some basics: Problem 1a What is data? Take a few min to discuss this with your partner Solution 1a write your answer here Problem 1b Below, I provide some data (in the form of numpy arrays). As good data scientists, what is the first thing you should do with this data? Feel free to create a new cell if necessary. End of explanation """ plt.scatter( # complete # complete # complete """ Explanation: Problem 1c [You may have already done this] Now that we understand the origin of the data, make a scatter plot showing their distribution. End of explanation """ p = np.polyfit( # complete plt.scatter( # complete # complete """ Explanation: Probelm 2) Fitting a Line to Data There is a very good chance, though I am not specifically assuming anything, that upon making the previous plot you had a thought along the lines of "these points fall on a line" or "these data represent a linear relationship." Problem 2a Is the assumption of linearity valid for the above data? Is it convenient? Take a few min to discuss this with your partner Solution 2a write your answer here Let us proceed with convenience and assume the data represent a linear relationship. In that case, in order to make predictions for future observations, we need to fit a line to the data. The "standard" proceedure for doing so is least-squares fitting. In brief, least-squares minimizes the sum of the squared value of the residuals between the data and the fitting function. I've often joked that all you need to be a good data scientist is google and stack overflow. Via those two tools, we can quickly deduce that the easiest way to perform a linear least-squares fit to the above data is with np.polyfit, which performs a least-squares polynomial fit to two numpy arrays. Problem 2b Use np.polyfit() to fit a line to the data. Overplot the best-fit line on the data. End of explanation """ p_yx = np.polyfit( # complete plt.scatter( # complete # complete print("For y vs. x, then x=50 would predict y={:.2f}".format( # complete print("For x vs. y, then x=50 would predict y={:.2f}".format( # complete """ Explanation: There is a very good chance, though, again, I am not specifically assuming anything, that for the previous plots that you plotted x along the abscissa and y along the ordinate. [Honestly, there's no one to blame if this is the case, this has essentially been drilled into all of us from the moment we started making plots. In fact, in matplotlib we cannot change the name of the abscissa label without adjusting the xlabel.] This leads us to an important question, however. What if y does not depend on x and instead x depends on y? Does that in any way change the results for the fit? Problem 2c Perform a linear least-squares fit to x vs. y (or if you already fit this, then reverse the axes). As above, plot the data and the best-fit model. To test if the relation is the same between the two fits, compare the predicted y value for both models corresponding to x = 50. End of explanation """ x = np.array([203, 58, 210, 202, 198, 158, 165, 201, 157, 131, 166, 160, 186, 125, 218, 146]) y = np.array([495, 173, 479, 504, 510, 416, 393, 442, 317, 311, 400, 337, 423, 334, 533, 344]) sigma_y = np.array([21, 15, 27, 14, 30, 16, 14, 25, 52, 16, 34, 31, 42, 26, 16, 22]) plt.errorbar( # complete """ Explanation: So we have now uncovered one of the peculiariaties of least-squares. Fitting y vs. x is not the same as fitting x vs. y. There are a couple essential assumptions that go into standard least-squares fitting: There is one dimension along which the data have negligible uncertainties Along the other dimension all of the uncertainties can be described via Gaussians of known variance These two conditions are rarely met for astronomical data. While condition 1 can be satisfied (e.g., time series data where there is essentially no uncertainty on the time of the observations), I contend that condition 2 is rarely, if ever, satisfied. Speaking of uncertainties(1), we have not utilized any thus far. [I hope this has raised some warning bells.] We will now re-organize our data to match what is originally in Hogg, Bovy, & Lang (previously x and y were swapped). (1) There is an amazing footnote in Hogg, Bovy, & Lang about "errors" vs. "uncertainties" - I suggest everyone read this. Problem 2d Re-plot the data including the uncertatines. End of explanation """ Y = # complete A = # complete C = # complete X = # complete best_fit = # complete plt.errorbar( # complete plt.plot( # complete print("The best-fit value for the slope and intercept are: {:.4f} and {:.4f}".format( # complete """ Explanation: We are now assuming that x has negligible uncertainties and that y has uncertainties that can be perfectly described by Gaussians of known variance. A portion of the appeal of least-squares is that it provides a deterministic method for determining the best fit. To understand that we now need to do a little linear algebra. We can arrange the data in the following matricies: $$ \mathbf{Y} = \left[ {\begin{array}{c} y_1 \ y_2 \ \dots \ y_N \end{array} } \right] , $$ $$ \mathbf{A} = \left[ {\begin{array}{cc} 1 & x_1 \ 1 & x_2 \ \dots & \dots \ 1 & x_N \end{array} } \right] , $$ $$ \mathbf{C} = \left[ {\begin{array}{cccc} \sigma_{y_1}^2 & 0 & \dots & 0 \ 0 & \sigma_{y_2}^2 & \dots & 0 \ \vdots & \vdots & \ddots & \vdots \ 0 & 0 & \dots & \sigma_{y_1}^2 \ \end{array} } \right] , $$ where $\mathbf{Y}$ is a vector, and $\mathbf{C}$ is the covariance matrix. Ultimately, we need to solve the equation $$\mathbf{Y} = \mathbf{A}\mathbf{X}.$$ I am skipping the derivation, but the solution to this equations is: $$ \left[ {\begin{array}{c} b \ m \ \end{array} } \right] = \mathbf{X} = \left[ \mathbf{A}^T \mathbf{C}^{-1} \mathbf{A}\right]^{-1} \left[ \mathbf{A}^T \mathbf{C}^{-1} \mathbf{Y}\right].$$ As noted in Hogg, Bovy, & Lang, this procedure minimizes the $\chi^2$ function, which is the total squared error, after appropriately scaling by the uncertainties: $$ \chi^2 = \Sigma_{i = 1}^{N} \frac{[y_i - f(x_i)]^2}{\sigma_{y_i}^2} = \left[ \mathbf{Y} - \mathbf{A}\mathbf{X}\right]^{T} \mathbf{C}^{-1} \left[ \mathbf{Y} - \mathbf{A} \mathbf{X}\right].$$ Problem 2e Using the linear algebra equations above (i.e. avoid np.polyfit or any other similar functions), determine the weighted least-squares best-fit values for $b$ and $m$, the intercept and slope, respectively. Plot the results of the best-fit line. How does this compare to the above estimates? End of explanation """ p = np.polyfit( # complete print("The best-fit value for the slope and intercept are: {:.4f} and {:.4f}".format( # complete """ Explanation: Problem 2f Confirm the results of this fit are the same as those from np.polyfit. Hint - be sure to include the uncertainties. End of explanation """ x = np.array([201, 201, 287, 166, 58, 157, 146, 218, 203, 186, 160, 47, 210, 131, 202, 125, 158, 198, 165, 244]) y = np.array([592, 442, 402, 400, 173, 317, 344, 533, 495, 423, 337, 583, 479, 311, 504, 334, 416, 510, 393, 401]) sigma_y = np.array([61, 25, 15, 34, 15, 52, 22, 16, 21, 42, 31, 38, 27, 16, 14, 26, 16, 30, 14, 25]) """ Explanation: Problem 3) Are the Uncertainties Actually Gaussian? Previously we noted that there are two essential assumptions that are required for least-squares fitting to be correct. We are now going to examine the latter requirement, namely, that the uncertainties can be perfectly described as Gaussians with known variance. Earlier I stated this assumption is rarely satisfied. Why might this be the case? In my experience (meaning this is hardly universal), if it's astro, it's got systematics. While I cannot prove this, I contend that systematic uncertainties are rarely Gaussian. If you are lucky enough to be in a regime where you can be confident that the systematics are Gaussian, I further contend that it is extremely difficult to be certain that the variance of that Gaussian is known. Then there's another (astro-specific) challenge: in many circumstances, we aren't actually working with data, but rather with the results of other models applied to the data. Let's take an optical astronomy (biased, but this is LSST after all) example. What are the data? In many cases inference is being based on measurements of brightness, but the true data in this case is simply a bunch of electron counts in a CCD. The brightness (or mag) is based on the application of a model (e.g., PSF, aperture, Kron) that is applied to the data. Thus, to assume that a flux (or mag) measurement has Gaussian uncertainties with known variance is to assume that whatever flux-measurement model has been applied always produces perfectly Gaussian uncertainties (and a lot of different assumptions go into flux-measurement models...) As a demonstration associated with the challenges of these assumptions, we will examine the data set presented in Hogg, Bovy, & Lang. End of explanation """ Y = # complete # complete # complete plt.errorbar( # complete plt.plot( # complete print("The best-fit value for the slope and intercept are: {:.4f} and {:.4f}".format( # complete """ Explanation: Problem 3a Using the least-squares methodology developed in Problem 2, determine the best-fit slope and intercept for a line fit to the data above. Make a scatter plot of the data, and overplot the best-fit line. What if anything, do you notice about the data and the fit? End of explanation """ Y = # complete # complete # complete plt.errorbar( # complete plt.plot( # complete """ Explanation: Unlike the data in Problems 1 and 2, there appear to be some significant outliers (of course - this appearance of outliers is entirely dependent upon the assumption of linearity, there may actually be no outliers and a complex relation between x and y). As such, it does not appear (to me) as though the best-fit line provides a good model for the data. Problem 3b Perform a least-squares 2nd order polynomial fit to the data. Overplot the bestfit curve. How does this compare to the linear model fit? End of explanation """ # complete """ Explanation: By eye (a metric that is hardly quantitative, but nevertheless worth developing because talks never provide all of the details), the quadratic fit appears "better" than the linear fit. But, there are still "outliers" and in the realm of polynomial fitting, it is always possible to get a better fit by adding more degrees to the polynomial. Should we keep going here, or should we stop? (Again - we will discuss model selection with Adam on Friday) [As a reminder - in machine learning we'd call this low training error, but the generalization error is likely huge] How should we deal with these potential outliers? (and to re-iterate, we cannot be certain that these points are, in fact, outliers) Amazingly, if you scroll through the literature you can find solutions like the following: "We do not believe the data point at (x, y) for reasons A, B, C. Thus, we exclude that point from the fit." This, obviously, lacks any sort of rigor. If data is going to be removed, and it is worth asking if data should ever be removed, it should not be subject to the "beliefs" of an individual person or group. A more common approach that you might encounter is known as $k\sigma$ clipping, which is an iterative procedure to identify and remove outliers from a data set. The procedure is as follows: Fit the model to the data Identify any data points that are $k\sigma$ discrepant from the best-fit model Remove the discrepant points, repeat steps 1 & 2 until there are no data beyond $k\sigma$ The motivation for this procedure is the following: in a small data set (such as the one above, 20 points), the likelihood of having large $\sigma$ deviations (let's say $k = 5$) is vanishingly small. Thus, it "makes sense" to remove those points. Of course, this only makes sense if the uncertainties are truly gaussian with low variance. So again, specific, and likely untrue, assumptions have to be made. Problem 3c Develop a $k\sigma$ clipping procedure to fit a line to the data set. Set $k = 5$ and determine the best-fit line to the data. Overplot the results of the procedure on the data. How does this fit to the data look? End of explanation """ # complete """ Explanation: By eye, the results above are not that satisfying. Several of those points do look like outliers, but there are also 2 points being rejected that are well within the other cluster of data. Furthermore, the point at $(x, y) \approx (60, 170)$ was clipped in an early iteration of the algorithm, but now with the final model this point is actually within $k\sigma$ of the best-fit line. What should one do with points like this? This is one of the great problems with $k\sigma$ clipping: how does one select the appropriate value for $k$? Even if there was a good heuristic argument for selecting $k$, is there fundamentally any difference between an observation that is $k\sigma + \epsilon$ away from the model versus a point at $k\sigma - \epsilon$, where $\epsilon \ll 1$? Any choice of $k$ will automatically remove one of these points and not the other, which seems somewhat arbitrary... Problem 3d Perform the $k\sigma$ procedure on the data, but this time set $k = 7$. Plot the results as above. How do these results compare to our previous fits? End of explanation """ # complete """ Explanation: By eye, this appears superior to the previous fit. At the same time, we have not actually optimized anything to definitively show that this is the case. If there are outliers in the data, then it stands to reason that the uncertainties are likely not correctly estimated. Problem 3e Perform the $k\sigma$ procedure on the data, with $k = 5$, but the variance increased by a factor 4 (i.e. sigma_y increased by a factor of 2). Plot the results as above. How do these results compare to our previous fits? End of explanation """
tensorflow/probability
tensorflow_probability/examples/jupyter_notebooks/Gaussian_Copula.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ import numpy as np import matplotlib.pyplot as plt import tensorflow.compat.v2 as tf tf.enable_v2_behavior() import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors """ Explanation: Copulas Primer <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/probability/examples/Gaussian_Copula"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Gaussian_Copula.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Gaussian_Copula.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/probability/tensorflow_probability/examples/jupyter_notebooks/Gaussian_Copula.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> End of explanation """ class GaussianCopulaTriL(tfd.TransformedDistribution): """Takes a location, and lower triangular matrix for the Cholesky factor.""" def __init__(self, loc, scale_tril): super(GaussianCopulaTriL, self).__init__( distribution=tfd.MultivariateNormalTriL( loc=loc, scale_tril=scale_tril), bijector=tfb.NormalCDF(), validate_args=False, name="GaussianCopulaTriLUniform") # Plot an example of this. unit_interval = np.linspace(0.01, 0.99, num=200, dtype=np.float32) x_grid, y_grid = np.meshgrid(unit_interval, unit_interval) coordinates = np.concatenate( [x_grid[..., np.newaxis], y_grid[..., np.newaxis]], axis=-1) pdf = GaussianCopulaTriL( loc=[0., 0.], scale_tril=[[1., 0.8], [0., 0.6]], ).prob(coordinates) # Plot its density. plt.contour(x_grid, y_grid, pdf, 100, cmap=plt.cm.jet); """ Explanation: A [copula](https://en.wikipedia.org/wiki/Copula_(probability_theory%29) is a classical approach for capturing the dependence between random variables. More formally, a copula is a multivariate distribution $C(U_1, U_2, ...., U_n)$ such that marginalizing gives $U_i \sim \text{Uniform}(0, 1)$. Copulas are interesting because we can use them to create multivariate distributions with arbitrary marginals. This is the recipe: Using the Probability Integral Transform turns an arbitrary continuous R.V. $X$ into a uniform one $F_X(X)$, where $F_X$ is the CDF of $X$. Given a copula (say bivariate) $C(U, V)$, we have that $U$ and $V$ have uniform marginal distributions. Now given our R.V's of interest $X, Y$, create a new distribution $C'(X, Y) = C(F_X(X), F_Y(Y))$. The marginals for $X$ and $Y$ are the ones we desired. Marginals are univariate and thus may be easier to measure and/or model. A copula enables starting from marginals yet also achieving arbitrary correlation between dimensions. Gaussian Copula To illustrate how copulas are constructed, consider the case of capturing dependence according to multivariate Gaussian correlations. A Gaussian Copula is one given by $C(u_1, u_2, ...u_n) = \Phi_\Sigma(\Phi^{-1}(u_1), \Phi^{-1}(u_2), ... \Phi^{-1}(u_n))$ where $\Phi_\Sigma$ represents the CDF of a MultivariateNormal, with covariance $\Sigma$ and mean 0, and $\Phi^{-1}$ is the inverse CDF for the standard normal. Applying the normal's inverse CDF warps the uniform dimensions to be normally distributed. Applying the multivariate normal's CDF then squashes the distribution to be marginally uniform and with Gaussian correlations. Thus, what we get is that the Gaussian Copula is a distribution over the unit hypercube $[0, 1]^n$ with uniform marginals. Defined as such, the Gaussian Copula can be implemented with tfd.TransformedDistribution and appropriate Bijector. That is, we are transforming a MultivariateNormal, via the use of the Normal distribution's inverse CDF, implemented by the tfb.NormalCDF bijector. Below, we implement a Gaussian Copula with one simplifying assumption: that the covariance is parameterized by a Cholesky factor (hence a covariance for MultivariateNormalTriL). (One could use other tf.linalg.LinearOperators to encode different matrix-free assumptions.). End of explanation """ a = 2.0 b = 2.0 gloc = 0. gscale = 1. x = tfd.Kumaraswamy(a, b) y = tfd.Gumbel(loc=gloc, scale=gscale) # Plot the distributions, assuming independence x_axis_interval = np.linspace(0.01, 0.99, num=200, dtype=np.float32) y_axis_interval = np.linspace(-2., 3., num=200, dtype=np.float32) x_grid, y_grid = np.meshgrid(x_axis_interval, y_axis_interval) pdf = x.prob(x_grid) * y.prob(y_grid) # Plot its density plt.contour(x_grid, y_grid, pdf, 100, cmap=plt.cm.jet); """ Explanation: The power, however, from such a model is using the Probability Integral Transform, to use the copula on arbitrary R.V.s. In this way, we can specify arbitrary marginals, and use the copula to stitch them together. We start with a model: $$\begin{align} X &\sim \text{Kumaraswamy}(a, b) \ Y &\sim \text{Gumbel}(\mu, \beta) \end{align}$$ and use the copula to get a bivariate R.V. $Z$, which has marginals Kumaraswamy and Gumbel. We'll start by plotting the product distribution generated by those two R.V.s. This is just to serve as a comparison point to when we apply the Copula. End of explanation """ class WarpedGaussianCopula(tfd.TransformedDistribution): """Application of a Gaussian Copula on a list of target marginals. This implements an application of a Gaussian Copula. Given [x_0, ... x_n] which are distributed marginally (with CDF) [F_0, ... F_n], `GaussianCopula` represents an application of the Copula, such that the resulting multivariate distribution has the above specified marginals. The marginals are specified by `marginal_bijectors`: These are bijectors whose `inverse` encodes the CDF and `forward` the inverse CDF. block_sizes is a 1-D Tensor to determine splits for `marginal_bijectors` length should be same as length of `marginal_bijectors`. See tfb.Blockwise for details """ def __init__(self, loc, scale_tril, marginal_bijectors, block_sizes=None): super(WarpedGaussianCopula, self).__init__( distribution=GaussianCopulaTriL(loc=loc, scale_tril=scale_tril), bijector=tfb.Blockwise(bijectors=marginal_bijectors, block_sizes=block_sizes), validate_args=False, name="GaussianCopula") """ Explanation: Joint Distribution with Different Marginals Now we use a Gaussian copula to couple the distributions together, and plot that. Again our tool of choice is TransformedDistribution applying the appropriate Bijector to obtain the chosen marginals. Specifically, we use a Blockwise bijector which applies different bijectors at different parts of the vector (which is still a bijective transformation). Now we can define the Copula we want. Given a list of target marginals (encoded as bijectors), we can easily construct a new distribution that uses the copula and has the specified marginals. End of explanation """ # Create our coordinates: coordinates = np.concatenate( [x_grid[..., np.newaxis], y_grid[..., np.newaxis]], -1) def create_gaussian_copula(correlation): # Use Gaussian Copula to add dependence. return WarpedGaussianCopula( loc=[0., 0.], scale_tril=[[1., 0.], [correlation, tf.sqrt(1. - correlation ** 2)]], # These encode the marginals we want. In this case we want X_0 has # Kumaraswamy marginal, and X_1 has Gumbel marginal. marginal_bijectors=[ tfb.Invert(tfb.KumaraswamyCDF(a, b)), tfb.Invert(tfb.GumbelCDF(loc=0., scale=1.))]) # Note that the zero case will correspond to independent marginals! correlations = [0., -0.8, 0.8] copulas = [] probs = [] for correlation in correlations: copula = create_gaussian_copula(correlation) copulas.append(copula) probs.append(copula.prob(coordinates)) # Plot it's density for correlation, copula_prob in zip(correlations, probs): plt.figure() plt.contour(x_grid, y_grid, copula_prob, 100, cmap=plt.cm.jet) plt.title('Correlation {}'.format(correlation)) """ Explanation: Finally, let's actually use this Gaussian Copula. We'll use a Cholesky of $\begin{bmatrix}1 & 0\\rho & \sqrt{(1-\rho^2)}\end{bmatrix}$, which will correspond to variances 1, and correlation $\rho$ for the multivariate normal. We'll look at a few cases: End of explanation """ def kumaraswamy_pdf(x): return tfd.Kumaraswamy(a, b).prob(np.float32(x)) def gumbel_pdf(x): return tfd.Gumbel(gloc, gscale).prob(np.float32(x)) copula_samples = [] for copula in copulas: copula_samples.append(copula.sample(10000)) plot_rows = len(correlations) plot_cols = 2 # for 2 densities [kumarswamy, gumbel] fig, axes = plt.subplots(plot_rows, plot_cols, sharex='col', figsize=(18,12)) # Let's marginalize out on each, and plot the samples. for i, (correlation, copula_sample) in enumerate(zip(correlations, copula_samples)): k = copula_sample[..., 0].numpy() g = copula_sample[..., 1].numpy() _, bins, _ = axes[i, 0].hist(k, bins=100, density=True) axes[i, 0].plot(bins, kumaraswamy_pdf(bins), 'r--') axes[i, 0].set_title('Kumaraswamy from Copula with correlation {}'.format(correlation)) _, bins, _ = axes[i, 1].hist(g, bins=100, density=True) axes[i, 1].plot(bins, gumbel_pdf(bins), 'r--') axes[i, 1].set_title('Gumbel from Copula with correlation {}'.format(correlation)) """ Explanation: Finally, let's verify that we actually get the marginals we want. End of explanation """
google/jax
cloud_tpu_colabs/JAX_NeurIPS_2020_demo.ipynb
apache-2.0
import jax import jax.numpy as jnp from jax import random key = random.PRNGKey(0) key, subkey = random.split(key) x = random.normal(key, (5000, 5000)) print(x.shape) print(x.dtype) y = jnp.dot(x, x) print(y[0, 0]) x import matplotlib.pyplot as plt plt.plot(x[0]) print(jnp.dot(x, x.T)) print(jnp.dot(x, 2 * x)[[0, 2, 1, 0], ..., None, ::-1]) import numpy as np x_cpu = np.array(x) %timeit -n 5 -r 2 np.dot(x_cpu, x_cpu) %timeit -n 5 -r 5 jnp.dot(x, x).block_until_ready() """ Explanation: The basics: interactive NumPy on GPU and TPU End of explanation """ from jax import grad def f(x): if x > 0: return 2 * x ** 3 else: return 3 * x key = random.PRNGKey(0) x = random.normal(key, ()) print(grad(f)(x)) print(grad(f)(-x)) print(grad(grad(f))(-x)) print(grad(grad(grad(f)))(-x)) """ Explanation: Automatic differentiation End of explanation """ from jax import jit key = random.PRNGKey(0) x = random.normal(key, (5000, 5000)) def f(x): y = x for _ in range(10): y = y - 0.1 * y + 3. return y[:100, :100] f(x) g = jit(f) g(x) %timeit f(x).block_until_ready() %timeit -n 100 g(x).block_until_ready() grad(jit(grad(jit(grad(jnp.tanh)))))(1.0) """ Explanation: Other JAX autodiff highlights: Forward- and reverse-mode, totally composable Fast Jacobians and Hessians Complex number support (holomorphic and non-holomorphic) Jacobian pre-accumulation for elementwise operations (like gelu) For much more, see the JAX Autodiff Cookbook (Part 1). End-to-end compilation with XLA with jit End of explanation """ jax.device_count() from jax import pmap y = pmap(lambda x: x ** 2)(jnp.arange(8)) print(y) y import matplotlib.pyplot as plt plt.plot(y) """ Explanation: Parallelization over multiple accelerators with pmap End of explanation """ from functools import partial from jax.lax import psum @partial(pmap, axis_name='i') def f(x): total = psum(x, 'i') return x / total, total normalized, total = f(jnp.arange(8.)) print(f"normalized:\n{normalized}\n") print("total:", total) """ Explanation: Collective communication operations End of explanation """ from jax.experimental import sharded_jit, PartitionSpec as P from jax import lax conv = lambda image, kernel: lax.conv(image, kernel, (1, 1), 'SAME') image = jnp.ones((1, 8, 2000, 1000)).astype(np.float32) kernel = jnp.array(np.random.random((8, 8, 5, 5)).astype(np.float32)) np.set_printoptions(edgeitems=1) conv(image, kernel) %timeit conv(image, kernel).block_until_ready() image_partitions = P(1, 1, 4, 2) sharded_conv = sharded_jit(conv, in_parts=(image_partitions, None), out_parts=image_partitions) sharded_conv(image, kernel) %timeit -n 10 sharded_conv(image, kernel).block_until_ready() """ Explanation: For more, see the pmap cookbook. Automatic parallelization with sharded_jit (new!) End of explanation """
xiaoxiaoyao/MyApp
jupyter_notebook/datascience.ipynb
unlicense
import pandas as pd df = pd.read_csv("datascience.csv", encoding='gb18030') #注意它的编码是中文GB18030,不是Pandas默认设置的编码,所以此处需要显式指定编码类型,以免出现乱码错误。 # 之后看看数据框的头几行,以确认读取是否正确。 df.head() #我们看看数据框的长度,以确认数据是否读取完整。 df.shape """ Explanation: 如何用Python从海量文本抽取主题? 你在工作、学习中是否曾因信息过载叫苦不迭?有一种方法能够替你读海量文章,并将不同的主题和对应的关键词抽取出来,让你谈笑间观其大略。本文使用Python对超过1000条文本做主题抽取,一步步带你体会非监督机器学习LDA方法的魅力。想不想试试呢? 每个现代人,几乎都体会过信息过载的痛苦。文章读不过来,音乐听不过来,视频看不过来。可是现实的压力,使你又不能轻易放弃掉。 准备 pip install jieba pip install pyldavis pip install pandas,sklearn 为了处理表格数据,我们依然使用数据框工具Pandas。先调用它,然后读入我们的数据文件datascience.csv. End of explanation """ import jieba def chinese_word_cut(mytext): return " ".join(jieba.cut(mytext)) df["content_cutted"] = df.content.apply(chinese_word_cut) #执行完毕之后,我们需要查看一下,文本是否已经被正确分词。 df.content_cutted.head() #文本向量化 from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer n_features = 1000 tf_vectorizer = CountVectorizer(strip_accents = 'unicode', max_features=n_features, stop_words='english', max_df = 0.5, min_df = 10) tf = tf_vectorizer.fit_transform(df.content_cutted) """ Explanation: (1024, 3) 行列数都与我们爬取到的数量一致,通过。 分词 下面我们需要做一件重要工作——分词 我们首先调用jieba分词包。 我们此次需要处理的,不是单一文本数据,而是1000多条文本数据,因此我们需要把这项工作并行化。这就需要首先编写一个函数,处理单一文本的分词。 有了这个函数之后,我们就可以不断调用它来批量处理数据框里面的全部文本(正文)信息了。你当然可以自己写个循环来做这项工作。但这里我们使用更为高效的apply函数。如果你对这个函数有兴趣,可以点击这段教学视频查看具体的介绍。 下面这一段代码执行起来,可能需要一小段时间。请耐心等候。 End of explanation """ #应用LDA方法 from sklearn.decomposition import LatentDirichletAllocation n_topics = 5 lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=50, learning_method='online', learning_offset=50., random_state=0) #这一部分工作量较大,程序会执行一段时间,Jupyter Notebook在执行中可能暂时没有响应。等待一会儿就好,不要着急。 lda.fit(tf) #主题没有一个确定的名称,而是用一系列关键词刻画的。我们定义以下的函数,把每个主题里面的前若干个关键词显示出来: def print_top_words(model, feature_names, n_top_words): for topic_idx, topic in enumerate(model.components_): print("Topic #%d:" % topic_idx) print(" ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])) print() #定义好函数之后,我们暂定每个主题输出前20个关键词。 n_top_words = 20 #以下命令会帮助我们依次输出每个主题的关键词表: tf_feature_names = tf_vectorizer.get_feature_names() print_top_words(lda, tf_feature_names, n_top_words) """ Explanation: 我们需要人为设定主题的数量。这个要求让很多人大跌眼镜——我怎么知道这一堆文章里面多少主题?! 别着急。应用LDA方法,指定(或者叫瞎猜)主题个数是必须的。如果你只需要把文章粗略划分成几个大类,就可以把数字设定小一些;相反,如果你希望能够识别出非常细分的主题,就增大主题个数。 对划分的结果,如果你觉得不够满意,可以通过继续迭代,调整主题数量来优化。 这里我们先设定为5个分类试试。 End of explanation """ import pyLDAvis import pyLDAvis.sklearn pyLDAvis.enable_notebook() pyLDAvis.sklearn.prepare(lda, tf, tf_vectorizer) """ Explanation: 到这里,LDA已经成功帮我们完成了主题抽取。但是我知道你不是很满意,因为结果不够直观。 那咱们就让它直观一些好了。 执行以下命令,会有有趣的事情发生。 End of explanation """
Jackporter415/phys202-2015-work
assignments/assignment09/IntegrationEx01.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy import integrate """ Explanation: Integration Exercise 1 Imports End of explanation """ def trapz(f, a, b, N): """Integrate the function f(x) over the range [a,b] with N points.""" h = (b - a)/N k = np.arange(1,N) I = h*(0.5*f(a)+f(b)*0.5+f(a+k*h).sum()) return I f = lambda x: x**2 g = lambda x: np.sin(x) I = trapz(f, 0, 1, 1000) assert np.allclose(I, 0.33333349999999995) J = trapz(g, 0, np.pi, 1000) assert np.allclose(J, 1.9999983550656628) """ Explanation: Trapezoidal rule The trapezoidal rule generates a numerical approximation to the 1d integral: $$ I(a,b) = \int_a^b f(x) dx $$ by dividing the interval $[a,b]$ into $N$ subdivisions of length $h$: $$ h = (b-a)/N $$ Note that this means the function will be evaluated at $N+1$ points on $[a,b]$. The main idea of the trapezoidal rule is that the function is approximated by a straight line between each of these points. Write a function trapz(f, a, b, N) that performs trapezoidal rule on the function f over the interval $[a,b]$ with N subdivisions (N+1 points). End of explanation """ answerf = integrate.quad(f,0,1) answerg = integrate.quad(g,0,np.pi) print (answerf) print (answerg) """These results are more accurate than my trapz function. """ assert True # leave this cell to grade the previous one """ Explanation: Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz function. Print the results and errors. End of explanation """
mdpiper/topoflow-notebooks
BMI-Meteorology-P-Scalar.ipynb
mit
%matplotlib inline import numpy as np """ Explanation: Precipitation in the BMI-ed Meteorology component Goal: In this example, I want to give the Meteorology component a constant scalar precipitation value and check whether it produces output when the model state is updated. Start with an import and some magic: End of explanation """ from topoflow.components.met_base import met_component m = met_component() """ Explanation: Import the Meteorology component and create an instance: End of explanation """ cfg_file = './input/meteorology.cfg' m.initialize(cfg_file) """ Explanation: Locate the cfg file and initialize the component: End of explanation """ precip = m.get_value('atmosphere_water__precipitation_leq-volume_flux') # `P` internally print type(precip) print precip.size precip """ Explanation: Despite setting a value of 20 mm/hr for P in the cfg file, if I call get_value at this point, the model precip values are zeroed out: End of explanation """ print m.get_start_time(), m.get_current_time(), m.get_end_time() """ Explanation: Maybe this will change after the first update? Show the model start, current, and stop times: End of explanation """ m.update() print '\nCurrent time: {} s'.format(m.get_current_time()) """ Explanation: Advance the model by one time step: End of explanation """ precip = m.get_value('atmosphere_water__precipitation_leq-volume_flux') print precip """ Explanation: Note that it hasn't precipitated: End of explanation """ new_value = np.array(15, dtype=np.float64) # set_value doesn't convert to the TF type... m.set_value('atmosphere_water__precipitation_leq-volume_flux', new_value) precip = m.get_value('atmosphere_water__precipitation_leq-volume_flux') print precip """ Explanation: But this might be expected, since the initial precip value retrieved by get_value was also zero. Try manually setting the precip rate variable to an arbitrary non-zero value: End of explanation """ m.update() print '\nCurrent time: {} s'.format(m.get_current_time()) """ Explanation: Note that I can't simply give set_value a new value of 15; I need to create a one-element Numpy array with a value of 15 to match what TopoFlow needs internally. Advance the model by another time step: End of explanation """ precip = m.get_value('atmosphere_water__precipitation_leq-volume_flux') print precip """ Explanation: Is precipitation being produced? End of explanation """
dereneaton/ipyrad
newdocs/API-analysis/cookbook-popgen-sumstats.ipynb
gpl-3.0
!hostname %load_ext autoreload %autoreload 2 %matplotlib inline import ipyrad import ipyrad.analysis as ipa import ipyparallel as ipp from ipyrad.analysis.popgen import Popgen from ipyrad import Assembly from ipyrad.analysis.locus_extracter import LocusExtracter ipyclient = ipp.Client(cluster_id="popgen") print(len(ipyclient)) # popgen tools can accept either an ipyrad assembly data = ipyrad.load_json("/tmp/ipyrad-test/watdo.json") # or alternatively the path to your VCF or HDF5 formatted snps file #data = "/tmp/ipyrad-test/watdo_outfiles/watdo.snps.hdf5" imap = { "pop1" : ["1A_0", "1B_0", "1C_0", "1D_0"], "pop2" : ["2E_0", "2F_0", "2G_0", "2H_0"], "pop3" : ["3I_0", "3J_0", "3K_0", "3L_0"], } popgen = Popgen(data=data, imap=imap) popgen.samples popgen.params from IPython.display import display popgen.run(ipyclient=ipyclient) popgen.results display(popgen.results) from ipyrad.analysis.locus_extracter import LocusExtracter import ipyparallel as ipp ipyclient = ipp.Client(cluster_id="popgen") print(len(ipyclient)) lex = LocusExtracter( data=data.seqs_database, imap=imap, mincov=len(imap), # ENFORCE at least 1 per spp. ) lex.run(ipyclient=ipyclient) print(len(popgen.lex.loci)) popgen.lex.get_locus(1, as_df=True) import pandas as pd wat = pd.DataFrame() with h5py.File(data.snps_database, 'r') as io5: diffs = io5["snps"][0] != io5["snps"][1] for idx, name in enumerate(io5["snps"].attrs["names"]): wat[name.decode("utf-8")] = io5["snps"][idx] wat["1A_0"] import h5py with h5py.File(data.seqs_database, 'r') as io5: print(io5.keys()) print(io5["phymap"].attrs.keys()) print(io5["phymap"].attrs["phynames"]) print(io5["phy"][0]) """ Explanation: <h2><span style="color:gray">ipyrad-analysis toolkit:</span> Popgen summary statistics</h2> Calculate summary statistics such as pi, Tajima's D, Fst End of explanation """ from collections import Counter from itertools import combinations import numpy as np # Make a processor and give it some data loci = [lex.get_locus(x, as_df=True) for x in range(2)] proc = ipa.popgen.Processor(popgen.params, 0, loci) proc.run() #proc._pi() locus = loci[0] #locus[10][:5] = 82 #display(locus) #%timeit proc.pi(locus) print(proc.pi(locus)) print(proc.Watterson(locus)) print(proc.TajimasD(locus)) print(proc.results) """ Explanation: Development of the Processor class to calculate all the stats End of explanation """ from ipyrad.assemble.utils import DCONS import pandas as pd import itertools p1 = popgen.imap["pop1"] #locus.loc[p1, :].apply(lambda x: [DCONS[y] for y in x]) cts = np.array(locus.apply(lambda bases:\ Counter(x for x in bases if x not in [45, 78]))) snps = np.array([len(x) for x in cts]) > 1 cts = cts[snps] def dcons(counter): new = list(itertools.chain(*[DCONS[x]*ct for x, ct in counter.items()])) return Counter(new) print(cts) %timeit list(map(dcons, cts)) """ Explanation: Prototyping the dcons function to split alleles per base End of explanation """ ipyrad.analysis.popgen._calc_sumstats(popgen, 10, loci) import pickle !ls analysis-popgen/ with open("analysis-popgen/0.p", 'rb') as inp: dat = pickle.load(inp) dat """ Explanation: Loading pickled results End of explanation """ proc._process_locus_pops(locus, ["pop1", "pop3"]) pop_cts, sidxs = proc._process_locus_pops(locus, ["pop1", "pop2"]) # Between population summary statistics def _dxy(cts_a, cts_b): Dxy = 0 ncomps = 0 for cta, ctb in zip(cts_a, cts_b): ncomps += sum(list(cta.values())) *\ sum(list(ctb.values())) for ka, va in cta.items(): for kb, vb in ctb.items(): if ka == kb: continue Dxy += va*vb print(Dxy, ncomps) return Dxy/ncomps Dxy = _dxy(pop_cts["pop1"], pop_cts["pop2"]) Dxy/len(locus) %timeit proc.Dxy(locus, ["pop1", "pop2"]) """ Explanation: Prototype Dxy End of explanation """ proc._fst_full(locus) print(np.zeros(len(proc.data.imap), len(proc.data.imap))) Dxy_arr = pd.DataFrame( data=np.zeros(len(proc.data.imap), len(proc.data.imap)), index=proc.data.imap.keys(), columns=proc.data.imap.keys(), ) loci = [lex.get_locus(x, as_df=True) for x in range(100)] proc = ipa.popgen.Processor(popgen.params, 0, loci) proc.run() """ Explanation: Prototype Fst End of explanation """ import glob pickles = glob.glob(os.path.join(popgen.workdir, "*.p")) sorted(pickles, key=lambda x: int(x.rsplit("/", 1)[-1][:-2])) #pickles[0].rsplit("/", 1)[-1][:-2] pdicts = {} for pkl in pickles: with open(pkl, 'rb') as inp: pdicts[int(pkl.rsplit("/", 1)[-1][:-2])] = pickle.load(inp) pdicts[0]["pi"] #print(pdicts[0]["pi"]) pdicts[0]["Fst"].keys() full_res = {} for d in [pdicts]: full_res.update(d) full_res.keys() pidx = sorted(full_res.keys()) pi_dict = {} w_theta_dict = {} tajd_dict = {} for idx in pidx: pi_dict.update(full_res[idx]["pi"]) w_theta_dict.update(full_res[idx]["Watterson"]) tajd_dict.update(full_res[idx]["TajimasD"]) popstats = {} for pop in proc.imap: popstats[pop] = pd.DataFrame([], columns=["pi", "raw_pi", "Watterson", "raw_Watterson", "TajimasD"], index=range(len(popgen.lex.loci))) for lidx in range(len(popgen.lex.loci)): popstats[pop]["pi"].loc[lidx] = pi_dict[lidx][pop]["pi_per_base"] popstats[pop]["raw_pi"].loc[lidx] = pi_dict[lidx][pop]["pi"] popstats[pop]["Watterson"].loc[lidx] = w_theta_dict[lidx][pop]["w_theta_per_base"] popstats[pop]["raw_Watterson"].loc[lidx] = w_theta_dict[lidx][pop]["w_theta"] popstats[pop]["TajimasD"].loc[lidx] = tajd_dict[lidx][pop] lidx = sorted(full_res.keys()) for idx in lidx[:1]: for pop in proc.imap: for bidx in full_res[idx]["pi"]: print(full_res[idx]["pi"][bidx][pop]["pi_per_base"]) # pi_per_base = np.mean(full_res[idx]["pi"][idx][pop]["pi_per_base"]) # print(pop, pi_per_base) pi_dict[0] #popstats["pop1"].mean() import matplotlib.pyplot as plt import numpy as np import pandas as pd df = pd.read_csv("/tmp/gorg-tropics_sags_tableS2 - SAGs.csv") print(df.columns) set(df["Lineage"]) #df[["Genome completeness (%)", "Lineage"]] df[["Raw read count", "Lineage"]] plt.hist(df[df["Lineage"] == "AEGEAN-169"]["Genome completeness (%)"]) import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF8') fig, ax = plt.subplots(figsize=(10, 10)) for l in set(df["Lineage"]): #print(l, np.mean(df[df["Lineage"] == l]["Genome completeness (%)"])) #print(l, np.mean([locale.atoi(x) for x in df[df["Lineage"] == l]["Raw read count"]])) #print(l, np.std([locale.atoi(x) for x in df[df["Lineage"] == l]["Assembly size (bp)"]])) lmask = df[np.array(df["Lineage"] == l) + np.array(df["Genome completeness (%)"]>80)] # cmask = df[df["Genome completeness (%)" > 80]] try: alpha=0.05 if l == "AEGEAN-169": alpha=1 plt.hist(lmask["Genome completeness (%)"], alpha=alpha, label=l, bins=40) except: pass plt.xlim(80, 100) plt.legend() nsamps=10 nspecies=3 dfs = [] for idx in range(nspecies): df = pd.DataFrame([ [idx] * nsamps, range(nsamps), np.random.normal(0, 10, nsamps), np.random.normal(0, 1, nsamps), np.random.randint(0, 100, nsamps), np.random.choice(["small", "medium", "large"], nsamps), ], index=["Species_ID", "Sample_ID", "Trait1", "Trait2", "Trait3", "Trait4"]).T dfs.append(df) df = pd.concat(dfs) df.to_csv("/tmp/watdo.csv", index=False) !cat /tmp/watdo.csv pd.set_option('display.max_rows', 999) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) inf = "/home/isaac/Continuosity/NEON/NEON_seq-metabarcode-zooplankton/NEON.D03.BARC.DP1.20221.001.2019-07.expanded.20210123T023002Z.RELEASE-2021/NEON.D03.BARC.DP1.20221.001.zoo_metabarcodeTaxonomy.2019-07.expanded.20201218T153238Z.csv" df = pd.read_csv(inf) df """ Explanation: Prototyping collating stats across runs End of explanation """
moble/PostNewtonian
Waveforms/TestTensors.ipynb
mit
from __future__ import division import sympy from sympy import * from sympy import Rational as frac import simpletensors from simpletensors import Vector, TensorProduct, SymmetricTensorProduct, Tensor init_printing() var('vartheta, varphi') var('nu, m, delta, c, t') # These are related scalar functions of time var('r, v, Omega', cls=Function) r = r(t) v = v(t) Omega = Omega(t) # These get redefined momentarily, but have to exist first var('nHat, lambdaHat, ellHat', cls=Function) # And now we define them as vector functions of time nHat = Vector('nHat', r'\hat{n}', [cos(Omega*t),sin(Omega*t),0,])(t) lambdaHat = Vector('lambdaHat', r'\hat{\lambda}', [-sin(Omega*t),cos(Omega*t),0,])(t) ellHat = Vector('ellHat', r'\hat{\ell}', [0,0,1,])(t) # These are the spin functions -- first, the individual components as regular sympy.Function objects; then the vectors themselves var('S_n, S_lambda, S_ell', cls=Function) var('Sigma_n, Sigma_lambda, Sigma_ell', cls=Function) SigmaVec = Vector('SigmaVec', r'\vec{\Sigma}', [Sigma_n(t), Sigma_lambda(t), Sigma_ell(t)])(t) SVec = Vector('S', r'\vec{S}', [S_n(t), S_lambda(t), S_ell(t)])(t) """ Explanation: The basic imports and the variables we'll be using: End of explanation """ nHat diff(nHat, t) diff(lambdaHat, t) diff(lambdaHat, t).components diff(lambdaHat, t).subs(t,0).components diff(lambdaHat, t, 2).components diff(lambdaHat, t, 2).subs(t,0).components diff(ellHat, t) diff(nHat, t, 2) diff(nHat,t, 3) diff(nHat,t, 4) diff(SigmaVec,t, 0) SigmaVec.fdiff() diff(SigmaVec,t, 1) diff(SigmaVec,t, 2) diff(SigmaVec,t, 2) | nHat T1 = TensorProduct(SigmaVec, SigmaVec, ellHat, coefficient=1) T2 = TensorProduct(SigmaVec, nHat, lambdaHat, coefficient=1) tmp = Tensor(T1,T2) display(T1, T2, tmp) diff(tmp, t, 1) T1+T2 T2*ellHat ellHat*T2 T1.trace(0,1) T2*ellHat for k in range(1,4): display((T2*ellHat).trace(0,k)) for k in range(1,4): display((T2*ellHat).trace(0,k).subs(t,0)) T1.trace(0,1) * T2 """ Explanation: Examples and tests End of explanation """ display(T1, T2) T3 = SymmetricTensorProduct(SigmaVec, SigmaVec, ellHat, coefficient=1) display(T3) T3.trace(0,1) diff(T3, t, 1) T3.symmetric T3*ellHat ellHat*T3 T1+T3 T1 = SymmetricTensorProduct(SigmaVec, SigmaVec, ellHat, nHat, coefficient=1) display(T1) display(T1.trace()) T1*T2 type(_) import simpletensors isinstance(__, simpletensors.TensorProductFunction) SymmetricTensorProduct(nHat, nHat, nHat).trace() diff(T1.trace(), t, 1) diff(T1.trace(), t, 2) diff(T1.trace(), t, 2).subs(t,0) """ Explanation: Sympy can be a little tricky because it caches things, which means that the first implementation of this code silently changed tensors in place, without meaning to. Let's just check that our variables haven't changed: End of explanation """
karlstroetmann/Formal-Languages
ANTLR4-Python/Differentiator/Differentiator.ipynb
gpl-2.0
!cat -n Differentiator.g4 """ Explanation: Generating Abstract Syntax Trees Our grammar is stored in the file Differentiator.g4. The grammar describes arithmetical expression that contain variables. Furthermore, the function symbols ln (natural logarithm) and exp (exponential function) are supported. End of explanation """ !antlr4 -Dlanguage=Python3 Differentiator.g4 """ Explanation: We start by generating both scanner and parser. End of explanation """ from DifferentiatorLexer import DifferentiatorLexer from DifferentiatorParser import DifferentiatorParser import antlr4 %run ../AST-2-Dot.ipynb """ Explanation: The files CalculatorLexer.py and CalculatorParser.py contain the generated scanner and parser, respectively. We have to import these files. Furthermore, the runtime of <span style="font-variant:small-caps;">Antlr</span> needs to be imported. End of explanation """ def main(): line = input('> ') while line != '': input_stream = antlr4.InputStream(line) lexer = DifferentiatorLexer(input_stream) token_stream = antlr4.CommonTokenStream(lexer) parser = DifferentiatorParser(token_stream) context = parser.expr() term = context.result display(tuple2dot(term)) derivative = diff(term) print(toString(derivative)) line = input('> ') """ Explanation: The function main prompts for an expression that is then parsed and differentiated with respect to the variable x. End of explanation """ def diff(e): if isinstance(e, int): return '0' if e[0] == '+': f , g = e[1:] fs, gs = diff(f), diff(g) return ('+', fs, gs) if e[0] == '-': f , g = e[1:] fs, gs = diff(f), diff(g) return ('-', fs, gs) if e[0] == '*': f , g = e[1:] fs, gs = diff(f), diff(g) return ('+', ('*', fs, g), ('*', f, gs)) if e[0] == '/': f , g = e[1:] fs, gs = diff(f), diff(g) return ('/', ('-', ('*', fs, g), ('*', f, gs)), ('*', g, g)) if e[0] == 'ln': f = e[1] fs = diff(f) return ('/', fs, f) if e[0] == 'exp': f = e[1] fs = diff(f) return ('*', fs, e) if e == 'x': return '1' return '0' """ Explanation: The function diff takes the parse tree e of an arithmetic expression and differentiate this expressions e with respect to the variable x. End of explanation """ def toString(e): if isinstance(e, int): return str(e) if e[0] == '+': f, g = e[1:] return toString(f) + ' + ' + toString(g) if e[0] == '-': f, g = e[1:] return toString(f) + ' - (' + toString(g) + ')' if e[0] == '*': f, g = e[1:] return parenString(f) + ' * ' + parenString(g) if e[0] == '/': f, g = e[1:] return parenString(f) + ' / (' + toString(g) + ')' if e[0] == 'ln': return 'ln(' + toString(e[1]) + ')' if e[0] == 'exp': return 'exp(' + toString(e[1]) + ')' return str(e) """ Explanation: The function toString takes an arithmetical expression that is represented as a nested tuple and converts it into a string. End of explanation """ def parenString(e): if isinstance(e, int): return toString(e) if e[0] in ['+', '-']: return '(' + toString(e) + ')' else: return toString(e) main() !rm *.py *.tokens *.interp !rm -r __pycache__/ !ls """ Explanation: Convert e into a string that is parenthesized if necessary. End of explanation """
GoogleCloudPlatform/asl-ml-immersion
notebooks/introduction_to_tensorflow/labs/int_logistic_regression.ipynb
apache-2.0
# @title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2018 The TensorFlow Authors. End of explanation """ import os import matplotlib.pyplot as plt import tensorflow as tf print(f"TensorFlow version: {tf.__version__}") print(f"Eager execution: {tf.executing_eagerly()}") """ Explanation: Custom training: walkthrough <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/customization/custom_training_walkthrough.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/customization/custom_training_walkthrough.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/customization/custom_training_walkthrough.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> This guide uses machine learning to categorize Iris flowers by species. It uses TensorFlow to: 1. Build a model, 2. Train this model on example data, and 3. Use the model to make predictions about unknown data. TensorFlow programming This guide uses these high-level TensorFlow concepts: Use TensorFlow's default eager execution development environment, Import data with the Datasets API, Build models and layers with TensorFlow's Keras API. This tutorial is structured like many TensorFlow programs: Import and parse the dataset. Select the type of model. Train the model. Evaluate the model's effectiveness. Use the trained model to make predictions. Setup program Configure imports Import TensorFlow and the other required Python modules. By default, TensorFlow uses eager execution to evaluate operations immediately, returning concrete values instead of creating a computational graph that is executed later. If you are used to a REPL or the python interactive console, this feels familiar. End of explanation """ train_dataset_url = "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv" train_dataset_fp = tf.keras.utils.get_file( fname=os.path.basename(train_dataset_url), origin=train_dataset_url ) print(f"Local copy of the dataset file: {train_dataset_fp}") """ Explanation: The Iris classification problem Imagine you are a botanist seeking an automated way to categorize each Iris flower you find. Machine learning provides many algorithms to classify flowers statistically. For instance, a sophisticated machine learning program could classify flowers based on photographs. Our ambitions are more modest—we're going to classify Iris flowers based on the length and width measurements of their sepals and petals. The Iris genus entails about 300 species, but our program will only classify the following three: Iris setosa Iris virginica Iris versicolor <table> <tr><td> <img src="https://www.tensorflow.org/images/iris_three_species.jpg" alt="Petal geometry compared for three iris species: Iris setosa, Iris virginica, and Iris versicolor"> </td></tr> <tr><td align="center"> <b>Figure 1.</b> <a href="https://commons.wikimedia.org/w/index.php?curid=170298">Iris setosa</a> (by <a href="https://commons.wikimedia.org/wiki/User:Radomil">Radomil</a>, CC BY-SA 3.0), <a href="https://commons.wikimedia.org/w/index.php?curid=248095">Iris versicolor</a>, (by <a href="https://commons.wikimedia.org/wiki/User:Dlanglois">Dlanglois</a>, CC BY-SA 3.0), and <a href="https://www.flickr.com/photos/33397993@N05/3352169862">Iris virginica</a> (by <a href="https://www.flickr.com/photos/33397993@N05">Frank Mayfield</a>, CC BY-SA 2.0).<br/>&nbsp; </td></tr> </table> Fortunately, someone has already created a dataset of 120 Iris flowers with the sepal and petal measurements. This is a classic dataset that is popular for beginner machine learning classification problems. Import and parse the training dataset Download the dataset file and convert it into a structure that can be used by this Python program. Download the dataset Download the training dataset file using the tf.keras.utils.get_file function. This returns the file path of the downloaded file: End of explanation """ !head -n5 {train_dataset_fp} """ Explanation: Inspect the data This dataset, iris_training.csv, is a plain text file that stores tabular data formatted as comma-separated values (CSV). Use the head -n5 command to take a peek at the first five entries: End of explanation """ # column order in CSV file column_names = [ "sepal_length", "sepal_width", "petal_length", "petal_width", "species", ] feature_names = column_names[:-1] label_name = column_names[-1] print(f"Features: {feature_names}") print(f"Label: {label_name}") """ Explanation: From this view of the dataset, notice the following: The first line is a header containing information about the dataset: There are 120 total examples. Each example has four features and one of three possible label names. Subsequent rows are data records, one example per line, where: The first four fields are features: these are the characteristics of an example. Here, the fields hold float numbers representing flower measurements. The last column is the label: this is the value we want to predict. For this dataset, it's an integer value of 0, 1, or 2 that corresponds to a flower name. Let's write that out in code: End of explanation """ class_names = ["Iris setosa", "Iris versicolor", "Iris virginica"] """ Explanation: Each label is associated with string name (for example, "setosa"), but machine learning typically relies on numeric values. The label numbers are mapped to a named representation, such as: 0: Iris setosa 1: Iris versicolor 2: Iris virginica For more information about features and labels, see the ML Terminology section of the Machine Learning Crash Course. End of explanation """ batch_size = 32 train_dataset = tf.data.experimental.make_csv_dataset( train_dataset_fp, batch_size, column_names=column_names, label_name=label_name, num_epochs=1, ) """ Explanation: Create a tf.data.Dataset TensorFlow's Dataset API handles many common cases for loading data into a model. This is a high-level API for reading data and transforming it into a form used for training. Since the dataset is a CSV-formatted text file, use the tf.data.experimental.make_csv_dataset function to parse the data into a suitable format. Since this function generates data for training models, the default behavior is to shuffle the data (shuffle=True, shuffle_buffer_size=10000), and repeat the dataset forever (num_epochs=None). We also set the batch_size parameter: End of explanation """ features, labels = next(iter(train_dataset)) print(features) """ Explanation: The make_csv_dataset function returns a tf.data.Dataset of (features, label) pairs, where features is a dictionary: {'feature_name': value} These Dataset objects are iterable. Let's look at a batch of features: End of explanation """ plt.scatter( features["petal_length"], features["sepal_length"], c=labels, cmap="viridis" ) plt.xlabel("Petal length") plt.ylabel("Sepal length") plt.show() """ Explanation: Notice that like-features are grouped together, or batched. Each example row's fields are appended to the corresponding feature array. Change the batch_size to set the number of examples stored in these feature arrays. You can start to see some clusters by plotting a few features from the batch: End of explanation """ def pack_features_vector(features, labels): """Pack the features into a single array.""" features = tf.stack(list(features.values()), axis=1) return features, labels """ Explanation: To simplify the model building step, create a function to repackage the features dictionary into a single array with shape: (batch_size, num_features). This function uses the tf.stack method which takes values from a list of tensors and creates a combined tensor at the specified dimension: End of explanation """ train_dataset = train_dataset.map(pack_features_vector) """ Explanation: Then use the tf.data.Dataset#map method to pack the features of each (features,label) pair into the training dataset: End of explanation """ features, labels = next(iter(train_dataset)) print(features[:5]) """ Explanation: The features element of the Dataset are now arrays with shape (batch_size, num_features). Let's look at the first few examples: End of explanation """ model = tf.keras.Sequential( [ tf.keras.layers.Dense( 10, activation=tf.nn.relu, input_shape=(4,) ), # input shape required tf.keras.layers.Dense(10, activation=tf.nn.relu), tf.keras.layers.Dense(3), ] ) """ Explanation: Select the type of model Why model? A model is a relationship between features and the label. For the Iris classification problem, the model defines the relationship between the sepal and petal measurements and the predicted Iris species. Some simple models can be described with a few lines of algebra, but complex machine learning models have a large number of parameters that are difficult to summarize. Could you determine the relationship between the four features and the Iris species without using machine learning? That is, could you use traditional programming techniques (for example, a lot of conditional statements) to create a model? Perhaps—if you analyzed the dataset long enough to determine the relationships between petal and sepal measurements to a particular species. And this becomes difficult—maybe impossible—on more complicated datasets. A good machine learning approach determines the model for you. If you feed enough representative examples into the right machine learning model type, the program will figure out the relationships for you. Select the model We need to select the kind of model to train. There are many types of models and picking a good one takes experience. This tutorial uses a neural network to solve the Iris classification problem. Neural networks can find complex relationships between features and the label. It is a highly-structured graph, organized into one or more hidden layers. Each hidden layer consists of one or more neurons. There are several categories of neural networks and this program uses a dense, or fully-connected neural network: the neurons in one layer receive input connections from every neuron in the previous layer. For example, Figure 2 illustrates a dense neural network consisting of an input layer, two hidden layers, and an output layer: <table> <tr><td> <img src="https://www.tensorflow.org/images/custom_estimators/full_network.png" alt="A diagram of the network architecture: Inputs, 2 hidden layers, and outputs"> </td></tr> <tr><td align="center"> <b>Figure 2.</b> A neural network with features, hidden layers, and predictions.<br/>&nbsp; </td></tr> </table> When the model from Figure 2 is trained and fed an unlabeled example, it yields three predictions: the likelihood that this flower is the given Iris species. This prediction is called inference. For this example, the sum of the output predictions is 1.0. In Figure 2, this prediction breaks down as: 0.02 for Iris setosa, 0.95 for Iris versicolor, and 0.03 for Iris virginica. This means that the model predicts—with 95% probability—that an unlabeled example flower is an Iris versicolor. Create a model using Keras The TensorFlow tf.keras API is the preferred way to create models and layers. This makes it easy to build models and experiment while Keras handles the complexity of connecting everything together. The tf.keras.Sequential model is a linear stack of layers. Its constructor takes a list of layer instances, in this case, two tf.keras.layers.Dense layers with 10 nodes each, and an output layer with 3 nodes representing our label predictions. The first layer's input_shape parameter corresponds to the number of features from the dataset, and is required: End of explanation """ predictions = model(features) predictions[:5] """ Explanation: The activation function determines the output shape of each node in the layer. These non-linearities are important—without them the model would be equivalent to a single layer. There are many tf.keras.activations, but ReLU is common for hidden layers. The ideal number of hidden layers and neurons depends on the problem and the dataset. Like many aspects of machine learning, picking the best shape of the neural network requires a mixture of knowledge and experimentation. As a rule of thumb, increasing the number of hidden layers and neurons typically creates a more powerful model, which requires more data to train effectively. Using the model Let's have a quick look at what this model does to a batch of features: End of explanation """ tf.nn.softmax(predictions[:5]) """ Explanation: Here, each example returns a logit for each class. To convert these logits to a probability for each class, use the softmax function: End of explanation """ print(f"Prediction: {tf.argmax(predictions, axis=1)}") print(f" Labels: {labels}") """ Explanation: Taking the tf.argmax across classes gives us the predicted class index. But, the model hasn't been trained yet, so these aren't good predictions: End of explanation """ loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) def loss(model, x, y, training): # training=training is needed only if there are layers with different # behavior during training versus inference (e.g. Dropout). y_ = model(x, training=training) return loss_object(y_true=y, y_pred=y_) l = loss(model, features, labels, training=False) print(f"Loss test: {l}") """ Explanation: Train the model Training is the stage of machine learning when the model is gradually optimized, or the model learns the dataset. The goal is to learn enough about the structure of the training dataset to make predictions about unseen data. If you learn too much about the training dataset, then the predictions only work for the data it has seen and will not be generalizable. This problem is called overfitting—it's like memorizing the answers instead of understanding how to solve a problem. The Iris classification problem is an example of supervised machine learning: the model is trained from examples that contain labels. In unsupervised machine learning, the examples don't contain labels. Instead, the model typically finds patterns among the features. Define the loss and gradient function Both training and evaluation stages need to calculate the model's loss. This measures how off a model's predictions are from the desired label, in other words, how bad the model is performing. We want to minimize, or optimize, this value. Our model will calculate its loss using the tf.keras.losses.SparseCategoricalCrossentropy function which takes the model's class probability predictions and the desired label, and returns the average loss across the examples. End of explanation """ def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets, training=True) return loss_value, tape.gradient(loss_value, model.trainable_variables) """ Explanation: Use the tf.GradientTape context to calculate the gradients used to optimize your model: End of explanation """ optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) """ Explanation: Create an optimizer An optimizer applies the computed gradients to the model's variables to minimize the loss function. You can think of the loss function as a curved surface (see Figure 3) and we want to find its lowest point by walking around. The gradients point in the direction of steepest ascent—so we'll travel the opposite way and move down the hill. By iteratively calculating the loss and gradient for each batch, we'll adjust the model during training. Gradually, the model will find the best combination of weights and bias to minimize loss. And the lower the loss, the better the model's predictions. <table> <tr><td> <img src="https://cs231n.github.io/assets/nn3/opt1.gif" width="70%" alt="Optimization algorithms visualized over time in 3D space."> </td></tr> <tr><td align="center"> <b>Figure 3.</b> Optimization algorithms visualized over time in 3D space.<br/>(Source: <a href="http://cs231n.github.io/neural-networks-3/">Stanford class CS231n</a>, MIT License, Image credit: <a href="https://twitter.com/alecrad">Alec Radford</a>) </td></tr> </table> TensorFlow has many optimization algorithms available for training. This model uses the tf.keras.optimizers.SGD that implements the stochastic gradient descent (SGD) algorithm. The learning_rate sets the step size to take for each iteration down the hill. This is a hyperparameter that you'll commonly adjust to achieve better results. Let's setup the optimizer: End of explanation """ loss_value, grads = grad(model, features, labels) print( "Step: {}, Initial Loss: {}".format( optimizer.iterations.numpy(), loss_value.numpy() ) ) optimizer.apply_gradients(zip(grads, model.trainable_variables)) print( "Step: {}, Loss: {}".format( optimizer.iterations.numpy(), loss(model, features, labels, training=True).numpy(), ) ) """ Explanation: We'll use this to calculate a single optimization step: End of explanation """ ## Note: Rerunning this cell uses the same model variables # Keep results for plotting train_loss_results = [] train_accuracy_results = [] num_epochs = 201 for epoch in range(num_epochs): epoch_loss_avg = tf.keras.metrics.Mean() epoch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy() # Training loop - using batches of 32 for x, y in train_dataset: # Optimize the model loss_value, grads = grad(model, x, y) optimizer.apply_gradients(zip(grads, model.trainable_variables)) # Track progress epoch_loss_avg.update_state(loss_value) # Add current batch loss # Compare predicted label to actual label # training=True is needed only if there are layers with different # behavior during training versus inference (e.g. Dropout). epoch_accuracy.update_state(y, model(x, training=True)) # End epoch train_loss_results.append(epoch_loss_avg.result()) train_accuracy_results.append(epoch_accuracy.result()) if epoch % 50 == 0: print( "Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}".format( epoch, epoch_loss_avg.result(), epoch_accuracy.result() ) ) """ Explanation: Training loop With all the pieces in place, the model is ready for training! A training loop feeds the dataset examples into the model to help it make better predictions. The following code block sets up these training steps: Iterate each epoch. An epoch is one pass through the dataset. Within an epoch, iterate over each example in the training Dataset grabbing its features (x) and label (y). Using the example's features, make a prediction and compare it with the label. Measure the inaccuracy of the prediction and use that to calculate the model's loss and gradients. Use an optimizer to update the model's variables. Keep track of some stats for visualization. Repeat for each epoch. The num_epochs variable is the number of times to loop over the dataset collection. Counter-intuitively, training a model longer does not guarantee a better model. num_epochs is a hyperparameter that you can tune. Choosing the right number usually requires both experience and experimentation: End of explanation """ fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8)) fig.suptitle("Training Metrics") axes[0].set_ylabel("Loss", fontsize=14) axes[0].plot(train_loss_results) axes[1].set_ylabel("Accuracy", fontsize=14) axes[1].set_xlabel("Epoch", fontsize=14) axes[1].plot(train_accuracy_results) plt.show() """ Explanation: Visualize the loss function over time While it's helpful to print out the model's training progress, it's often more helpful to see this progress. TensorBoard is a nice visualization tool that is packaged with TensorFlow, but we can create basic charts using the matplotlib module. Interpreting these charts takes some experience, but you really want to see the loss go down and the accuracy go up: End of explanation """ test_url = ( "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv" ) test_fp = tf.keras.utils.get_file( fname=os.path.basename(test_url), origin=test_url ) test_dataset = tf.data.experimental.make_csv_dataset( test_fp, batch_size, column_names=column_names, label_name="species", num_epochs=1, shuffle=False, ) test_dataset = test_dataset.map(pack_features_vector) """ Explanation: Evaluate the model's effectiveness Now that the model is trained, we can get some statistics on its performance. Evaluating means determining how effectively the model makes predictions. To determine the model's effectiveness at Iris classification, pass some sepal and petal measurements to the model and ask the model to predict what Iris species they represent. Then compare the model's predictions against the actual label. For example, a model that picked the correct species on half the input examples has an accuracy of 0.5. Figure 4 shows a slightly more effective model, getting 4 out of 5 predictions correct at 80% accuracy: <table cellpadding="8" border="0"> <colgroup> <col span="4" > <col span="1" bgcolor="lightblue"> <col span="1" bgcolor="lightgreen"> </colgroup> <tr bgcolor="lightgray"> <th colspan="4">Example features</th> <th colspan="1">Label</th> <th colspan="1" >Model prediction</th> </tr> <tr> <td>5.9</td><td>3.0</td><td>4.3</td><td>1.5</td><td align="center">1</td><td align="center">1</td> </tr> <tr> <td>6.9</td><td>3.1</td><td>5.4</td><td>2.1</td><td align="center">2</td><td align="center">2</td> </tr> <tr> <td>5.1</td><td>3.3</td><td>1.7</td><td>0.5</td><td align="center">0</td><td align="center">0</td> </tr> <tr> <td>6.0</td> <td>3.4</td> <td>4.5</td> <td>1.6</td> <td align="center">1</td><td align="center" bgcolor="red">2</td> </tr> <tr> <td>5.5</td><td>2.5</td><td>4.0</td><td>1.3</td><td align="center">1</td><td align="center">1</td> </tr> <tr><td align="center" colspan="6"> <b>Figure 4.</b> An Iris classifier that is 80% accurate.<br/>&nbsp; </td></tr> </table> Setup the test dataset Evaluating the model is similar to training the model. The biggest difference is the examples come from a separate test set rather than the training set. To fairly assess a model's effectiveness, the examples used to evaluate a model must be different from the examples used to train the model. The setup for the test Dataset is similar to the setup for training Dataset. Download the CSV text file and parse that values, then give it a little shuffle: End of explanation """ test_accuracy = tf.keras.metrics.Accuracy() for (x, y) in test_dataset: # training=False is needed only if there are layers with different # behavior during training versus inference (e.g. Dropout). logits = model(x, training=False) prediction = tf.argmax(logits, axis=1, output_type=tf.int32) test_accuracy(prediction, y) print(f"Test set accuracy: {test_accuracy.result():.3%}") """ Explanation: Evaluate the model on the test dataset Unlike the training stage, the model only evaluates a single epoch of the test data. In the following code cell, we iterate over each example in the test set and compare the model's prediction against the actual label. This is used to measure the model's accuracy across the entire test set: End of explanation """ tf.stack([y, prediction], axis=1) """ Explanation: We can see on the last batch, for example, the model is usually correct: End of explanation """ predict_dataset = tf.convert_to_tensor( [ [ 5.1, 3.3, 1.7, 0.5, ], [ 5.9, 3.0, 4.2, 1.5, ], [6.9, 3.1, 5.4, 2.1], ] ) # training=False is needed only if there are layers with different # behavior during training versus inference (e.g. Dropout). predictions = model(predict_dataset, training=False) for i, logits in enumerate(predictions): class_idx = tf.argmax(logits).numpy() p = tf.nn.softmax(logits)[class_idx] name = class_names[class_idx] print(f"Example {i} prediction: {name} ({100 * p:4.1f}%)") """ Explanation: Use the trained model to make predictions We've trained a model and "proven" that it's good—but not perfect—at classifying Iris species. Now let's use the trained model to make some predictions on unlabeled examples; that is, on examples that contain features but not a label. In real-life, the unlabeled examples could come from lots of different sources including apps, CSV files, and data feeds. For now, we're going to manually provide three unlabeled examples to predict their labels. Recall, the label numbers are mapped to a named representation as: 0: Iris setosa 1: Iris versicolor 2: Iris virginica End of explanation """
tensorflow/docs
site/en/guide/migrate/migrating_checkpoints.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2021 The TensorFlow Authors. End of explanation """ import tensorflow as tf import tensorflow.compat.v1 as tf1 def print_checkpoint(save_path): reader = tf.train.load_checkpoint(save_path) shapes = reader.get_variable_to_shape_map() dtypes = reader.get_variable_to_dtype_map() print(f"Checkpoint at '{save_path}':") for key in shapes: print(f" (key='{key}', shape={shapes[key]}, dtype={dtypes[key].name}, " f"value={reader.get_tensor(key)})") """ Explanation: Migrating model checkpoints <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/guide/migrate/migrating_checkpoints"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/migrate/migrating_checkpoints.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/migrating_checkpoints.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/migrate/migrating_checkpoints.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Note: Checkpoints saved with tf.compat.v1.Saver are often referred as TF1 or name-based checkpoints. Checkpoints saved with tf.train.Checkpoint are referred as TF2 or object-based checkpoints. Overview This guide assumes that you have a model that saves and loads checkpoints with tf.compat.v1.Saver, and want to migrate the code use the TF2 tf.train.Checkpoint API, or use pre-existing checkpoints in your TF2 model. Below are some common scenarios that you may encounter: Scenario 1 There are existing TF1 checkpoints from previous training runs that need to be loaded or converted to TF2. To load the TF1 checkpoint in TF2, see the snippet Load a TF1 checkpoint in TF2. To convert the checkpoint to TF2, see Checkpoint conversion. Scenario 2 You are adjusting your model in a way that risks changing variable names and paths (such as when incrementally migrating away from get_variable to explicit tf.Variable creation), and would like to maintain saving/loading of existing checkpoints along the way. See the section on How to maintain checkpoint compatibility during model migration Scenario 3 You are migrating your training code and checkpoints to TF2, but your inference pipeline continues to require TF1 checkpoints for now (for production stability). Option 1 Save both TF1 and TF2 checkpoints when training. see Save a TF1 checkpoint in TF2 Option 2 Convert the TF2 checkpoint to TF1. see Checkpoint conversion The examples below show all the combinations of saving and loading checkpoints in TF1/TF2, so you have some flexibility in determining how to migrate your model. Setup End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) c = tf1.get_variable('scoped/c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.Session() as sess: saver = tf1.train.Saver() sess.run(a.assign(1)) sess.run(b.assign(2)) sess.run(c.assign(3)) saver.save(sess, 'tf1-ckpt') print_checkpoint('tf1-ckpt') a = tf.Variable(5.0, name='a') b = tf.Variable(6.0, name='b') with tf.name_scope('scoped'): c = tf.Variable(7.0, name='c') ckpt = tf.train.Checkpoint(variables=[a, b, c]) save_path_v2 = ckpt.save('tf2-ckpt') print_checkpoint(save_path_v2) """ Explanation: Changes from TF1 to TF2 This section is included if you are curious about what has changed between TF1 and TF2, and what we mean by "name-based" (TF1) vs "object-based" (TF2) checkpoints. The two types of checkpoints are actually saved in the same format, which is essentially a key-value table. The difference lies in how the keys are generated. The keys in named-based checkpoints are the names of the variables. The keys in object-based checkpoints refer to the path from the root object to the variable (the examples below will help to get a better sense of what this means). First, save some checkpoints: End of explanation """ a = tf.Variable(0.) b = tf.Variable(0.) c = tf.Variable(0.) root = ckpt = tf.train.Checkpoint(variables=[a, b, c]) print("root type =", type(root).__name__) print("root.variables =", root.variables) print("root.variables[0] =", root.variables[0]) """ Explanation: If you look at the keys in tf2-ckpt, they all refer to the object paths of each variable. For example, variable a is the first element in the variables list, so its key becomes variables/0/... (feel free to ignore the .ATTRIBUTES/VARIABLE_VALUE constant). A closer inspection of the Checkpoint object below: End of explanation """ module = tf.Module() module.d = tf.Variable(0.) test_ckpt = tf.train.Checkpoint(v={'a': a, 'b': b}, c=c, module=module) test_ckpt_path = test_ckpt.save('root-tf2-ckpt') print_checkpoint(test_ckpt_path) """ Explanation: Try experimenting with the below snippet and see how the checkpoint keys change with the object structure: End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) c = tf1.get_variable('scoped/c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.Session() as sess: saver = tf1.train.Saver() sess.run(a.assign(1)) sess.run(b.assign(2)) sess.run(c.assign(3)) save_path = saver.save(sess, 'tf1-ckpt') print_checkpoint(save_path) """ Explanation: Why does TF2 use this mechanism? Because there is no more global graph in TF2, variable names are unreliable and can be inconsistent between programs. TF2 encourages the object-oriented modelling approach where variables are owned by layers, and layers are owned by a model: variable = tf.Variable(...) layer.variable_name = variable model.layer_name = layer How to maintain checkpoint compatibility during model migration <a name="maintain-checkpoint-compat"></a> One important step in the migration process is ensuring that all variables are initialized to the correct values, which in turn allows you to validate that the ops/functions are doing the correct computations. To accomplish this, you must consider the checkpoint compatibility between models in the various stages of migration. Essentially, this section answers the question, how do I keep using the same checkpoint while changing the model. Below are three ways of maintaining checkpoint compatibility, in order of increasing flexibility: The model has the same variable names as before. The model has different variable names, and maintains a assignment map that maps variable names in the checkpoint to the new names. The model has different variable names, and maintains a TF2 Checkpoint object that stores all of the variables. When the variable names match Long title: How to re-use checkpoints when the variable names match. Short answer: You can directly load the pre-existing checkpoint with either tf1.train.Saver or tf.train.Checkpoint. If you are using tf.compat.v1.keras.utils.track_tf1_style_variables, then it will ensure that your model variable names are the same as before. You can also manually ensure that variable names match. When the variable names match in the migrated models, you may directly use either tf.train.Checkpoint or tf.compat.v1.train.Saver to load the checkpoint. Both APIs are compatible with eager and graph mode, so you can use them at any stage of the migration. Note: You can use tf.train.Checkpoint to load TF1 checkpoints, but you cannot use tf.compat.v1.Saver to load TF2 checkpoints without complicated name matching. Below are examples of using the same checkpoint with different models. First, save a TF1 checkpoint with tf1.train.Saver: End of explanation """ a = tf.Variable(0.0, name='a') b = tf.Variable(0.0, name='b') with tf.name_scope('scoped'): c = tf.Variable(0.0, name='c') # With the removal of collections in TF2, you must pass in the list of variables # to the Saver object: saver = tf1.train.Saver(var_list=[a, b, c]) saver.restore(sess=None, save_path=save_path) print(f"loaded values of [a, b, c]: [{a.numpy()}, {b.numpy()}, {c.numpy()}]") # Saving also works in eager (sess must be None). path = saver.save(sess=None, save_path='tf1-ckpt-saved-in-eager') print_checkpoint(path) """ Explanation: The example below uses tf.compat.v1.Saver to load the checkpoint while in eager mode: End of explanation """ a = tf.Variable(0.0, name='a') b = tf.Variable(0.0, name='b') with tf.name_scope('scoped'): c = tf.Variable(0.0, name='c') # Without the name_scope, name="scoped/c" works too: c_2 = tf.Variable(0.0, name='scoped/c') print("Variable names: ") print(f" a.name = {a.name}") print(f" b.name = {b.name}") print(f" c.name = {c.name}") print(f" c_2.name = {c_2.name}") # Restore the values with tf.train.Checkpoint ckpt = tf.train.Checkpoint(variables=[a, b, c, c_2]) ckpt.restore(save_path) print(f"loaded values of [a, b, c, c_2]: [{a.numpy()}, {b.numpy()}, {c.numpy()}, {c_2.numpy()}]") """ Explanation: The next snippet loads the checkpoint using the TF2 API tf.train.Checkpoint: End of explanation """ print_checkpoint('tf1-ckpt') """ Explanation: Variable names in TF2 Variables still all have a name argument you can set. Keras models also take a name argument as which they set as the prefix for their variables. The v1.name_scope function can be used to set variable name prefixes. This is very different from tf.variable_scope. It only affects names, and doesn't track variables and reuse. The tf.compat.v1.keras.utils.track_tf1_style_variables decorator is a shim that helps you maintain variable names and TF1 checkpoint compatibility, by keeping the naming and reuse semantics of tf.variable_scope and tf.compat.v1.get_variable unchanged. See the Model mapping guide for more info. Note 1: If you are using the shim, use TF2 APIs to load your checkpoints (even when using pre-trained TF1 checkpoints). See the section Checkpoint Keras. Note 2: When migrating to tf.Variable from get_variable: If your shim-decorated layer or module consists of some variables (or Keras layers/models) that use tf.Variable instead of tf.compat.v1.get_variable and get attached as properties/tracked in an object oriented way, they may have different variable naming semantics in TF1.x graphs/sessions versus during eager execution. In short, the names may not be what you expect them to be when running in TF2. Warning: Variables may have duplicate names in eager execution, which may cause problems if multiple variables in the name-based checkpoint need to be mapped to the same name. You may be able to explicitly adjust the layer and variable names using tf.name_scope and layer constructor or tf.Variable name arguments to adjust variable names and ensure there are no duplicates. Maintaining assignment maps Assignment maps are commonly used to transfer weights between TF1 models, and can also be used during your model migration if the variable names change. You can use these maps with tf.compat.v1.train.init_from_checkpoint, tf.compat.v1.train.Saver, and tf.train.load_checkpoint to load weights into models in which the variable or scope names may have changed. The examples in this section will use a previously saved checkpoint: End of explanation """ # Restoring with tf1.train.init_from_checkpoint: # A new model with a different scope for the variables. with tf.Graph().as_default() as g: with tf1.variable_scope('new_scope'): a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) c = tf1.get_variable('scoped/c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.Session() as sess: # The assignment map will remap all variables in the checkpoint to the # new scope: tf1.train.init_from_checkpoint( 'tf1-ckpt', assignment_map={'/': 'new_scope/'}) # `init_from_checkpoint` adds the initializers to these variables. # Use `sess.run` to run these initializers. sess.run(tf1.global_variables_initializer()) print("Restored [a, b, c]: ", sess.run([a, b, c])) """ Explanation: Loading with init_from_checkpoint tf1.train.init_from_checkpoint must be called while in a Graph/Session, because it places the values in the variable initializers instead of creating an assign op. You can use the assignment_map argument to configure how the variables are loaded. From the documentation: Assignment map supports following syntax: * 'checkpoint_scope_name/': 'scope_name/' - will load all variables in current scope_name from checkpoint_scope_name with matching tensor names. * 'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name' - will initialize scope_name/variable_name variable from checkpoint_scope_name/some_other_variable. * 'scope_variable_name': variable - will initialize given tf.Variable object with tensor 'scope_variable_name' from the checkpoint. * 'scope_variable_name': list(variable) - will initialize list of partitioned variables with tensor 'scope_variable_name' from the checkpoint. * '/': 'scope_name/' - will load all variables in current scope_name from checkpoint's root (e.g. no scope). End of explanation """ # Restoring with tf1.train.Saver (works in both graph and eager): # A new model with a different scope for the variables. with tf1.variable_scope('new_scope'): a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) c = tf1.get_variable('scoped/c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) # Initialize the saver with a dictionary with the original variable names: saver = tf1.train.Saver({'a': a, 'b': b, 'scoped/c': c}) saver.restore(sess=None, save_path='tf1-ckpt') print("Restored [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) """ Explanation: Loading with tf1.train.Saver Unlike init_from_checkpoint, tf.compat.v1.train.Saver runs in both graph and eager mode. The var_list argument optionally accepts a dictionary, except it must map variable names to the tf.Variable object. End of explanation """ # Restoring with tf.train.load_checkpoint (works in both graph and eager): # A new model with a different scope for the variables. with tf.Graph().as_default() as g: with tf1.variable_scope('new_scope'): a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) c = tf1.get_variable('scoped/c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.Session() as sess: # It may be easier writing a loop if your model has a lot of variables. reader = tf.train.load_checkpoint('tf1-ckpt') sess.run(a.assign(reader.get_tensor('a'))) sess.run(b.assign(reader.get_tensor('b'))) sess.run(c.assign(reader.get_tensor('scoped/c'))) print("Restored [a, b, c]: ", sess.run([a, b, c])) """ Explanation: Loading with tf.train.load_checkpoint This option is for you if you need precise control over the variable values. Again, this works in both graph and eager modes. End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(1)) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(2)) with tf1.variable_scope('scoped'): c = tf1.get_variable('c', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(3)) with tf1.Session() as sess: sess.run(tf1.global_variables_initializer()) print("[a, b, c]: ", sess.run([a, b, c])) # Save a TF2 checkpoint ckpt = tf.train.Checkpoint(unscoped=[a, b], scoped=[c]) tf2_ckpt_path = ckpt.save('tf2-ckpt') print_checkpoint(tf2_ckpt_path) """ Explanation: Maintaining a TF2 Checkpoint object If the variable and scope names may change a lot during the migration, then use tf.train.Checkpoint and TF2 checkpoints. TF2 uses the object structure instead of variable names (more details in Changes from TF1 to TF2). In short, when creating a tf.train.Checkpoint to save or restore checkpoints, make sure it uses the same ordering (for lists) and keys (for dictionaries and keyword arguments to the Checkpoint initializer). Some examples of checkpoint compatibility: ``` ckpt = tf.train.Checkpoint(foo=[var_a, var_b]) compatible with ckpt tf.train.Checkpoint(foo=[var_a, var_b]) not compatible with ckpt tf.train.Checkpoint(foo=[var_b, var_a]) tf.train.Checkpoint(bar=[var_a, var_b]) ``` The code samples below show how to use the "same" tf.train.Checkpoint to load variables with different names. First, save a TF2 checkpoint: End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a_different_name', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) b = tf1.get_variable('b_different_name', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.variable_scope('different_scope'): c = tf1.get_variable('c', shape=[], dtype=tf.float32, initializer=tf1.zeros_initializer()) with tf1.Session() as sess: sess.run(tf1.global_variables_initializer()) print("Initialized [a, b, c]: ", sess.run([a, b, c])) ckpt = tf.train.Checkpoint(unscoped=[a, b], scoped=[c]) # `assert_consumed` validates that all checkpoint objects are restored from # the checkpoint. `run_restore_ops` is required when running in a TF1 # session. ckpt.restore(tf2_ckpt_path).assert_consumed().run_restore_ops() # Removing `assert_consumed` is fine if you want to skip the validation. # ckpt.restore(tf2_ckpt_path).run_restore_ops() print("Restored [a, b, c]: ", sess.run([a, b, c])) """ Explanation: You can keep using tf.train.Checkpoint even if the variable/scope names change: End of explanation """ a = tf.Variable(0.) b = tf.Variable(0.) c = tf.Variable(0.) print("Initialized [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) # The keys "scoped" and "unscoped" are no longer relevant, but are used to # maintain compatibility with the saved checkpoints. ckpt = tf.train.Checkpoint(unscoped=[a, b], scoped=[c]) ckpt.restore(tf2_ckpt_path).assert_consumed().run_restore_ops() print("Restored [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) """ Explanation: And in eager mode: End of explanation """ # A model_fn that saves a TF1 checkpoint def model_fn_tf1_ckpt(features, labels, mode): # This model adds 2 to the variable `v` in every train step. train_step = tf1.train.get_or_create_global_step() v = tf1.get_variable('var', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) return tf.estimator.EstimatorSpec( mode, predictions=v, train_op=tf.group(v.assign_add(2), train_step.assign_add(1)), loss=tf.constant(1.), scaffold=None ) !rm -rf est-tf1 est = tf.estimator.Estimator(model_fn_tf1_ckpt, 'est-tf1') def train_fn(): return tf.data.Dataset.from_tensor_slices(([1,2,3], [4,5,6])) est.train(train_fn, steps=1) latest_checkpoint = tf.train.latest_checkpoint('est-tf1') print_checkpoint(latest_checkpoint) # A model_fn that saves a TF2 checkpoint def model_fn_tf2_ckpt(features, labels, mode): # This model adds 2 to the variable `v` in every train step. train_step = tf1.train.get_or_create_global_step() v = tf1.get_variable('var', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) ckpt = tf.train.Checkpoint(var_list={'var': v}, step=train_step) return tf.estimator.EstimatorSpec( mode, predictions=v, train_op=tf.group(v.assign_add(2), train_step.assign_add(1)), loss=tf.constant(1.), scaffold=tf1.train.Scaffold(saver=ckpt) ) !rm -rf est-tf2 est = tf.estimator.Estimator(model_fn_tf2_ckpt, 'est-tf2', warm_start_from='est-tf1') def train_fn(): return tf.data.Dataset.from_tensor_slices(([1,2,3], [4,5,6])) est.train(train_fn, steps=1) latest_checkpoint = tf.train.latest_checkpoint('est-tf2') print_checkpoint(latest_checkpoint) assert est.get_variable_value('var_list/var/.ATTRIBUTES/VARIABLE_VALUE') == 4 """ Explanation: TF2 checkpoints in Estimator The sections above describe how to maintain checkpoint compatiblity while migrating your model. These concepts also apply for Estimator models, although the way the checkpoint is saved/loaded is slightly different. As you migrate your Estimator model to use TF2 APIs, you may want to switch from TF1 to TF2 checkpoints while the model is still using the estimator. This sections shows how to do so. tf.estimator.Estimator and MonitoredSession have a saving mechanism called the scaffold, a tf.compat.v1.train.Scaffold object. The Scaffold can contain a tf1.train.Saver or tf.train.Checkpoint, which enables Estimator and MonitoredSession to save TF1- or TF2-style checkpoints. End of explanation """ a = tf.Variable(1.0, name='a') b = tf.Variable(2.0, name='b') with tf.name_scope('scoped'): c = tf.Variable(3.0, name='c') saver = tf1.train.Saver(var_list=[a, b, c]) path = saver.save(sess=None, save_path='tf1-ckpt-saved-in-eager') print_checkpoint(path) """ Explanation: The final value of v should be 16, after being warm-started from est-tf1, then trained for an additional 5 steps. The train step value doesn't carry over from the warm_start checkpoint. Checkpointing Keras Models built with Keras still use tf1.train.Saver and tf.train.Checkpoint to load pre-existing weights. When your model is fully migrated, switch to using model.save_weights and model.load_weights, especially if you are using the ModelCheckpoint callback when training. Some things you should know about checkpoints and Keras: Initialization vs Building Keras models and layers must go through two steps before being fully created. First is the initialization of the Python object: layer = tf.keras.layers.Dense(x). Second is the build step, in which most of the weights are actually created: layer.build(input_shape). You can also build a model by calling it or running a single train, eval, or predict step (the first time only). If you find that model.load_weights(path).assert_consumed() is raising an error, then it is likely that the model/layers have not been built. Keras uses TF2 checkpoints tf.train.Checkpoint(model).write is equivalent to model.save_weights. Same with tf.train.Checkpoint(model).read and model.load_weights. Note that Checkpoint(model) != Checkpoint(model=model). TF2 checkpoints work with Keras's build() step tf.train.Checkpoint.restore has a mechanism called deferred restoration which allows tf.Module and Keras objects to store variable values if the variable has not yet been created. This allows initialized models to load weights and build after. ``` m = YourKerasModel() status = m.load_weights(path) This call builds the model. The variables are created with the restored values. m.predict(inputs) status.assert_consumed() ``` Because of this mechanism, we highly recommend that you use TF2 checkpoint loading APIs with Keras models (even when restoring pre-existing TF1 checkpoints into the model mapping shims). See more in the checkpoint guide. Code Snippets The snippets below show the TF1/TF2 version compatibility in the checkpoint saving APIs. Save a TF1 checkpoint in TF2 <a name="save-tf1-in-tf2"></a> End of explanation """ a = tf.Variable(0., name='a') b = tf.Variable(0., name='b') with tf.name_scope('scoped'): c = tf.Variable(0., name='c') print("Initialized [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) saver = tf1.train.Saver(var_list=[a, b, c]) saver.restore(sess=None, save_path='tf1-ckpt-saved-in-eager') print("Restored [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) """ Explanation: Load a TF1 checkpoint in TF2 <a name="load-tf1-in-tf2"></a> End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(1)) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(2)) with tf1.variable_scope('scoped'): c = tf1.get_variable('c', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(3)) with tf1.Session() as sess: sess.run(tf1.global_variables_initializer()) ckpt = tf.train.Checkpoint( var_list={v.name.split(':')[0]: v for v in tf1.global_variables()}) tf2_in_tf1_path = ckpt.save('tf2-ckpt-saved-in-session') print_checkpoint(tf2_in_tf1_path) """ Explanation: Save a TF2 checkpoint in TF1 End of explanation """ with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) with tf1.variable_scope('scoped'): c = tf1.get_variable('c', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) with tf1.Session() as sess: sess.run(tf1.global_variables_initializer()) print("Initialized [a, b, c]: ", sess.run([a, b, c])) ckpt = tf.train.Checkpoint( var_list={v.name.split(':')[0]: v for v in tf1.global_variables()}) ckpt.restore('tf2-ckpt-saved-in-session-1').run_restore_ops() print("Restored [a, b, c]: ", sess.run([a, b, c])) """ Explanation: Load a TF2 checkpoint in TF1 End of explanation """ def convert_tf1_to_tf2(checkpoint_path, output_prefix): """Converts a TF1 checkpoint to TF2. To load the converted checkpoint, you must build a dictionary that maps variable names to variable objects. ``` ckpt = tf.train.Checkpoint(vars={name: variable}) ckpt.restore(converted_ckpt_path) ``` Args: checkpoint_path: Path to the TF1 checkpoint. output_prefix: Path prefix to the converted checkpoint. Returns: Path to the converted checkpoint. """ vars = {} reader = tf.train.load_checkpoint(checkpoint_path) dtypes = reader.get_variable_to_dtype_map() for key in dtypes.keys(): vars[key] = tf.Variable(reader.get_tensor(key)) return tf.train.Checkpoint(vars=vars).save(output_prefix) """ Explanation: Checkpoint conversion <a name="checkpoint-conversion"></a> You can convert checkpoints between TF1 and TF2 by loading and re-saving the checkpoints. An alternative is tf.train.load_checkpoint, shown in the code below. Convert TF1 checkpoint to TF2 End of explanation """ # Make sure to run the snippet in `Save a TF1 checkpoint in TF2`. print_checkpoint('tf1-ckpt-saved-in-eager') converted_path = convert_tf1_to_tf2('tf1-ckpt-saved-in-eager', 'converted-tf1-to-tf2') print("\n[Converted]") print_checkpoint(converted_path) # Try loading the converted checkpoint. a = tf.Variable(0.) b = tf.Variable(0.) c = tf.Variable(0.) ckpt = tf.train.Checkpoint(vars={'a': a, 'b': b, 'scoped/c': c}) ckpt.restore(converted_path).assert_consumed() print("\nRestored [a, b, c]: ", [a.numpy(), b.numpy(), c.numpy()]) """ Explanation: Convert the checkpoint saved in the snippet Save a TF1 checkpoint in TF2: End of explanation """ def convert_tf2_to_tf1(checkpoint_path, output_prefix): """Converts a TF2 checkpoint to TF1. The checkpoint must be saved using a `tf.train.Checkpoint(var_list={name: variable})` To load the converted checkpoint with `tf.compat.v1.Saver`: ``` saver = tf.compat.v1.train.Saver(var_list={name: variable}) # An alternative, if the variable names match the keys: saver = tf.compat.v1.train.Saver(var_list=[variables]) saver.restore(sess, output_path) ``` """ vars = {} reader = tf.train.load_checkpoint(checkpoint_path) dtypes = reader.get_variable_to_dtype_map() for key in dtypes.keys(): # Get the "name" from the if key.startswith('var_list/'): var_name = key.split('/')[1] # TF2 checkpoint keys use '/', so if they appear in the user-defined name, # they are escaped to '.S'. var_name = var_name.replace('.S', '/') vars[var_name] = tf.Variable(reader.get_tensor(key)) return tf1.train.Saver(var_list=vars).save(sess=None, save_path=output_prefix) """ Explanation: Convert TF2 checkpoint to TF1 End of explanation """ # Make sure to run the snippet in `Save a TF2 checkpoint in TF1`. print_checkpoint('tf2-ckpt-saved-in-session-1') converted_path = convert_tf2_to_tf1('tf2-ckpt-saved-in-session-1', 'converted-tf2-to-tf1') print("\n[Converted]") print_checkpoint(converted_path) # Try loading the converted checkpoint. with tf.Graph().as_default() as g: a = tf1.get_variable('a', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) b = tf1.get_variable('b', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) with tf1.variable_scope('scoped'): c = tf1.get_variable('c', shape=[], dtype=tf.float32, initializer=tf1.constant_initializer(0)) with tf1.Session() as sess: saver = tf1.train.Saver([a, b, c]) saver.restore(sess, converted_path) print("\nRestored [a, b, c]: ", sess.run([a, b, c])) """ Explanation: Convert the checkpoint saved in the snippet Save a TF2 checkpoint in TF1: End of explanation """
t-vi/candlegp
notebooks/upper_bound.ipynb
apache-2.0
%matplotlib inline import numpy from matplotlib import pyplot import pandas import sys, os sys.path.append(os.path.join(os.getcwd(),'..')) pyplot.style.use('ggplot') import IPython import torch from torch.autograd import Variable import candlegp if 0: N = 20 X = torch.rand(N,1).double() Y = (torch.sin(12*X) + 0.6*torch.cos(25*X) + torch.randn(N,1).double()*0.1+3.0).squeeze(1) pyplot.figure() pyplot.plot(X.numpy(), Y.numpy(), 'kx', mew=2) else: x = pandas.read_csv(r"data/snelson_train_inputs", header=None).as_matrix()[::4] y = pandas.read_csv(r"data/snelson_train_outputs", header=None).as_matrix()[::4] X = torch.from_numpy(x).double() Y = torch.from_numpy(y).double().squeeze() pyplot.plot(x,y,'.') X.size(), Y.size() def plot_model(m, name=""): pX = np.linspace(-3, 9, 100)[:, None] pY, pYv = m.predict_y(pX) plt.plot(X, Y, 'x') plt.plot(pX, pY) try: plt.plot(m.Z.value, m.Z.value * 0, 'o') except AttributeError: pass two_sigma = (2.0 * pYv ** 0.5)[:, 0] plt.fill_between(pX[:, 0], pY[:, 0] - two_sigma, pY[:, 0] + two_sigma, alpha=0.15) lml = -m._objective(m.get_free_state())[0] plt.title("%s (lml = %f)" % (name, lml)) return lml """ Explanation: Discussion of the GP marginal likelihood upper bound Mark van der Wilk, Augustus 2017 Adapted to Pytorch by Thomas Viehmann See gp_upper for code to tighten the upper bound through optimisation, and a more comprehensive discussion. End of explanation """ def optimize(m, lr=5e-3, it=50): opt = torch.optim.LBFGS(m.parameters(), lr=lr, max_iter=40) def eval_model(): obj = m() opt.zero_grad() obj.backward() return obj for i in range(it): obj = m() opt.zero_grad() obj.backward() opt.step(eval_model) if i%5==0: print(i,':',obj.data[0]) return -obj.data[0] k = candlegp.kernels.RBF(1, lengthscales=torch.DoubleTensor([1.0]),variance=torch.DoubleTensor([1.0])) m = candlegp.models.GPR(Variable(X), Variable(Y.unsqueeze(1)), kern=k) #m.likelihood.variance.set(0.01) full_lml = optimize(m, lr=1e-2) xstar = torch.linspace(-3,9,100).double() mu, var = m.predict_y(Variable(xstar.unsqueeze(1))) cred_size = (var**0.5*2).squeeze(1) mu = mu.squeeze(1) pyplot.plot(xstar.numpy(),mu.data.numpy(),'b') pyplot.fill_between(xstar.numpy(),mu.data.numpy()+cred_size.data.numpy(), mu.data.numpy()-cred_size.data.numpy(),facecolor='0.75') pyplot.plot(X.numpy(), Y.numpy(), 'kx', mew=2) m """ Explanation: Full model End of explanation """ Ms = numpy.arange(4, 20, 2) vfe_lml = [] vupper_lml = [] vfe_hyps = [] for M in Ms: Zinit = X[:M, :].clone() k = candlegp.kernels.RBF(1, lengthscales=torch.DoubleTensor([1.0]),variance=torch.DoubleTensor([1.0])) m = candlegp.models.SGPR(Variable(X), Variable(Y.unsqueeze(1)), k, Zinit) m.likelihood.variance.set(0.01) optimize(m, lr=1e-3, it=100) vfe_lml.append(-m.objective().data[0]) vupper_lml.append(m.compute_upper_bound().data[0]) vfe_hyps.append(m.state_dict()) print("%i" % M, end=" ") IPython.display.clear_output() pyplot.figure() pyplot.plot(Ms[:len(vfe_lml)], vfe_lml, label="lower") pyplot.plot(Ms[:len(vfe_lml)], vupper_lml, label="upper") pyplot.axhline(full_lml, label="full", alpha=0.3) pyplot.xlabel("Number of inducing points") pyplot.ylabel("LML estimate") pyplot.legend() pyplot.title("LML bounds for models trained with SGPR") pyplot.xlim(4,20) pyplot.show() vfe_hyps = pandas.DataFrame(vfe_hyps) """ Explanation: Upper bounds for sparse variational models As a first investigation, we compute the upper bound for models trained using the sparse variational GP approximation. End of explanation """ fMs = numpy.arange(3, 20, 1) fvfe_lml = [] # Fixed vfe lml fvupper_lml = [] # Fixed upper lml for M in fMs: Zinit = vfe.Z.value[:M, :].copy() Zinit = np.vstack((Zinit, X[np.random.permutation(len(X))[:(M - len(Zinit))], :].copy())) init_params = vfe.get_parameter_dict() init_params['model.Z'] = Zinit vfe = gpflow.models.SGPR(X, Y, gpflow.kernels.RBF(1), Zinit) vfe.set_parameter_dict(init_params) vfe.kern.fixed = True vfe.likelihood.fixed = True vfe.optimize() fvfe_lml.append(-vfe._objective(vfe.get_free_state())[0]) fvupper_lml.append(vfe.compute_upper_bound()) print("%i" % M, end=" ") plt.plot(fMs, fvfe_lml, label="lower") plt.plot(fMs, fvupper_lml, label="upper") plt.axhline(full_lml, label="full", alpha=0.3) plt.xlabel("Number of inducing points") plt.ylabel("LML estimate") plt.legend() """ Explanation: We see that the lower bound increases as more inducing points are added. Note that the upper bound does not monotonically decrease! This is because as we train the sparse model, we also get better estimates of the hyperparameters. The upper bound will be different for this different setting of the hyperparameters, and is sometimes looser. The upper bound also converges to the true lml slower than the lower bound. Upper bounds for fixed hyperparameters Here, we train sparse models with the hyperparameters fixed to the optimal value found previously. End of explanation """ vfe = gpflow.models.SGPR(X, Y, gpflow.kernels.RBF(1), X[None, 0, :].copy()) vfe.optimize() print("Lower bound: %f" % -vfe._objective(vfe.get_free_state())[0]) print("Upper bound: %f" % vfe.compute_upper_bound()) """ Explanation: Now, as the hyperparameters are fixed, the bound does monotonically decrease. We chose the optimal hyperparameters here, but the picture should be the same for any hyperparameter setting. This shows that we increasingly get a better estimate of the marginal likelihood as we add more inducing points. A tight estimate bound does not imply a converged model End of explanation """ vfe """ Explanation: In this case we show that for the hyperparameter setting, the bound is very tight. However, this does not imply that we have enough inducing points, but simply that we have correctly identified the marginal likelihood for this particular hyperparameter setting. In this specific case, where we used a single inducing point, the model collapses to not using the GP at all (lengthscale is really long to model only the mean). The rest of the variance is explained by noise. This GP can be perfectly approximated with a single inducing point. End of explanation """
leosartaj/scipy-2016-tutorial
tutorial_exercises/02-Solve-Subs-Plot.ipynb
bsd-3-clause
solveset(x**2 - 4, x) """ Explanation: Solveset Equation solving is both a common need also a common building block for more complicated symbolic algorithms. Here we introduce the solveset function. End of explanation """ solveset(x**2 - 9 == 0, x) """ Explanation: Solveset takes two arguments and one optional argument specifying the domain, an equation like $x^2 - 4$ and a variable on which we want to solve, like $x$ and an optional argument domain specifying the region in which we want to solve. Solveset returns the values of the variable, $x$, for which the equation, $x^2 - 4$ equals 0. Exercise What would the following code produce? Are you sure? End of explanation """ solveset(sin(x), x) """ Explanation: Infinite Solutions One of the major improvements of solveset is that it also supports infinite solution. End of explanation """ solveset(exp(x) -1, x) """ Explanation: Domain argument End of explanation """ solveset(exp(x) -1, x, domain=S.Reals) """ Explanation: solveset by default solves everything in the complex domain. In complex domain $exp(x) == cos(x) + i\ sin(x)$ and solution is basically equal to solution to $cos(x) == 1$. If you want only real solution, you can specify the domain as S.Reals. End of explanation """ height, width, area = symbols('height, width, area') solveset(area - height*width, height) """ Explanation: Symbolic use of solveset Results of solveset don't need to be numeric, like {-2, 2}. We can use solveset to perform algebraic manipulations. For example if we know a simple equation for the area of a square area = height * width we can solve this equation for any of the variables. For example how would we solve this system for the height, given the area and width? End of explanation """ # Solve for the radius of a sphere, given the volume """ Explanation: Note that we would have liked to have written solveset(area == height * width, height) But the == gotcha bites us. Instead we remember that solveset expects an expression that is equal to zero, so we rewrite the equation area = height * width into the equation 0 = height * width - area and that is what we give to solveset. Exercise Compute the radius of a sphere, given the volume. Reminder, the volume of a sphere of radius r is given by $$ V = \frac{4}{3}\pi r^3 $$ End of explanation """ x**2 # Replace x with y (x**2).subs({x: y}) """ Explanation: You will probably get several solutions, this is fine. The first one is probably the one that you want. Substitution We often want to substitute in one expression for another. For this we use the subs method End of explanation """ # Replace x with sin(x) """ Explanation: Exercise Subsitute $x$ for $sin(x)$ in the equation $x^2 + 2\cdot x + 1$ End of explanation """ # Solve for the height of a rectangle given area and width soln = list(solveset(area - height*width, height))[0] soln # Define perimeter of rectangle in terms of height and width perimeter = 2*(height + width) # Substitute the solution for height into the expression for perimeter perimeter.subs({height: soln}) """ Explanation: Subs + Solveset We can use subs and solve together to plug the solution of one equation into another End of explanation """ V, r = symbols('V,r', real=True) 4*pi/3 * r**3 list(solveset(V - 4*pi/3 * r**3, r))[0] """ Explanation: Exercise In the last section you solved for the radius of a sphere given its volume End of explanation """ (?).subs(?) """ Explanation: Now lets compute the surface area of a sphere in terms of the volume. Recall that the surface area of a sphere is given by $$ 4 \pi r^2 $$ End of explanation """ %matplotlib inline plot(x**2) """ Explanation: Does the expression look right? How would you expect the surface area to scale with respect to the volume? What is the exponent on $V$? Plotting SymPy can plot expressions easily using the plot function. By default this links against matplotlib. End of explanation """ plot(?) """ Explanation: Exercise In the last exercise you derived a relationship between the volume of a sphere and the surface area. Plot this relationship using plot. End of explanation """ textplot(x**2, -3, 3) """ Explanation: Low dependencies You may know that SymPy tries to be a very low-dependency project. Our user base is very broad. Some entertaining aspects result. For example, textplot. End of explanation """
Kaggle/learntools
notebooks/embeddings/raw/4-exercises.ipynb
apache-2.0
import os import numpy as np import pandas as pd from matplotlib import pyplot as plt import matplotlib as mpl from learntools.core import binder; binder.bind(globals()) from learntools.embeddings.ex4_tsne import * #_RM_ input_dir = '.' #_UNCOMMENT_ #input_dir = '../input/visualizing-embeddings-with-t-sne' csv_path = os.path.join(input_dir, 'movies_tsne.csv') df = pd.read_csv(csv_path, index_col=0) """ Explanation: Exercise (t-SNE) One practical application of visualizing trained embeddings with t-SNE is understanding what information about the embedded entities our model has (and hasn't) learned. This can give us some intuition about how our model works, what latent features it thinks are useful, whether adding certain additional data explicitly might improve the model's accuracy, and so on. In the tutorial, we briefly explored the question of whether our embeddings were sensitive to genre. In this exercise, we'll see if we can identify patterns in our 2-d embedding space when we group or filter by some other movie metadata. To get started, run the code cell below to import the necessary libraries, and load a copy of the t-SNE mapping we learned in the lesson. End of explanation """ FS = (13, 9) fig, ax = plt.subplots(figsize=FS) c = np.random.rand(len(df)) pts = ax.scatter(df.x, df.y, c=c) cbar = fig.colorbar(pts) #%%RM_IF(PROD)%% # Correct (solution code) FS = (13, 9) fig, ax = plt.subplots(figsize=FS) c = df.year pts = ax.scatter(df.x, df.y, c=c) cbar = fig.colorbar(pts) #%%RM_IF(PROD)%% # Custom cmap FS = (13, 9) fig, ax = plt.subplots(figsize=FS) c = df.year pts = ax.scatter(df.x, df.y, c=c, cmap='cubehelix') cbar = fig.colorbar(pts) #%%RM_IF(PROD)%% # Solution w/ sampling FS = (13, 9) fig, ax = plt.subplots(figsize=FS) n = 2000 _df = df.sample(n, random_state=1).copy() c = _df.year pts = ax.scatter(_df.x, _df.y, c=c) cbar = fig.colorbar(pts) """ Explanation: 1. Release year The code cell below shows how we can use the c keyword arg of Axes.scatter to specify a color for each point of a scatter plot. Right now, we're graphing the positions of our movie embeddings (after t-SNE dimensionality reduction) and assigning color randomly. Update the code below so that a movie's point is colored according to its year of release. End of explanation """ #_COMMENT_IF(PROD)_ part1.solution() """ Explanation: Are our movie embeddings sensitive to year? Is there a global pattern to year of release in our t-SNE mapping? i.e. is it possible to draw a straight line through our embeddings such that year tends to increase as we move in that direction? Bonus If you'd like to push yourself further, try some of the following exercises: Try experimenting with different color maps, using the cmap keyword argument to scatter. You can browse the colormaps that ship with matplotlib here. Do different colormaps offer different insights into the data? What if you use one of the "qualitative colormaps"? By default, the smallest and largest numerical values in the data are mapped to the extremes of our colormap. In the case of year, the earliest movie in our dataset is from 1902, but there are very few movies in the first few decades of the 20th century. Would our results be easier to interpret if we started our colormap at 1930 or 1940? Give it a try. Hint: check out the norm argument to ax.scatter and the documentation for matplotlib.colors.Normalize. Can you identify any exceptions to the overall trend in your graph? Try zooming in on the area of an anomaly and looking at the labels of the points. How many movies make up the anomaly? Do you have a hypothesis about why our algorithm would have placed them there? (Suggestion: try reusing some of the helper functions defined in the tutorial such as plot_region) End of explanation """ # Your code goes here """ Explanation: 2. Average rating This is a very salient question for our problem of predicting user-assigned ratings. Does a movie's "goodness" or "badness", as measured by its average user rating, manifest in its embedding? To find out, create a scatter plot of our movie embeddings where a movie's color is set according to its mean rating. Hint: Use the code from part 1 as a model. End of explanation """ #_COMMENT_IF(PROD)_ part2.hint() #%%RM_IF(PROD)%% FS = (13, 9) fig, ax = plt.subplots(figsize=FS) c = df.mean_rating pts = ax.scatter(df.x, df.y, c=c, cmap='cubehelix') cbar = fig.colorbar(pts) #_COMMENT_IF(PROD)_ part2.solution() """ Explanation: Again, is there a global pattern to the distribution of mean rating? End of explanation """ fig, ax = plt.subplots(figsize=FS) c = df.n_ratings pts = ax.scatter(df.x, df.y, c=c) cbar = fig.colorbar(pts) """ Explanation: Bonus: Some movies are divisive - you either love them, or you hate them. Is this reflected in our embeddings? You'll have to come up with a way to calculate a measure of how 'spread out' the user ratings are for each movie. 3. Number of ratings Do our embeddings reflect the number of ratings we have in the dataset for each movie? (We might think of this as a proxy for how popular or obscure a movie is.) Run the code cell below to generate a visualization similar to the previous two, this time using color to represent number of ratings: End of explanation """ part3.solution() #%%RM_IF(PROD)%% # Solution code fig, ax = plt.subplots(figsize=FS) c = df.n_ratings pts = ax.scatter(df.x, df.y, c=c, norm=mpl.colors.LogNorm()) cbar = fig.colorbar(pts) """ Explanation: Yikes, this is pretty hard to read. Most of our movies have on the order of hundreds of ratings, but there's also a long tail of movies with tends of thousands of ratings, which makes a linear scale a poor choice. Try improving the visualization above to help us answer our original question: are our embeddings sensitive to number of ratings? (And to what degree is the trend global vs. local?) Hint: Check out the norm keyword argument to Axes.scatter. End of explanation """
afronski/playground-notes
scalable-machine-learning/solutions/ML_lab3_linear_reg_student.ipynb
mit
labVersion = 'cs190_week3_v_1_2' """ Explanation: Linear Regression Lab This lab covers a common supervised learning pipeline, using a subset of the Million Song Dataset from the UCI Machine Learning Repository. Our goal is to train a linear regression model to predict the release year of a song given a set of audio features. This lab will cover: Part 1: Read and parse the initial dataset Visualization 1: Features Visualization 2: Shifting labels Part 2: Create and evaluate a baseline model Visualization 3: Predicted vs. actual Part 3: Train (via gradient descent) and evaluate a linear regression model Visualization 4: Training error Part 4: Train using MLlib and tune hyperparameters via grid search Visualization 5: Best model's predictions Visualization 6: Hyperparameter heat map Part 5: Add interactions between features Note that, for reference, you can look up the details of the relevant Spark methods in Spark's Python API and the relevant NumPy methods in the NumPy Reference End of explanation """ # load testing library from test_helper import Test import os.path baseDir = os.path.join('data') inputPath = os.path.join('cs190', 'millionsong.txt') fileName = os.path.join(baseDir, inputPath) numPartitions = 2 rawData = sc.textFile(fileName, numPartitions) numPoints = rawData.count() print numPoints samplePoints = rawData.take(5) print samplePoints # TEST Load and check the data (1a) Test.assertEquals(numPoints, 6724, 'incorrect value for numPoints') Test.assertEquals(len(samplePoints), 5, 'incorrect length for samplePoints') """ Explanation: Part 1: Read and parse the initial dataset (1a) Load and check the data The raw data is currently stored in text file. We will start by storing this raw data in as an RDD, with each element of the RDD representing a data point as a comma-delimited string. Each string starts with the label (a year) followed by numerical audio features. Use the count method to check how many data points we have. Then use the take method to create and print out a list of the first 5 data points in their initial string format. End of explanation """ from pyspark.mllib.regression import LabeledPoint import numpy as np # Here is a sample raw data point: # '2001.0,0.884,0.610,0.600,0.474,0.247,0.357,0.344,0.33,0.600,0.425,0.60,0.419' # In this raw data point, 2001.0 is the label, and the remaining values are features def parsePoint(line): """Converts a comma separated unicode string into a `LabeledPoint`. Args: line (unicode): Comma separated unicode string where the first element is the label and the remaining elements are features. Returns: LabeledPoint: The line is converted into a `LabeledPoint`, which consists of a label and features. """ features = line.split(',') return LabeledPoint(features[0], features[1:]) parsedSamplePoints = rawData.map(parsePoint) firstPointFeatures = parsedSamplePoints.take(1)[0].features firstPointLabel = parsedSamplePoints.take(1)[0].label print firstPointFeatures, firstPointLabel d = len(firstPointFeatures) print d # TEST Using LabeledPoint (1b) Test.assertTrue(isinstance(firstPointLabel, float), 'label must be a float') expectedX0 = [0.8841,0.6105,0.6005,0.4747,0.2472,0.3573,0.3441,0.3396,0.6009,0.4257,0.6049,0.4192] Test.assertTrue(np.allclose(expectedX0, firstPointFeatures, 1e-4, 1e-4), 'incorrect features for firstPointFeatures') Test.assertTrue(np.allclose(2001.0, firstPointLabel), 'incorrect label for firstPointLabel') Test.assertTrue(d == 12, 'incorrect number of features') """ Explanation: (1b) Using LabeledPoint In MLlib, labeled training instances are stored using the LabeledPoint object. Write the parsePoint function that takes as input a raw data point, parses it using Python's unicode.split method, and returns a LabeledPoint. Use this function to parse samplePoints (from the previous question). Then print out the features and label for the first training point, using the LabeledPoint.features and LabeledPoint.label attributes. Finally, calculate the number features for this dataset. Note that split() can be called directly on a unicode or str object. For example, u'split,me'.split(',') returns [u'split', u'me']. End of explanation """ import matplotlib.pyplot as plt import matplotlib.cm as cm sampleMorePoints = rawData.take(50) # You can uncomment the line below to see randomly selected features. These will be randomly # selected each time you run the cell. Note that you should run this cell with the line commented # out when answering the lab quiz questions. # sampleMorePoints = rawData.takeSample(False, 50) parsedSampleMorePoints = map(parsePoint, sampleMorePoints) dataValues = map(lambda lp: lp.features.toArray(), parsedSampleMorePoints) def preparePlot(xticks, yticks, figsize=(10.5, 6), hideLabels=False, gridColor='#999999', gridWidth=1.0): """Template for generating the plot layout.""" plt.close() fig, ax = plt.subplots(figsize=figsize, facecolor='white', edgecolor='white') ax.axes.tick_params(labelcolor='#999999', labelsize='10') for axis, ticks in [(ax.get_xaxis(), xticks), (ax.get_yaxis(), yticks)]: axis.set_ticks_position('none') axis.set_ticks(ticks) axis.label.set_color('#999999') if hideLabels: axis.set_ticklabels([]) plt.grid(color=gridColor, linewidth=gridWidth, linestyle='-') map(lambda position: ax.spines[position].set_visible(False), ['bottom', 'top', 'left', 'right']) return fig, ax # generate layout and plot fig, ax = preparePlot(np.arange(.5, 11, 1), np.arange(.5, 49, 1), figsize=(8,7), hideLabels=True, gridColor='#eeeeee', gridWidth=1.1) image = plt.imshow(dataValues,interpolation='nearest', aspect='auto', cmap=cm.Greys) for x, y, s in zip(np.arange(-.125, 12, 1), np.repeat(-.75, 12), [str(x) for x in range(12)]): plt.text(x, y, s, color='#999999', size='10') plt.text(4.7, -3, 'Feature', color='#999999', size='11'), ax.set_ylabel('Observation') pass """ Explanation: Visualization 1: Features First we will load and setup the visualization library. Then we will look at the raw features for 50 data points by generating a heatmap that visualizes each feature on a grey-scale and shows the variation of each feature across the 50 sample data points. The features are all between 0 and 1, with values closer to 1 represented via darker shades of grey. End of explanation """ parsedDataInit = rawData.map(parsePoint) onlyLabels = parsedDataInit.map(lambda r: r.label) minYear = onlyLabels.min() maxYear = onlyLabels.max() print maxYear, minYear # TEST Find the range (1c) Test.assertEquals(len(parsedDataInit.take(1)[0].features), 12, 'unexpected number of features in sample point') sumFeatTwo = parsedDataInit.map(lambda lp: lp.features[2]).sum() Test.assertTrue(np.allclose(sumFeatTwo, 3158.96224351), 'parsedDataInit has unexpected values') yearRange = maxYear - minYear Test.assertTrue(yearRange == 89, 'incorrect range for minYear to maxYear') """ Explanation: (1c) Find the range Now let's examine the labels to find the range of song years. To do this, first parse each element of the rawData RDD, and then find the smallest and largest labels. End of explanation """ parsedData = parsedDataInit.map(lambda r: LabeledPoint(r.label - minYear, r.features)) # Should be a LabeledPoint print type(parsedData.take(1)[0]) # View the first point print '\n{0}'.format(parsedData.take(1)) # TEST Shift labels (1d) oldSampleFeatures = parsedDataInit.take(1)[0].features newSampleFeatures = parsedData.take(1)[0].features Test.assertTrue(np.allclose(oldSampleFeatures, newSampleFeatures), 'new features do not match old features') sumFeatTwo = parsedData.map(lambda lp: lp.features[2]).sum() Test.assertTrue(np.allclose(sumFeatTwo, 3158.96224351), 'parsedData has unexpected values') minYearNew = parsedData.map(lambda lp: lp.label).min() maxYearNew = parsedData.map(lambda lp: lp.label).max() Test.assertTrue(minYearNew == 0, 'incorrect min year in shifted data') Test.assertTrue(maxYearNew == 89, 'incorrect max year in shifted data') """ Explanation: (1d) Shift labels As we just saw, the labels are years in the 1900s and 2000s. In learning problems, it is often natural to shift labels such that they start from zero. Starting with parsedDataInit, create a new RDD consisting of LabeledPoint objects in which the labels are shifted such that smallest label equals zero. End of explanation """ # get data for plot oldData = (parsedDataInit .map(lambda lp: (lp.label, 1)) .reduceByKey(lambda x, y: x + y) .collect()) x, y = zip(*oldData) # generate layout and plot data fig, ax = preparePlot(np.arange(1920, 2050, 20), np.arange(0, 150, 20)) plt.scatter(x, y, s=14**2, c='#d6ebf2', edgecolors='#8cbfd0', alpha=0.75) ax.set_xlabel('Year'), ax.set_ylabel('Count') pass # get data for plot newData = (parsedData .map(lambda lp: (lp.label, 1)) .reduceByKey(lambda x, y: x + y) .collect()) x, y = zip(*newData) # generate layout and plot data fig, ax = preparePlot(np.arange(0, 120, 20), np.arange(0, 120, 20)) plt.scatter(x, y, s=14**2, c='#d6ebf2', edgecolors='#8cbfd0', alpha=0.75) ax.set_xlabel('Year (shifted)'), ax.set_ylabel('Count') pass """ Explanation: Visualization 2: Shifting labels We will look at the labels before and after shifting them. Both scatter plots below visualize tuples storing i) a label value and ii) the number of training points with this label. The first scatter plot uses the initial labels, while the second one uses the shifted labels. Note that the two plots look the same except for the labels on the x-axis. End of explanation """ weights = [.8, .1, .1] seed = 42 parsedTrainData, parsedValData, parsedTestData = parsedData.randomSplit(weights, seed) parsedTrainData.cache() parsedValData.cache() parsedTestData.cache() nTrain = parsedTrainData.count() nVal = parsedValData.count() nTest = parsedTestData.count() print nTrain, nVal, nTest, nTrain + nVal + nTest print parsedData.count() # TEST Training, validation, and test sets (1e) Test.assertEquals(parsedTrainData.getNumPartitions(), numPartitions, 'parsedTrainData has wrong number of partitions') Test.assertEquals(parsedValData.getNumPartitions(), numPartitions, 'parsedValData has wrong number of partitions') Test.assertEquals(parsedTestData.getNumPartitions(), numPartitions, 'parsedTestData has wrong number of partitions') Test.assertEquals(len(parsedTrainData.take(1)[0].features), 12, 'parsedTrainData has wrong number of features') sumFeatTwo = (parsedTrainData .map(lambda lp: lp.features[2]) .sum()) sumFeatThree = (parsedValData .map(lambda lp: lp.features[3]) .reduce(lambda x, y: x + y)) sumFeatFour = (parsedTestData .map(lambda lp: lp.features[4]) .reduce(lambda x, y: x + y)) Test.assertTrue(np.allclose([sumFeatTwo, sumFeatThree, sumFeatFour], 2526.87757656, 297.340394298, 184.235876654), 'parsed Train, Val, Test data has unexpected values') Test.assertTrue(nTrain + nVal + nTest == 6724, 'unexpected Train, Val, Test data set size') Test.assertEquals(nTrain, 5371, 'unexpected value for nTrain') Test.assertEquals(nVal, 682, 'unexpected value for nVal') Test.assertEquals(nTest, 671, 'unexpected value for nTest') """ Explanation: (1e) Training, validation, and test sets We're almost done parsing our dataset, and our final task involves split it into training, validation and test sets. Use the randomSplit method with the specified weights and seed to create RDDs storing each of these datasets. Next, cache each of these RDDs, as we will be accessing them multiple times in the remainder of this lab. Finally, compute the size of each dataset and verify that the sum of their sizes equals the value computed in Part (1a). End of explanation """ averageTrainYear = (parsedTrainData .map(lambda r: r.label) .sum()) / nTrain print averageTrainYear # TEST Average label (2a) Test.assertTrue(np.allclose(averageTrainYear, 53.9316700801), 'incorrect value for averageTrainYear') """ Explanation: Part 2: Create and evaluate a baseline model (2a) Average label A very simple yet natural baseline model is one where we always make the same prediction independent of the given data point, using the average label in the training set as the constant prediction value. Compute this value, which is the average (shifted) song year for the training set. Use an appropriate method in the RDD API. End of explanation """ import math def squaredError(label, prediction): """Calculates the the squared error for a single prediction. Args: label (float): The correct value for this observation. prediction (float): The predicted value for this observation. Returns: float: The difference between the `label` and `prediction` squared. """ return (label - prediction) ** 2 def calcRMSE(labelsAndPreds): """Calculates the root mean squared error for an `RDD` of (label, prediction) tuples. Args: labelsAndPred (RDD of (float, float)): An `RDD` consisting of (label, prediction) tuples. Returns: float: The square root of the mean of the squared errors. """ return math.sqrt(labelsAndPreds.map(lambda (a, b): squaredError(a, b)).sum() / labelsAndPreds.count()) labelsAndPreds = sc.parallelize([(3., 1.), (1., 2.), (2., 2.)]) # RMSE = sqrt[((3-1)^2 + (1-2)^2 + (2-2)^2) / 3] = 1.291 exampleRMSE = calcRMSE(labelsAndPreds) print exampleRMSE # TEST Root mean squared error (2b) Test.assertTrue(np.allclose(squaredError(3, 1), 4.), 'incorrect definition of squaredError') Test.assertTrue(np.allclose(exampleRMSE, 1.29099444874), 'incorrect value for exampleRMSE') """ Explanation: (2b) Root mean squared error We naturally would like to see how well this naive baseline performs. We will use root mean squared error (RMSE) for evaluation purposes. Implement a function to compute RMSE given an RDD of (label, prediction) tuples, and test out this function on an example. End of explanation """ labelsAndPredsTrain = parsedTrainData.map(lambda r: (r.label, averageTrainYear)) rmseTrainBase = calcRMSE(labelsAndPredsTrain) labelsAndPredsVal = parsedValData.map(lambda r: (r.label, averageTrainYear)) rmseValBase = calcRMSE(labelsAndPredsVal) labelsAndPredsTest = parsedTestData.map(lambda r: (r.label, averageTrainYear)) rmseTestBase = calcRMSE(labelsAndPredsTest) print 'Baseline Train RMSE = {0:.3f}'.format(rmseTrainBase) print 'Baseline Validation RMSE = {0:.3f}'.format(rmseValBase) print 'Baseline Test RMSE = {0:.3f}'.format(rmseTestBase) # TEST Training, validation and test RMSE (2c) Test.assertTrue(np.allclose([rmseTrainBase, rmseValBase, rmseTestBase], [21.305869, 21.586452, 22.136957]), 'incorrect RMSE value') """ Explanation: (2c) Training, validation and test RMSE Now let's calculate the training, validation and test RMSE of our baseline model. To do this, first create RDDs of (label, prediction) tuples for each dataset, and then call calcRMSE. Note that each RMSE can be interpreted as the average prediction error for the given dataset (in terms of number of years). End of explanation """ from matplotlib.colors import ListedColormap, Normalize from matplotlib.cm import get_cmap cmap = get_cmap('YlOrRd') norm = Normalize() actual = np.asarray(parsedValData .map(lambda lp: lp.label) .collect()) error = np.asarray(parsedValData .map(lambda lp: (lp.label, lp.label)) .map(lambda (l, p): squaredError(l, p)) .collect()) clrs = cmap(np.asarray(norm(error)))[:,0:3] fig, ax = preparePlot(np.arange(0, 100, 20), np.arange(0, 100, 20)) plt.scatter(actual, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=0.5) ax.set_xlabel('Predicted'), ax.set_ylabel('Actual') pass predictions = np.asarray(parsedValData .map(lambda lp: averageTrainYear) .collect()) error = np.asarray(parsedValData .map(lambda lp: (lp.label, averageTrainYear)) .map(lambda (l, p): squaredError(l, p)) .collect()) norm = Normalize() clrs = cmap(np.asarray(norm(error)))[:,0:3] fig, ax = preparePlot(np.arange(53.0, 55.0, 0.5), np.arange(0, 100, 20)) ax.set_xlim(53, 55) plt.scatter(predictions, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=0.3) ax.set_xlabel('Predicted'), ax.set_ylabel('Actual') """ Explanation: Visualization 3: Predicted vs. actual We will visualize predictions on the validation dataset. The scatter plots below visualize tuples storing i) the predicted value and ii) true label. The first scatter plot represents the ideal situation where the predicted value exactly equals the true label, while the second plot uses the baseline predictor (i.e., averageTrainYear) for all predicted values. Further note that the points in the scatter plots are color-coded, ranging from light yellow when the true and predicted values are equal to bright red when they drastically differ. End of explanation """ from pyspark.mllib.linalg import DenseVector def gradientSummand(weights, lp): """Calculates the gradient summand for a given weight and `LabeledPoint`. Note: `DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably within this function. For example, they both implement the `dot` method. Args: weights (DenseVector): An array of model weights (betas). lp (LabeledPoint): The `LabeledPoint` for a single observation. Returns: DenseVector: An array of values the same length as `weights`. The gradient summand. """ return (weights.dot(lp.features) - lp.label) * lp.features exampleW = DenseVector([1, 1, 1]) exampleLP = LabeledPoint(2.0, [3, 1, 4]) summandOne = gradientSummand(exampleW, exampleLP) print summandOne exampleW = DenseVector([.24, 1.2, -1.4]) exampleLP = LabeledPoint(3.0, [-1.4, 4.2, 2.1]) summandTwo = gradientSummand(exampleW, exampleLP) print summandTwo # TEST Gradient summand (3a) Test.assertTrue(np.allclose(summandOne, [18., 6., 24.]), 'incorrect value for summandOne') Test.assertTrue(np.allclose(summandTwo, [1.7304,-5.1912,-2.5956]), 'incorrect value for summandTwo') """ Explanation: Part 3: Train (via gradient descent) and evaluate a linear regression model (3a) Gradient summand Now let's see if we can do better via linear regression, training a model via gradient descent (we'll omit the intercept for now). Recall that the gradient descent update for linear regression is: $$ \scriptsize \mathbf{w}_{i+1} = \mathbf{w}_i - \alpha_i \sum_j (\mathbf{w}_i^\top\mathbf{x}_j - y_j) \mathbf{x}_j \,.$$ where $ \scriptsize i $ is the iteration number of the gradient descent algorithm, and $ \scriptsize j $ identifies the observation. First, implement a function that computes the summand for this update, i.e., the summand equals $ \scriptsize (\mathbf{w}^\top \mathbf{x} - y) \mathbf{x} \, ,$ and test out this function on two examples. Use the DenseVector dot method. End of explanation """ def getLabeledPrediction(weights, observation): """Calculates predictions and returns a (label, prediction) tuple. Note: The labels should remain unchanged as we'll use this information to calculate prediction error later. Args: weights (np.ndarray): An array with one weight for each features in `trainData`. observation (LabeledPoint): A `LabeledPoint` that contain the correct label and the features for the data point. Returns: RDD of tuple: An RDD containing (label, prediction) tuples. """ return (observation.label, weights.dot(observation.features)) weights = np.array([1.0, 1.5]) predictionExample = sc.parallelize([LabeledPoint(2, np.array([1.0, .5])), LabeledPoint(1.5, np.array([.5, .5]))]) labelsAndPredsExample = predictionExample.map(lambda lp: getLabeledPrediction(weights, lp)) print labelsAndPredsExample.collect() # TEST Use weights to make predictions (3b) Test.assertEquals(labelsAndPredsExample.collect(), [(2.0, 1.75), (1.5, 1.25)], 'incorrect definition for getLabeledPredictions') """ Explanation: (3b) Use weights to make predictions Next, implement a getLabeledPredictions function that takes in weights and an observation's LabeledPoint and returns a (label, prediction) tuple. Note that we can predict by computing the dot product between weights and an observation's features. End of explanation """ def linregGradientDescent(trainData, numIters): """Calculates the weights and error for a linear regression model trained with gradient descent. Note: `DenseVector` behaves similarly to a `numpy.ndarray` and they can be used interchangably within this function. For example, they both implement the `dot` method. Args: trainData (RDD of LabeledPoint): The labeled data for use in training the model. numIters (int): The number of iterations of gradient descent to perform. Returns: (np.ndarray, np.ndarray): A tuple of (weights, training errors). Weights will be the final weights (one weight per feature) for the model, and training errors will contain an error (RMSE) for each iteration of the algorithm. """ # The length of the training data n = trainData.count() # The number of features in the training data d = len(trainData.take(1)[0].features) w = np.zeros(d) alpha = 1.0 # We will compute and store the training error after each iteration errorTrain = np.zeros(numIters) for i in range(numIters): # Use getLabeledPrediction from (3b) with trainData to obtain an RDD of (label, prediction) # tuples. Note that the weights all equal 0 for the first iteration, so the predictions will # have large errors to start. labelsAndPredsTrain = trainData.map(lambda r: getLabeledPrediction(w, r)) errorTrain[i] = calcRMSE(labelsAndPredsTrain) # Calculate the `gradient`. Make use of the `gradientSummand` function you wrote in (3a). # Note that `gradient` sould be a `DenseVector` of length `d`. gradient = trainData.map(lambda r: gradientSummand(w, r)).sum() # Update the weights alpha_i = alpha / (n * np.sqrt(i+1)) w -= gradient * alpha_i return w, errorTrain # Create a toy dataset with n = 10, d = 3, and then run 5 iterations of gradient descent # note: the resulting model will not be useful; the goal here is to verify that # linregGradientDescent is working properly. exampleN = 10 exampleD = 3 exampleData = (sc .parallelize(parsedTrainData.take(exampleN)) .map(lambda lp: LabeledPoint(lp.label, lp.features[0:exampleD]))) print exampleData.take(2) exampleNumIters = 5 exampleWeights, exampleErrorTrain = linregGradientDescent(exampleData, exampleNumIters) print exampleWeights # TEST Gradient descent (3c) expectedOutput = [48.88110449, 36.01144093, 30.25350092] Test.assertTrue(np.allclose(exampleWeights, expectedOutput), 'value of exampleWeights is incorrect') expectedError = [79.72013547, 30.27835699, 9.27842641, 9.20967856, 9.19446483] Test.assertTrue(np.allclose(exampleErrorTrain, expectedError), 'value of exampleErrorTrain is incorrect') """ Explanation: (3c) Gradient descent Next, implement a gradient descent function for linear regression and test out this function on an example. End of explanation """ numIters = 50 weightsLR0, errorTrainLR0 = linregGradientDescent(parsedTrainData, numIters) labelsAndPreds = parsedValData.map(lambda r: getLabeledPrediction(weightsLR0, r)) rmseValLR0 = calcRMSE(labelsAndPreds) print 'Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}'.format(rmseValBase, rmseValLR0) # TEST Train the model (3d) expectedOutput = [22.64535883, 20.064699, -0.05341901, 8.2931319, 5.79155768, -4.51008084, 15.23075467, 3.8465554, 9.91992022, 5.97465933, 11.36849033, 3.86452361] Test.assertTrue(np.allclose(weightsLR0, expectedOutput), 'incorrect value for weightsLR0') """ Explanation: (3d) Train the model Now let's train a linear regression model on all of our training data and evaluate its accuracy on the validation set. Note that the test set will not be used here. If we evaluated the model on the test set, we would bias our final results. We've already done much of the required work: we computed the number of features in Part (1b); we created the training and validation datasets and computed their sizes in Part (1e); and, we wrote a function to compute RMSE in Part (2b). End of explanation """ norm = Normalize() clrs = cmap(np.asarray(norm(np.log(errorTrainLR0))))[:,0:3] fig, ax = preparePlot(np.arange(0, 60, 10), np.arange(2, 6, 1)) ax.set_ylim(2, 6) plt.scatter(range(0, numIters), np.log(errorTrainLR0), s=14**2, c=clrs, edgecolors='#888888', alpha=0.75) ax.set_xlabel('Iteration'), ax.set_ylabel(r'$\log_e(errorTrainLR0)$') pass norm = Normalize() clrs = cmap(np.asarray(norm(errorTrainLR0[6:])))[:,0:3] fig, ax = preparePlot(np.arange(0, 60, 10), np.arange(17, 22, 1)) ax.set_ylim(17.8, 21.2) plt.scatter(range(0, numIters-6), errorTrainLR0[6:], s=14**2, c=clrs, edgecolors='#888888', alpha=0.75) ax.set_xticklabels(map(str, range(6, 66, 10))) ax.set_xlabel('Iteration'), ax.set_ylabel(r'Training Error') pass """ Explanation: Visualization 4: Training error We will look at the log of the training error as a function of iteration. The first scatter plot visualizes the logarithm of the training error for all 50 iterations. The second plot shows the training error itself, focusing on the final 44 iterations. End of explanation """ from pyspark.mllib.regression import LinearRegressionWithSGD # Values to use when training the linear regression model. numIters = 500 # iterations alpha = 1.0 # step miniBatchFrac = 1.0 # miniBatchFraction reg = 1e-1 # regParam regType = 'l2' # regType useIntercept = True # intercept firstModel = LinearRegressionWithSGD.train(parsedTrainData, iterations = numIters, step = alpha, miniBatchFraction = miniBatchFrac, regParam = reg, regType = regType, intercept = useIntercept) # `weightsLR1` stores the model weights; `interceptLR1` stores the model intercept weightsLR1 = firstModel.weights interceptLR1 = firstModel.intercept print weightsLR1, interceptLR1 # TEST LinearRegressionWithSGD (4a) expectedIntercept = 13.3335907631 expectedWeights = [16.682292427, 14.7439059559, -0.0935105608897, 6.22080088829, 4.01454261926, -3.30214858535, 11.0403027232, 2.67190962854, 7.18925791279, 4.46093254586, 8.14950409475, 2.75135810882] Test.assertTrue(np.allclose(interceptLR1, expectedIntercept), 'incorrect value for interceptLR1') Test.assertTrue(np.allclose(weightsLR1, expectedWeights), 'incorrect value for weightsLR1') """ Explanation: Part 4: Train using MLlib and perform grid search (4a) LinearRegressionWithSGD We're already doing better than the baseline model, but let's see if we can do better by adding an intercept, using regularization, and (based on the previous visualization) training for more iterations. MLlib's LinearRegressionWithSGD essentially implements the same algorithm that we implemented in Part (3b), albeit more efficiently and with various additional functionality, such as stochastic gradient approximation, including an intercept in the model and also allowing L1 or L2 regularization. First use LinearRegressionWithSGD to train a model with L2 regularization and with an intercept. This method returns a LinearRegressionModel. Next, use the model's weights and intercept attributes to print out the model's parameters. End of explanation """ samplePoint = parsedTrainData.take(1)[0] samplePrediction = firstModel.predict(samplePoint.features) print samplePrediction # TEST Predict (4b) Test.assertTrue(np.allclose(samplePrediction, 56.8013380112), 'incorrect value for samplePrediction') """ Explanation: (4b) Predict Now use the LinearRegressionModel.predict() method to make a prediction on a sample point. Pass the features from a LabeledPoint into the predict() method. End of explanation """ # TODO: Replace <FILL IN> with appropriate code labelsAndPreds = parsedValData.map(lambda r: (r.label, firstModel.predict(r.features))) rmseValLR1 = calcRMSE(labelsAndPreds) print ('Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}' + '\n\tLR1 = {2:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1) # TEST Evaluate RMSE (4c) Test.assertTrue(np.allclose(rmseValLR1, 19.691247), 'incorrect value for rmseValLR1') """ Explanation: (4c) Evaluate RMSE Next evaluate the accuracy of this model on the validation set. Use the predict() method to create a labelsAndPreds RDD, and then use the calcRMSE() function from Part (2b). End of explanation """ bestRMSE = rmseValLR1 bestRegParam = reg bestModel = firstModel numIters = 500 alpha = 1.0 miniBatchFrac = 1.0 for reg in [ 1e-10, 1e-5, 1 ]: model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha, miniBatchFrac, regParam=reg, regType='l2', intercept=True) labelsAndPreds = parsedValData.map(lambda lp: (lp.label, model.predict(lp.features))) rmseValGrid = calcRMSE(labelsAndPreds) print rmseValGrid if rmseValGrid < bestRMSE: bestRMSE = rmseValGrid bestRegParam = reg bestModel = model rmseValLRGrid = bestRMSE print ('Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}\n\tLR1 = {2:.3f}\n' + '\tLRGrid = {3:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1, rmseValLRGrid) # TEST Grid search (4d) Test.assertTrue(np.allclose(17.017170, rmseValLRGrid), 'incorrect value for rmseValLRGrid') """ Explanation: (4d) Grid search We're already outperforming the baseline on the validation set by almost 2 years on average, but let's see if we can do better. Perform grid search to find a good regularization parameter. Try regParam values 1e-10, 1e-5, and 1. End of explanation """ predictions = np.asarray(parsedValData .map(lambda lp: bestModel.predict(lp.features)) .collect()) actual = np.asarray(parsedValData .map(lambda lp: lp.label) .collect()) error = np.asarray(parsedValData .map(lambda lp: (lp.label, bestModel.predict(lp.features))) .map(lambda (l, p): squaredError(l, p)) .collect()) norm = Normalize() clrs = cmap(np.asarray(norm(error)))[:,0:3] fig, ax = preparePlot(np.arange(0, 120, 20), np.arange(0, 120, 20)) ax.set_xlim(15, 82), ax.set_ylim(-5, 105) plt.scatter(predictions, actual, s=14**2, c=clrs, edgecolors='#888888', alpha=0.75, linewidths=.5) ax.set_xlabel('Predicted'), ax.set_ylabel(r'Actual') pass """ Explanation: Visualization 5: Best model's predictions Next, we create a visualization similar to 'Visualization 3: Predicted vs. actual' from Part 2 using the predictions from the best model from Part (4d) on the validation dataset. Specifically, we create a color-coded scatter plot visualizing tuples storing i) the predicted value from this model and ii) true label. End of explanation """ reg = bestRegParam modelRMSEs = [] for alpha in [ 1e-5, 10 ]: for numIters in [ 500, 5 ]: model = LinearRegressionWithSGD.train(parsedTrainData, numIters, alpha, miniBatchFrac, regParam=reg, regType='l2', intercept=True) labelsAndPreds = parsedValData.map(lambda lp: (lp.label, model.predict(lp.features))) rmseVal = calcRMSE(labelsAndPreds) print 'alpha = {0:.0e}, numIters = {1}, RMSE = {2:.3f}'.format(alpha, numIters, rmseVal) modelRMSEs.append(rmseVal) # TEST Vary alpha and the number of iterations (4e) expectedResults = sorted([56.969705, 56.892949, 355124752.221221]) Test.assertTrue(np.allclose(sorted(modelRMSEs)[:3], expectedResults), 'incorrect value for modelRMSEs') """ Explanation: (4e) Vary alpha and the number of iterations In the previous grid search, we set alpha = 1 for all experiments. Now let's see what happens when we vary alpha. Specifically, try 1e-5 and 10 as values for alpha and also try training models for 500 iterations (as before) but also for 5 iterations. Evaluate all models on the validation set. Note that if we set alpha too small the gradient descent will require a huge number of steps to converge to the solution, and if we use too large of an alpha it can cause numerical problems, like you'll see below for alpha = 10. End of explanation """ from matplotlib.colors import LinearSegmentedColormap # Saved parameters and results, to save the time required to run 36 models numItersParams = [10, 50, 100, 250, 500, 1000] regParams = [1e-8, 1e-6, 1e-4, 1e-2, 1e-1, 1] rmseVal = np.array([[ 20.36769649, 20.36770128, 20.36818057, 20.41795354, 21.09778437, 301.54258421], [ 19.04948826, 19.0495 , 19.05067418, 19.16517726, 19.97967727, 23.80077467], [ 18.40149024, 18.40150998, 18.40348326, 18.59457491, 19.82155716, 23.80077467], [ 17.5609346 , 17.56096749, 17.56425511, 17.88442127, 19.71577117, 23.80077467], [ 17.0171705 , 17.01721288, 17.02145207, 17.44510574, 19.69124734, 23.80077467], [ 16.58074813, 16.58079874, 16.58586512, 17.11466904, 19.6860931 , 23.80077467]]) numRows, numCols = len(numItersParams), len(regParams) rmseVal = np.array(rmseVal) rmseVal.shape = (numRows, numCols) fig, ax = preparePlot(np.arange(0, numCols, 1), np.arange(0, numRows, 1), figsize=(8, 7), hideLabels=True, gridWidth=0.) ax.set_xticklabels(regParams), ax.set_yticklabels(numItersParams) ax.set_xlabel('Regularization Parameter'), ax.set_ylabel('Number of Iterations') colors = LinearSegmentedColormap.from_list('blue', ['#0022ff', '#000055'], gamma=.2) image = plt.imshow(rmseVal,interpolation='nearest', aspect='auto', cmap = colors) # Zoom into the bottom left numItersParamsZoom, regParamsZoom = numItersParams[-3:], regParams[:4] rmseValZoom = rmseVal[-3:, :4] numRows, numCols = len(numItersParamsZoom), len(regParamsZoom) fig, ax = preparePlot(np.arange(0, numCols, 1), np.arange(0, numRows, 1), figsize=(8, 7), hideLabels=True, gridWidth=0.) ax.set_xticklabels(regParamsZoom), ax.set_yticklabels(numItersParamsZoom) ax.set_xlabel('Regularization Parameter'), ax.set_ylabel('Number of Iterations') colors = LinearSegmentedColormap.from_list('blue', ['#0022ff', '#000055'], gamma=.2) image = plt.imshow(rmseValZoom,interpolation='nearest', aspect='auto', cmap = colors) pass """ Explanation: Visualization 6: Hyperparameter heat map Next, we perform a visualization of hyperparameter search using a larger set of hyperparameters (with precomputed results). Specifically, we create a heat map where the brighter colors correspond to lower RMSE values. The first plot has a large area with brighter colors. In order to differentiate within the bright region, we generate a second plot corresponding to the hyperparameters found within that region. End of explanation """ import itertools def twoWayInteractions(lp): """Creates a new `LabeledPoint` that includes two-way interactions. Note: For features [x, y] the two-way interactions would be [x^2, x*y, y*x, y^2] and these would be appended to the original [x, y] feature list. Args: lp (LabeledPoint): The label and features for this observation. Returns: LabeledPoint: The new `LabeledPoint` should have the same label as `lp`. Its features should include the features from `lp` followed by the two-way interaction features. """ interactions = map(lambda (a,b): a * b, list(itertools.product(lp.features, lp.features))) return LabeledPoint(lp.label, np.hstack((lp.features, interactions))) print twoWayInteractions(LabeledPoint(0.0, [2, 3])) # Transform the existing train, validation, and test sets to include two-way interactions. trainDataInteract = parsedTrainData.map(twoWayInteractions).cache() valDataInteract = parsedValData.map(twoWayInteractions).cache() testDataInteract = parsedTestData.map(twoWayInteractions).cache() # TEST Add two-way interactions (5a) twoWayExample = twoWayInteractions(LabeledPoint(0.0, [2, 3])) Test.assertTrue(np.allclose(sorted(twoWayExample.features), sorted([2.0, 3.0, 4.0, 6.0, 6.0, 9.0])), 'incorrect features generatedBy twoWayInteractions') twoWayPoint = twoWayInteractions(LabeledPoint(1.0, [1, 2, 3])) Test.assertTrue(np.allclose(sorted(twoWayPoint.features), sorted([1.0,2.0,3.0,1.0,2.0,3.0,2.0,4.0,6.0,3.0,6.0,9.0])), 'incorrect features generated by twoWayInteractions') Test.assertEquals(twoWayPoint.label, 1.0, 'incorrect label generated by twoWayInteractions') Test.assertTrue(np.allclose(sum(trainDataInteract.take(1)[0].features), 40.821870576035529), 'incorrect features in trainDataInteract') Test.assertTrue(np.allclose(sum(valDataInteract.take(1)[0].features), 45.457719932695696), 'incorrect features in valDataInteract') Test.assertTrue(np.allclose(sum(testDataInteract.take(1)[0].features), 35.109111632783168), 'incorrect features in testDataInteract') """ Explanation: Part 5: Add interactions between features (5a) Add 2-way interactions So far, we've used the features as they were provided. Now, we will add features that capture the two-way interactions between our existing features. Write a function twoWayInteractions that takes in a LabeledPoint and generates a new LabeledPoint that contains the old features and the two-way interactions between them. Note that a dataset with three features would have nine ( $ \scriptsize 3^2 $ ) two-way interactions. You might want to use itertools.product to generate tuples for each of the possible 2-way interactions. Remember that you can combine two DenseVector or ndarray objects using np.hstack. End of explanation """ numIters = 500 alpha = 1.0 miniBatchFrac = 1.0 reg = 1e-10 modelInteract = LinearRegressionWithSGD.train(trainDataInteract, numIters, alpha, miniBatchFrac, regParam=reg, regType='l2', intercept=True) labelsAndPredsInteract = valDataInteract.map(lambda lp: (lp.label, modelInteract.predict(lp.features))) rmseValInteract = calcRMSE(labelsAndPredsInteract) print ('Validation RMSE:\n\tBaseline = {0:.3f}\n\tLR0 = {1:.3f}\n\tLR1 = {2:.3f}\n\tLRGrid = ' + '{3:.3f}\n\tLRInteract = {4:.3f}').format(rmseValBase, rmseValLR0, rmseValLR1, rmseValLRGrid, rmseValInteract) # TEST Build interaction model (5b) Test.assertTrue(np.allclose(rmseValInteract, 15.6894664683), 'incorrect value for rmseValInteract') """ Explanation: (5b) Build interaction model Now, let's build the new model. We've done this several times now. To implement this for the new features, we need to change a few variable names. Remember that we should build our model from the training data and evaluate it on the validation data. Note that you should re-run your hyperparameter search after changing features, as using the best hyperparameters from your prior model will not necessary lead to the best model. For this exercise, we have already preset the hyperparameters to reasonable values. End of explanation """ labelsAndPredsTest = testDataInteract.map(lambda lp: (lp.label, modelInteract.predict(lp.features))) rmseTestInteract = calcRMSE(labelsAndPredsTest) print ('Test RMSE:\n\tBaseline = {0:.3f}\n\tLRInteract = {1:.3f}' .format(rmseTestBase, rmseTestInteract)) # TEST Evaluate interaction model on test data (5c) Test.assertTrue(np.allclose(rmseTestInteract, 16.3272040537), 'incorrect value for rmseTestInteract') """ Explanation: (5c) Evaluate interaction model on test data Our final step is to evaluate the new model on the test dataset. Note that we haven't used the test set to evaluate any of our models. Because of this, our evaluation provides us with an unbiased estimate for how our model will perform on new data. If we had changed our model based on viewing its performance on the test set, our estimate of RMSE would likely be overly optimistic. We'll also print the RMSE for both the baseline model and our new model. With this information, we can see how much better our model performs than the baseline model. End of explanation """
mne-tools/mne-tools.github.io
0.14/_downloads/plot_read_evoked.ipynb
bsd-3-clause
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) from mne import read_evokeds from mne.datasets import sample print(__doc__) data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis-ave.fif' # Reading condition = 'Left Auditory' evoked = read_evokeds(fname, condition=condition, baseline=(None, 0), proj=True) """ Explanation: Reading and writing an evoked file This script shows how to read and write evoked datasets. End of explanation """ evoked.plot(exclude=[]) # Show result as a 2D image (x: time, y: channels, color: amplitude) evoked.plot_image(exclude=[]) """ Explanation: Show result as a butteryfly plot: By using exclude=[] bad channels are not excluded and are shown in red End of explanation """
theavey/ParaTemp
examples/paratemp_analysis_examples.ipynb
apache-2.0
import collections import errno import sys, os, re, subprocess, glob import time import matplotlib.pyplot as plt import MDAnalysis import MDAnalysis.analysis import MDAnalysis.analysis.rdf import numpy as np import pandas as pd import six from importlib import reload import paratemp.coordinate_analysis as ca import paratemp as pt from paratemp.re_universe import REUniverse import thtools from thtools import cd, merge_two_dicts from thtools import save_obj, load_obj, make_obj_dir reload(ca) reload(pt) reload(thtools) """ Explanation: Imports and such End of explanation """ def parse_plumed_dists(p_plumed, verbose=True): """ Read a plumed input and return dict of defined dists Note, this returns 1-based indexes for the atoms which is what MDAnalysis will need and what PLUMED/GROMACS use, but it is different than VMD (and Python, generally).""" with open(p_plumed, 'r') as f_plumed: init_lines = f_plumed.readlines() lines = [] for line in init_lines: lines.append(line.split('#')[0]) dists = dict() for line in lines: if 'DISTANCE' in line: m = re.search(r'(\S+):.+ATOMS=(\d+),(\d+)', line) if m: n, a1, a2 = m.groups() dists[n] = (int(a1), int(a2)) else: n = re.search(r'(\S+):.+', line).group(1) if verbose: print('Unable to define atoms ' 'for distance: {}'.format(n)) return dists """ Explanation: Parse distances from PLUMED input End of explanation """ l_configs = ['MaEn', 'MaEx', 'MiEn', 'MiEx'] dp_configs = dict() for c in l_configs: dp_configs[c] = os.path.abspath( os.path.join('PTAD-cinnamate/', c)) p_gro = os.path.abspath('PTAD-cinnamate/MaEn/tad-MaEn-solutes.gro') d_temp = parse_plumed_dists('PTAD-cinnamate/MaEn/plumed-cin-ptad-MaEn.dat') d_metad_dists = {'CV1': d_temp['dm1'], 'CV2': d_temp['dm2']} del(d_temp) d_ox_dists = {'O-O': [69, 71], 'O(l)-Cy': [69, 75], 'O(r)-Cy': [71, 75]} """ Explanation: Create dicts of files, folders, and distances Using parse_plumed_dists for a single set of simulations End of explanation """ dp_catff = dict(phen_cg='CGenFF-3-body/PT/PTAD-cinnamate/', phen_ga='repeat-juanma-w-pt/tad-cinnamate/', naph_ga='repeat-juanma-w-pt/ntad-cinnamate/') dp_l_configs = dict(MaEn='major-endo', MaEx='major-exo', MiEn='minor-endo', MiEx='minor-exo') dp_s_configs = dict(MaEn='MaEn', MaEx='MaEx', MiEn='MiEn', MiEx='MiEx') dd_configs = dict(phen_cg=dp_s_configs, phen_ga=append_to_keys(dp_l_configs, '13-3htmf-etc/05'), naph_ga=append_to_keys(dp_l_configs, '02-PT')) dp_gros = dict(phen_cg='/projectnb/nonadmd/theavey/CGenFF-3-body/PT/PTAD-cinnamate/MaEn/tad-MaEn-solutes.gro', phen_ga=os.path.abspath('repeat-juanma-w-pt/tad-cinnamate/solutes.gro'), naph_ga=os.path.abspath('repeat-juanma-w-pt/ntad-cinnamate/ntad-cinnamate.gro')) dd_cv_def = dict(naph_ga={'O-O': [53, 29], 'O(l)-dm': [53, 4], 'O(r)-dm': [29, 4], 'CV1':[129,53], 'CV2':[102,68]}) """ Explanation: For multiple simulations End of explanation """ d_reus = dict() for config in dp_configs: reu = REUniverse(p_gro, dp_configs[config], traj_glob='npt*xtc') d_reus[config] = reu for u in reu: u.read_data() """ Explanation: Create REUniverses and calculate some dists Just import the Universes and read_data End of explanation """ d_reus = dict() for catff in dp_catff: dp_configs = dd_configs[catff] top = dp_gros[catff] for config in dp_configs: key = f'{catff}_{config}' bf = os.path.join(dp_catff[catff], dp_configs[config]) reu = REUniverse(top, bf, traj_glob='npt*.xtc') for u in reu: try: u.read_data() except OSError: d_cv_def = dd_cv_def[catff] u.calculate_distances(**d_cv_def) u.save_data() d_reus[key] = reu """ Explanation: Import and calculate distances if necessary Could also be done by read, calc, save because it now will not do any unnecessary steps End of explanation """ figs = [] for u in reu: fig = u.fes_1d('O-O', bins=15, linewidth=2)[3] figs.append(fig) """ Explanation: Plotting Simple 1D FESs for Universes in an REUniverse End of explanation """ figs = [] for u in reu: fig, ax = u.fes_2d(x='CV1', y='CV2', xlabel='CV 1', ylabel='CV 2')[3:5] """ Explanation: Simple 2D FESs for Universes in an REUniverse End of explanation """ x_lims = np.zeros([64, 2]) j = 0 for config in d_ptus: for i, u in enumerate(d_ptus[config]): u.figs = dict() u.read_data(ignore_no_data=True) fig, axes = ca.fes_array_3_legend(u.data, temp=u.temperature, labels=('O-O', 'O(l)-Cy', 'O(r)-Cy'), bins=15, linewidth=2.0)[3:] ax = axes.flat[0] if ax.get_ylim()[1] > 10: for ax in axes.flat[:3]: ax.set_ylim((-0.5, 7)) fig.tight_layout(rect=[0, 0, 1, 0.95]) fig.suptitle('{} {:.0f} K'.format(config, u.temperature)) u.figs['fes_ox_dists_bins'] = fig x_lims[j] = ax.get_xlim() j += 1 """ Explanation: Using ca.fes_array_3_legend End of explanation """ name_gro = p_gro name_gro = os.path.abspath(name_gro) fig, ax = plt.subplots() bins_CV_Os = {} rdfs_CV_Os = {} for key in sorted(dp_configs): # for key in ['MiEx']: with cd(dp_configs[key]): i = 0 print 'Now starting on {} {}...'.format(key, i) univ = d_reus[key][i] final_time = univ.final_time_str file_name_end = '-PT-phen-cg-{}-{}-{}.pdf'.format(key, i, final_time) reactant_CV_Os = univ.select_atoms('(resname is 3htmf) and (name is O1 or name is O2)') catalyst_CV_Os = univ.select_atoms('(resname is TAD or resname is tad) and (name is O1 or name is OH)') rcrdf = MDAnalysis.analysis.rdf.InterRDF( reactant_CV_Os, catalyst_CV_Os, range=(2.0, 12.0)) rcrdf.run() print rcrdf.count bins_CV_Os[key] = rcrdf.bins rdfs_CV_Os[key] = rcrdf.rdf ax.plot(rcrdf.bins, rcrdf.rdf, label=key) ax.legend() fig """ Explanation: Radial distributions Calculate radial distributions End of explanation """ r = 0.0019872 temp = univ.temperature g_CV_Os = {} for key in rdfs_CV_Os: rdfs = rdfs_CV_Os[key] g_CV_Os[key] = - r * temp * np.log(rdfs + 1e-40) min_g = min([min(gs) for gs in g_CV_Os.values()]) for key in g_CV_Os: g_CV_Os[key] = g_CV_Os[key] - min_g fig, ax = plt.subplots() for key in sorted(g_CV_Os): ax.plot(bins_CV_Os[key], g_CV_Os[key], label=key) ax.set_xlim([2.4,9.9]) ax.set_ylim([-0.1,2.7]) ax.legend() ax.set_ylabel(r'$\Delta G$ / (kcal / mol)') ax.set_xlabel('distance / $\mathrm{\AA}$') fig """ Explanation: Make FES from radial distributions End of explanation """ x_lims = np.zeros((64, 2)) j = 0 df_pvn_same = dict() df_figs = df_pvn_same for key in d_reus: if 'naph' not in key: continue config = key[-4:] reu = d_reus[key] equiv_ga_reu = d_reus['phen_ga_'+config] for i, u in enumerate(reu): fig, ax = plt.subplots(1, 1) df_figs[f'{config}_{i}'] = fig u.fes_1d('O-O', bins=15, ax=ax, linewidth=2, label='naphthyl') equiv_ga_reu[i].fes_1d('O-O', bins=15, ax=ax, linewidth=2, label='phenanthryl') ax.set_xlim((3.24, 5.85)) ax.set_aspect(0.3, adjustable='box-forced') if ax.get_ylim()[1] > 10: ax.set_ylim((-0.5, 7)) ax.legend() fig.tight_layout() x_lims[j] = ax.get_xlim() j += 1 # break """ Explanation: Plot FES from two Universes on the same axes End of explanation """ # Cutoff values used for frame selection cv1_cuts = [6.5, 9.] cv2_cuts = [1.5, 3.] name_set = 'lCV1-sCV2' # (partial) name for the file # instantiate the Universe object univ = ca.Taddol('solutes.gro', 'major-endo/13-3htmf-etc/05/pbc-MaEn-0.xtc') # Calculate/read-in the distance data try: univ.data['CV1'] except KeyError: univ.read_data(filename='major-endo/13-3htmf-etc/05/npt-PT-MaEn-out0.h5') # Create boolean array telling where the cutoffs are satisfied bool_array = ((univ.data['CV1'] > cv1_cuts[0]) & (univ.data['CV1'] < cv1_cuts[1]) & (univ.data['CV2'] > cv2_cuts[0]) & (univ.data['CV2'] < cv2_cuts[1])) num = len(univ.data[bool_array]) print('These cutoffs include {} frames.'.format(num)) # Create solute atomselection to not save the solvent to disk solutes = univ.select_atoms('resname is 3HT or resname is CIN or resname is TAD') # write the selected frames into a new trajectory file with mda.Writer('minim-structs-'+name_set+'-rjm-PT-MaEn-0.xtc', solutes.n_atoms) as W: for ts in univ.trajectory: if bool_array[univ.trajectory.frame]: W.write(solutes) """ Explanation: Pull out certain frames from a trajectory and save to disk End of explanation """
eds-uga/csci1360e-su17
lectures/L7.ipynb
mit
def our_function(): pass def our_function(): pass """ Explanation: Lecture 7: Functions I CSCI 1360E: Foundations for Informatics and Analytics Overview and Objectives In this lecture, we'll introduce the concept of functions, critical abstractions in nearly every modern programming language. Functions are important for abstracting and categorizing large codebases into smaller, logical, and human-digestable components. By the end of this lecture, you should be able to: Define a function that performs a specific task Set function arguments and return values Write a function from scratch to answer questions in JupyterHub! Part 1: Defining Functions A function in Python is not very different from a function as you've probably learned since algebra. "Let $f$ be a function of $x$"...sound familiar? We're basically doing the same thing here. A function ($f$) will [usually] take something as input ($x$), perform some kind of operation on it, and then [usually] return a result ($y$). Which is why we usually see $f(x) = y$. A function, then, is composed of three main components: 1: The function itself. A [good] function will have one very specific task it performs. This task is usually reflected in its name. Take the examples of print, or sqrt, or exp, or log; all these names are very clear about what the function does. 2: Arguments (if any). Arguments (or parameters) are the input to the function. It's possible a function may not take any arguments at all, but often at least one is required. For example, print has 1 argument: a string. 3: Return values (if any). Return values are the output of the function. It's possible a function may not return anything; technically, print does not return anything. But common math functions like sqrt or log have clear return values: the output of that math operation. Philosophy A core tenet in writing functions is that functions should do one thing, and do it well (with apologies to the Unix Philosophy). Writing good functions makes code much easier to troubleshoot and debug, as the code is already logically separated into components that perform very specific tasks. Thus, if your application is breaking, you usually have a good idea where to start looking. It's very easy to get caught up writing "god functions": one or two massive functions that essentially do everything you need your program to do. But if something breaks, this design is very difficult to debug. Functions vs Methods You've probably heard the term "method" before, in this class. Quite often, these two terms are used interchangeably, and for our purposes they are pretty much the same. BUT. These terms ultimately identify different constructs, so it's important to keep that in mind. Specifically: Methods are functions defined inside classes (sorry, not being covered in 1360E). Functions are not inside classes. Otherwise, functions and methods work identically. So how do we write functions? At this point in the course, you've probably already seen how this works, but we'll go through it step by step regardless. First, we define the function header. This is the portion of the function that defines the name of the function, the arguments, and uses the Python keyword def to make everything official: End of explanation """ # Call the function! our_function() # Nothing happens...no print statement, no computations, nothing. # But there's no error either...so, yay? """ Explanation: That's everything we need for a working function! Let's walk through it: def keyword: required before writing any function, to tell Python "hey! this is a function!" Function name: one word (can "fake" spaces with underscores), which is the name of the function and how we'll refer to it later Arguments: a comma-separated list of arguments the function takes to perform its task. If no arguments are needed (as above), then just open-paren-close-paren. Colon: the colon indicates the end of the function header and the start of the actual function's code. pass: since Python is sensitive to whitespace, we can't leave a function body blank; luckily, there's the pass keyword that does pretty much what it sounds like--no operation at all, just a placeholder. Admittedly, our function doesn't really do anything interesting. It takes no parameters, and the function body consists exclusively of a placeholder keyword that also does nothing. Still, it's a perfectly valid function! End of explanation """ def one_arg(arg1): print(arg1) def two_args(arg1, arg2): print(arg1, arg2) def three_args(arg1, arg2, arg3): print(arg1, arg2, arg3) # And so on... """ Explanation: Other notes on functions You can define functions (as we did just before) almost anywhere in your code. Still, good coding practices behooves you to generally group your function definitions together, e.g. at the top of your Python file. Invoking or activating a function is referred to as calling the function. When you call a function, you type its name, an open parenthesis, any arguments you're sending to the function, and a closing parenthesis. If there are no arguments, then calling the function is as simple as typing the function name and an open-close pair of parentheses (as in our previous example). Part 2: Function Arguments Arguments (or parameters), as stated before, are the function's input; the "$x$" to our "$f$", as it were. You can specify as many arguments as want, separating them by commas: End of explanation """ one_arg(10) # "one_arg" takes only 1 argument one_arg(10, 5) # "one_arg" won't take 2 arguments! two_args(10, 5) # "two_args", on the other hand, does take 2 arguments two_args(10, 5, 1) # ...but it doesn't take 3 """ Explanation: Like functions, you can name the arguments anything you want, though also like functions you'll probably want to give them more meaningful names besides arg1, arg2, and arg3. When these become just three functions among hundreds in a massive codebase written by dozens of different people, it's helpful when the code itself gives you hints as to what it does. When you call a function, you'll need to provide the same number of arguments in the function call as appear in the function header, otherwise Python will yell at you. End of explanation """ def func_with_default_arg(positional, default = 10): print(positional, default) func_with_default_arg("pos_arg") func_with_default_arg("pos_arg", default = 999) """ Explanation: To be fair, it's a pretty easy error to diagnose, but still something to keep in mind--especially as we move beyond basic "positional" arguments (as they are so called in the previous error message) into optional arguments. Default arguments "Positional" arguments--the only kind we've seen so far--are required whenever you call a function. If the function header specifies a positional argument, then every single call to that functions needs to have that argument specified. In our previous example, one_arg is defined with 1 positional argument, so every time you call one_arg, you HAVE to supply 1 argument. Same with two_args defining 2 arguments, and three_args defining 3 arguments. Calling any of these functions without exactly the right number of arguments will result in an error. There are cases, however, where it can be helpful to have optional, or default, arguments. In this case, when the function is called, the programmer can decide whether or not they want to override the default values. You can specify default arguments in the function header: End of explanation """ def games_in_library(username, library): print("User '{}' owns: ".format(username)) for game in library: print("\t{}".format(game)) """ Explanation: Can you piece together what's happening here? Note that, in the function header, one of the arguments is set equal to a particular value: def func_with_default_arg(positional, default = 10): This means that you can call this function with only 1 arguments, and if you do, the second argument will take its "default" value, aka the value that is assigned in the function header (in this case, 10). Alternatively, you can specify a different value for the second argument if you supply 2 arguments when you call the function. Can you think of examples where default arguments might be useful? Let's do one more small example before moving on to return values. Let's build a method which prints out a list of video games in someone's Steam library. End of explanation """ games_in_library('fps123', ['DOTA 2', 'Left 4 Dead', 'Doom', 'Counterstrike', 'Team Fortress 2']) games_in_library('rts456', ['Civilization V', 'Cities: Skylines', 'Sins of a Solar Empire']) games_in_library('smrt789', ['Binding of Isaac', 'Monaco']) """ Explanation: You can imagine how you might modify this function to include a default argument--perhaps a list of games that everybody owns by simply registering with Steam. End of explanation """ def identity_function(in_arg): return in_arg x = "this is the function input" return_value = identity_function(x) print(return_value) """ Explanation: In this example, our function games_in_library has two positional arguments: username, which is the Steam username of the person, and library, which is a list of video game titles. The function simply prints out the username and the titles they own. Part 3: Return Values Just as functions [can] take input, they also [can] return output for the programmer to decide what to do with. Almost any function you will ever write will most likely have a return value of some kind. If not, your function may not be "well-behaved", aka sticking to the general guideline of doing one thing very well. There are certainly some cases where functions won't return anything--functions that just print things, functions that run forever (yep, they exist!), functions designed specifically to test other functions--but these are highly specialized cases we are not likely to encounter in this course. Keep this in mind as a "rule of thumb": if your function doesn't have a return statement, you may need to double-check your code. To return a value from a function, just use the return keyword: End of explanation """ def explode_string(some_string): list_of_characters = [] for index in range(len(some_string)): list_of_characters.append(some_string[index]) return list_of_characters words = "Blahblahblah" output = explode_string(words) print(output) """ Explanation: This is pretty basic: the function returns back to the programmer as output whatever was passed into the function as input. Hence, "identity function." Anything you can pass in as function parameters, you can return as function output, including lists: End of explanation """ def list_to_tuple(inlist): return [10, inlist] # Yep, this is just a list. print(list_to_tuple([1, 2, 3])) print(list_to_tuple(["one", "two", "three"])) """ Explanation: This function takes a string as input, uses a loop to "explode" the string, and returns a list of individual characters. You can even return multiple values simultaneously from a function. They're just treated as tuples! End of explanation """
saudijack/unfpyboot
Day_01/01_Advanced_Python/02_LambdaFunction.ipynb
mit
lambda argument_list: expression # The argument list consists of a comma separated list of arguments and # the expression is an arithmetic expression using these arguments. f = lambda x, y : x + y f(2,1) """ Explanation: Lambda Function and More <font color='red'>Reference Documents</font> <OL> <LI> <A HREF="http://www.u.arizona.edu/~erdmann/mse350/topics/list_comprehensions.html">Map, Filter, Lambda, and List Comprehensions in Python</A> </OL> <font color='red'>Lambda, Filter, Reduce and Map</font> <UL> <LI> The lambda operator or lambda function is a way to create small anonymous functions. <LI> These functions are throw-away functions, i.e. they are just needed where they have been created. <LI> Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). </UL> Basic Syntax of a Lambda Function End of explanation """ line1 = "A cat, a dog " line2 = " a bird, a mountain" # Use X as an alias for two methods. x = lambda s: s.strip().upper() # Call the lambda to shorten the program's source. line1b = x(line1) line2b = x(line2) print(line1b) print(line2b) """ Explanation: Lambda as macro End of explanation """ r = map(func, seq) """ Explanation: Map Function map() is a function with two arguments: End of explanation """ def fahrenheit(T): return ((float(9)/5)*T + 32) def celsius(T): return (float(5)/9)*(T-32) temp = (36.5, 37, 37.5,39) F = map(fahrenheit, temp) print F C = map(celsius, F) print C # map() can be applied to more than one list. # The lists have to have the same length. a = [1,2,3,4] b = [17,12,11,10] c = [-1,-4,5,9] map(lambda x,y:x+y, a,b) map(lambda x,y,z:x+y+z, a,b,c) map(lambda x,y,z:x+y-z, a,b,c) """ Explanation: The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func End of explanation """ words = 'The quick brown fox jumps over the lazy dog'.split() print words stuff = [] for w in words: stuff.append([w.upper(), w.lower(), len(w)]) for i in stuff: print i """ Explanation: <u>Problem 1</u> End of explanation """ fib = [0,1,1,2,3,5,8,13,21,34,55] result = filter(lambda x: x % 2, fib) print result result = filter(lambda x: x % 2 == 0, fib) print result """ Explanation: Use list comprehension and lambda/map function to define <b>stuff</b>. Filter Function The function <B>filter(func, iterableType)</B> offers an elegant way to filter out all the elements of any iterable type (list, tuple, string, etc.), for which the function func returns True. End of explanation """ sentence = "It's a myth that there are no words in English without vowels." vowels = 'aeiou' """ Explanation: <u>Problem 2</u> Use the filter function to remove all the vowels from the sentence End of explanation """ def reduce( aFunction, aSequence, init= 0 ): r= init for s in aSequence: r= aFunction( r, s ) return r """ Explanation: Reduce Function The function <B>reduce(func, seq)</B> continually applies the function func() to the sequence seq. It returns a single value. Syntax End of explanation """ A = reduce(lambda x,y: x+y, [47,11,42,13]) print A # Determining the maximum of a list of numerical values by using reduce f = lambda a,b: a if (a > b) else b B = reduce(f, [47,11,42,102,13]) print B # Calculating the sum of the numbers from 1 to n: n = 300 C = reduce(lambda x, y: x+y, range(1,n+1)) print C def x100y(x,y): return 100*x+y reduce(x100y, [13]) reduce(x100y, [2, 5, 9]) reduce(x100y, [2, 5, 9], 7) """ Explanation: Examples End of explanation """ print reduce(lambda x,y: x*y, [47,11,42,102,13]) # note that you can improve the speed of the calculation using built-in functions # or better still: using the numpy module from operator import mul import numpy as np a = range(1, 101) print "reduce(lambda x, y: x * y, a)" %timeit reduce(lambda x, y: x * y, a) # (1) print "reduce(mul, a)" %timeit reduce(mul, a) # (2) print "np.prod(a)" a = np.array(a) %timeit np.prod(a) # (3) """ Explanation: <u>Problem 3</u> Use the reduce function to find the product of all the entries in the list [47,11,42,102,13] End of explanation """ from IPython.display import YouTubeVideo YouTubeVideo("hrR0WrQMhSs") """ Explanation: <font color='red'>Exception Handling</font> End of explanation """ def enter_number0(): n = int(raw_input("Please enter a number: ")) enter_number0() def enter_number1(): while True: try: n = raw_input("Please enter an integer: ") n = int(n) break except ValueError: print "No valid integer! Please try again ..." print "Great, you successfully entered an integer!" enter_number1() """ Explanation: <UL> <LI> An exception is an error that happens during the execution of a program. <LI> Exceptions are known to non-programmers as instances that do not conform to a general rule. <LI> Exception handling is a construct to handle or deal with errors automatically. <LI> The code, which harbours the risk of an exception, is embedded in a try block. </UL> Simple example End of explanation """ def inverse_number0(): try: x = float(raw_input("Your number: ")) inverse = 1.0 / x except ValueError: print "You should have given either an int or a float" except ZeroDivisionError: print "Infinity" else: print "OK" inverse_number0() # import module sys to get the type of exception import sys def inverse_number1(): while True: try: x = int(raw_input("Enter an integer: ")) r = 1/x break except: print "Oops!",sys.exc_info()[0],"occured." print "Please try again." print print "The reciprocal of",x,"is",r inverse_number1() """ Explanation: Some Exception Errors <UL> <LI> <B>IOError</B>: The file cannot be opened <LI> <B>ImportError</B>: Python cannot find the module <LI> <B>ValueError</B>: A built-in operation or function receives an argument that has the right type but an inappropriate value. <LI> <B>KeyboardInterrupt</B>: The user hits the interrupt key (normally Control-C or Delete) <LI> <B>EOFError</B>: One of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data. <LI> <B> OverflowError, ZeroDivisionError, FloatingPointError</B>: </UL> An exhaustive list of built-in exceptions can be found here: https://docs.python.org/2/library/exceptions.html else... End of explanation """ def inverse_number2(): try: x = float(raw_input("Your number: ")) inverse = 1.0 / x finally: print "There may or may not have been an exception." print "The inverse: ", inverse inverse_number2() def inverse_number3(): try: x = float(raw_input("Your number: ")) inverse = 1.0 / x except ValueError: print "You should have given either an int or a float" except ZeroDivisionError: print "Infinity" finally: print "There may or may not have been an exception." inverse_number3() """ Explanation: Clean-up Actions (try ... finally) End of explanation """ def achilles_arrow(x): if abs(x - 1) < 1e-3: raise StopIteration x = 1 - (1-x)/2. return x x=0.0 while True: try: x = achilles_arrow(x) except StopIteration: break print "x = ", x """ Explanation: Raising Exceptions End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/cnrm-cerfacs/cmip6/models/cnrm-esm2-1/land.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-esm2-1', 'land') """ Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: CNRM-ESM2-1 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energy Balance, Carbon Cycle, Nitrogen Cycle, River Routing, Lakes. Properties: 154 (96 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:52 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Conservation Properties 3. Key Properties --&gt; Timestepping Framework 4. Key Properties --&gt; Software Properties 5. Grid 6. Grid --&gt; Horizontal 7. Grid --&gt; Vertical 8. Soil 9. Soil --&gt; Soil Map 10. Soil --&gt; Snow Free Albedo 11. Soil --&gt; Hydrology 12. Soil --&gt; Hydrology --&gt; Freezing 13. Soil --&gt; Hydrology --&gt; Drainage 14. Soil --&gt; Heat Treatment 15. Snow 16. Snow --&gt; Snow Albedo 17. Vegetation 18. Energy Balance 19. Carbon Cycle 20. Carbon Cycle --&gt; Vegetation 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality 26. Carbon Cycle --&gt; Litter 27. Carbon Cycle --&gt; Soil 28. Carbon Cycle --&gt; Permafrost Carbon 29. Nitrogen Cycle 30. River Routing 31. River Routing --&gt; Oceanic Discharge 32. Lakes 33. Lakes --&gt; Method 34. Lakes --&gt; Wetlands 1. Key Properties Land surface key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of land surface model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of land surface model code (e.g. MOSES2.2) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.3. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of the processes modelled (e.g. dymanic vegation, prognostic albedo, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_atmosphere_flux_exchanges') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "water" # "energy" # "carbon" # "nitrogen" # "phospherous" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.4. Land Atmosphere Flux Exchanges Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Fluxes exchanged with the atmopshere. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.atmospheric_coupling_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.5. Atmospheric Coupling Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of land surface coupling with the Atmosphere model component, which may be different for different quantities (e.g. dust: semi-implicit, water vapour: explicit) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_cover') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bare soil" # "urban" # "lake" # "land ice" # "lake ice" # "vegetated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.6. Land Cover Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Types of land cover defined in the land surface model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_cover_change') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.7. Land Cover Change Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe how land cover change is managed (e.g. the use of net or gross transitions) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.8. Tiling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general tiling procedure used in the land surface (if any). Include treatment of physiography, land/sea, (dynamic) vegetation coverage and orography/roughness End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.energy') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Conservation Properties TODO 2.1. Energy Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how energy is conserved globally and to what level (e.g. within X [units]/year) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.water') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Water Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how water is conserved globally and to what level (e.g. within X [units]/year) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Carbon Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how carbon is conserved globally and to what level (e.g. within X [units]/year) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestep_dependent_on_atmosphere') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestepping Framework TODO 3.1. Timestep Dependent On Atmosphere Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is a time step dependent on the frequency of atmosphere coupling? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overall timestep of land surface model (i.e. time between calls) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestepping_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.3. Timestepping Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of time stepping method and associated time step(s) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Software Properties Software properties of land surface code 4.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Grid Land surface grid 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the grid in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.horizontal.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Grid --&gt; Horizontal The horizontal grid in the land surface 6.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the horizontal grid (not including any tiling) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.horizontal.matches_atmosphere_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.2. Matches Atmosphere Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the horizontal grid match the atmosphere? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.vertical.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Vertical The vertical grid in the soil 7.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the vertical grid in the soil (not including any tiling) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.vertical.total_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.2. Total Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The total depth of the soil (in metres) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Soil Land surface soil 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of soil in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_water_coupling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Heat Water Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the coupling between heat and water in the soil End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.number_of_soil layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 8.3. Number Of Soil layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of soil layers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the soil scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Soil --&gt; Soil Map Key properties of the land surface soil map 9.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of soil map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.structure') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.2. Structure Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil structure map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.texture') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.3. Texture Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil texture map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.organic_matter') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.4. Organic Matter Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil organic matter map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.albedo') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.5. Albedo Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil albedo map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.water_table') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.6. Water Table Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil water table map, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.continuously_varying_soil_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 9.7. Continuously Varying Soil Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the soil properties vary continuously with depth? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.soil_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.8. Soil Depth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil depth map End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 10. Soil --&gt; Snow Free Albedo TODO 10.1. Prognostic Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is snow free albedo prognostic? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.functions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation type" # "soil humidity" # "vegetation state" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.2. Functions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If prognostic, describe the dependancies on snow free albedo calculations End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.direct_diffuse') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "distinction between direct and diffuse albedo" # "no distinction between direct and diffuse albedo" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.3. Direct Diffuse Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, describe the distinction between direct and diffuse albedo End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.number_of_wavelength_bands') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 10.4. Number Of Wavelength Bands Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, enter the number of wavelength bands used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11. Soil --&gt; Hydrology Key properties of the land surface soil hydrology 11.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of the soil hydrological model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 11.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of river soil hydrology in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.3. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil hydrology tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.vertical_discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.4. Vertical Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the typical vertical discretisation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.number_of_ground_water_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 11.5. Number Of Ground Water Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of soil layers that may contain water End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.lateral_connectivity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "perfect connectivity" # "Darcian flow" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.6. Lateral Connectivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe the lateral connectivity between tiles End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Bucket" # "Force-restore" # "Choisnel" # "Explicit diffusion" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.7. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The hydrological dynamics scheme in the land surface model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.number_of_ground_ice_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 12. Soil --&gt; Hydrology --&gt; Freezing TODO 12.1. Number Of Ground Ice Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How many soil layers may contain ground ice End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.ice_storage_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.2. Ice Storage Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the method of ice storage End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.permafrost') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.3. Permafrost Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of permafrost, if any, within the land surface scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.drainage.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13. Soil --&gt; Hydrology --&gt; Drainage TODO 13.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General describe how drainage is included in the land surface scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.drainage.types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Gravity drainage" # "Horton mechanism" # "topmodel-based" # "Dunne mechanism" # "Lateral subsurface flow" # "Baseflow from groundwater" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Different types of runoff represented by the land surface model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14. Soil --&gt; Heat Treatment TODO 14.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of how heat treatment properties are defined End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of soil heat scheme in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14.3. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil heat treatment tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.vertical_discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14.4. Vertical Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the typical vertical discretisation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.heat_storage') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Force-restore" # "Explicit diffusion" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14.5. Heat Storage Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the method of heat storage End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "soil moisture freeze-thaw" # "coupling with snow temperature" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14.6. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe processes included in the treatment of soil heat End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Snow Land surface snow 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of snow in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the snow tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.number_of_snow_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.3. Number Of Snow Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of snow levels used in the land surface scheme/model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.density') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "constant" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.4. Density Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow density End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.water_equivalent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.5. Water Equivalent Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of the snow water equivalent End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.heat_content') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.6. Heat Content Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of the heat content of snow End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.temperature') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.7. Temperature Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow temperature End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.liquid_water_content') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.8. Liquid Water Content Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow liquid water End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_cover_fractions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "ground snow fraction" # "vegetation snow fraction" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.9. Snow Cover Fractions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify cover fractions used in the surface snow scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "snow interception" # "snow melting" # "snow freezing" # "blowing snow" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.10. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Snow related processes in the land surface scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.11. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the snow scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_albedo.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "prescribed" # "constant" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16. Snow --&gt; Snow Albedo TODO 16.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of snow-covered land albedo End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_albedo.functions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation type" # "snow age" # "snow density" # "snow grain type" # "aerosol deposition" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.2. Functions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N *If prognostic, * End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17. Vegetation Land surface vegetation 17.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of vegetation in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 17.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of vegetation scheme in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.dynamic_vegetation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 17.3. Dynamic Vegetation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there dynamic evolution of vegetation? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.4. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the vegetation tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_representation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation types" # "biome types" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.5. Vegetation Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Vegetation classification used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "broadleaf tree" # "needleleaf tree" # "C3 grass" # "C4 grass" # "vegetated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.6. Vegetation Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of vegetation types in the classification, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biome_types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "evergreen needleleaf forest" # "evergreen broadleaf forest" # "deciduous needleleaf forest" # "deciduous broadleaf forest" # "mixed forest" # "woodland" # "wooded grassland" # "closed shrubland" # "opne shrubland" # "grassland" # "cropland" # "wetlands" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.7. Biome Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of biome types in the classification, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_time_variation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed (not varying)" # "prescribed (varying from files)" # "dynamical (varying from simulation)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.8. Vegetation Time Variation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How the vegetation fractions in each tile are varying with time End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_map') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.9. Vegetation Map Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If vegetation fractions are not dynamically updated , describe the vegetation map used (common name and reference, if possible) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.interception') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 17.10. Interception Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is vegetation interception of rainwater represented? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.phenology') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic (vegetation map)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.11. Phenology Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation phenology End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.phenology_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.12. Phenology Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation phenology End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.leaf_area_index') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prescribed" # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.13. Leaf Area Index Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation leaf area index End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.leaf_area_index_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.14. Leaf Area Index Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of leaf area index End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biomass') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.15. Biomass Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 *Treatment of vegetation biomass * End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biomass_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.16. Biomass Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation biomass End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biogeography') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.17. Biogeography Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation biogeography End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biogeography_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.18. Biogeography Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation biogeography End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.stomatal_resistance') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "light" # "temperature" # "water availability" # "CO2" # "O3" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.19. Stomatal Resistance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify what the vegetation stomatal resistance depends on End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.stomatal_resistance_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.20. Stomatal Resistance Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation stomatal resistance End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.21. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the vegetation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 18. Energy Balance Land surface energy balance 18.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of energy balance in land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 18.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the energy balance tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.number_of_surface_temperatures') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 18.3. Number Of Surface Temperatures Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The maximum number of distinct surface temperatures in a grid cell (for example, each subgrid tile may have its own temperature) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.evaporation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "alpha" # "beta" # "combined" # "Monteith potential evaporation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.4. Evaporation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify the formulation method for land surface evaporation, from soil and vegetation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "transpiration" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.5. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe which processes are included in the energy balance scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19. Carbon Cycle Land surface carbon cycle 19.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of carbon cycle in land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the carbon cycle tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 19.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of carbon cycle in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.anthropogenic_carbon') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "grand slam protocol" # "residence time" # "decay time" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 19.4. Anthropogenic Carbon Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Describe the treament of the anthropogenic carbon pool End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 19.5. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the carbon scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 20. Carbon Cycle --&gt; Vegetation TODO 20.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 20.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.forest_stand_dynamics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 20.3. Forest Stand Dynamics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the treatment of forest stand dyanmics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.photosynthesis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis TODO 21.1. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for photosynthesis (e.g. type of photosynthesis, distinction between C3 and C4 grasses, Nitrogen depencence, etc.) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.maintainance_respiration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration TODO 22.1. Maintainance Respiration Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for maintainence respiration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.growth_respiration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22.2. Growth Respiration Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for growth respiration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation TODO 23.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the allocation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_bins') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "leaves + stems + roots" # "leaves + stems + roots (leafy + woody)" # "leaves + fine roots + coarse roots + stems" # "whole plant (no distinction)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.2. Allocation Bins Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify distinct carbon bins used in allocation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_fractions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "function of vegetation type" # "function of plant allometry" # "explicitly calculated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.3. Allocation Fractions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how the fractions of allocation are calculated End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.phenology.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology TODO 24.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the phenology scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.mortality.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality TODO 25.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the mortality scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 26. Carbon Cycle --&gt; Litter TODO 26.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 26.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 26.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 26.4. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the general method used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 27. Carbon Cycle --&gt; Soil TODO 27.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 27.4. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the general method used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.is_permafrost_included') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 28. Carbon Cycle --&gt; Permafrost Carbon TODO 28.1. Is Permafrost Included Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is permafrost included? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.emitted_greenhouse_gases') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 28.2. Emitted Greenhouse Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the GHGs emitted End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 28.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.impact_on_soil_properties') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 28.4. Impact On Soil Properties Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the impact of permafrost on soil properties End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29. Nitrogen Cycle Land surface nitrogen cycle 29.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the nitrogen cycle in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the notrogen cycle tiling, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 29.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of nitrogen cycle in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the nitrogen scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30. River Routing Land surface river routing 30.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of river routing in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the river routing, if any. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of river routing scheme in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.grid_inherited_from_land_surface') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 30.4. Grid Inherited From Land Surface Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the grid inherited from land surface? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.grid_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.5. Grid Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of grid, if not inherited from land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.number_of_reservoirs') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.6. Number Of Reservoirs Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of reservoirs End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.water_re_evaporation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "flood plains" # "irrigation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30.7. Water Re Evaporation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N TODO End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.coupled_to_atmosphere') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 30.8. Coupled To Atmosphere Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Is river routing coupled to the atmosphere model component? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.coupled_to_land') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.9. Coupled To Land Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the coupling between land and rivers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.quantities_exchanged_with_atmosphere') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30.10. Quantities Exchanged With Atmosphere Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If couple to atmosphere, which quantities are exchanged between river routing and the atmosphere model components? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.basin_flow_direction_map') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "present day" # "adapted for other periods" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30.11. Basin Flow Direction Map Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 What type of basin flow direction map is being used? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.flooding') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.12. Flooding Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the representation of flooding, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 30.13. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the river routing End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.oceanic_discharge.discharge_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "direct (large rivers)" # "diffuse" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31. River Routing --&gt; Oceanic Discharge TODO 31.1. Discharge Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify how rivers are discharged to the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.oceanic_discharge.quantities_transported') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.2. Quantities Transported Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Quantities that are exchanged from river-routing to the ocean model component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32. Lakes Land surface lakes 32.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of lakes in the land surface End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.coupling_with_rivers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 32.2. Coupling With Rivers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are lakes coupled to the river routing model component? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 32.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of lake scheme in seconds End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.quantities_exchanged_with_rivers') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.4. Quantities Exchanged With Rivers Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If coupling with rivers, which quantities are exchanged between the lakes and rivers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.vertical_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32.5. Vertical Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the vertical grid of lakes End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the lake scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.ice_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 33. Lakes --&gt; Method TODO 33.1. Ice Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is lake ice included? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.albedo') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 33.2. Albedo Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of lake albedo End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.dynamics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "No lake dynamics" # "vertical" # "horizontal" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 33.3. Dynamics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which dynamics of lakes are treated? horizontal, vertical, etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.dynamic_lake_extent') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 33.4. Dynamic Lake Extent Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is a dynamic lake extent scheme included? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.endorheic_basins') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 33.5. Endorheic Basins Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basins not flowing to ocean included? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.wetlands.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 34. Lakes --&gt; Wetlands TODO 34.1. Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the treatment of wetlands, if any End of explanation """
DJCordhose/ai
notebooks/talks/2017_intro_data2day.ipynb
mit
import warnings warnings.filterwarnings('ignore') %matplotlib inline %pylab inline import matplotlib.pylab as plt import numpy as np from distutils.version import StrictVersion import sklearn print(sklearn.__version__) assert StrictVersion(sklearn.__version__ ) >= StrictVersion('0.18.1') # Evtl. hat Azure nur 0.19, wir brauchen aber .20 für das Plotting, dann das hier installieren und Notebook neu starten # !conda update pandas -y import pandas as pd print(pd.__version__) assert StrictVersion(pd.__version__) >= StrictVersion('0.20.0') """ Explanation: Einführung in Machine Learning Online Version: http://bit.ly/data2day-ml Grundidee des Supervised Machine Learnings Grundhoffnung: Generalisierung auf bisher unbekannte Daten und Situationen Häufiger Anwendungsfall: Klassifikation End of explanation """ from sklearn.datasets import load_iris iris = load_iris() print(iris.DESCR) X = iris.data y = iris.target X.shape, y.shape X[0] y[0] X_sepal_length = X[:, 0] X_sepal_width = X[:, 1] X_petal_length = X[:, 2] X_petal_width = X[:, 3] X_petal_width.shape """ Explanation: Der Klassiker als Beispiel: Lilien anhand von Blütengrößen unterscheiden Zuerst laden wir den Iris Datensatz und verschaffen uns einen ersten Eindruck https://de.wikipedia.org/wiki/Portal:Statistik/Datensaetze#Iris Sepal: Sepalum, Kelchblatt: der grüne Teil der das bunte umschließt: https://de.wikipedia.org/wiki/Kelchblatt Petal: Petalum, Kronblatt: der bunte Teil, den wir allgemein als Blüte wahrnehmen: https://de.wikipedia.org/wiki/Kronblatt End of explanation """ import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap iris_df = pd.DataFrame(iris.data, columns=iris.feature_names) CMAP = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) pd.plotting.scatter_matrix(iris_df, c=iris.target, edgecolor='black', figsize=(15, 15), cmap=CMAP) plt.show() """ Explanation: Nur eine Art ist linear von den beiden anderen trennbar End of explanation """ from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y) X_train.shape, y_train.shape, X_test.shape, y_test.shape """ Explanation: Problem: Wie wissen wir, ob wir unser System gut trainiert haben? Aufteilung der Daten in Training (60%) und Test (40%) http://scikit-learn.org/stable/modules/cross_validation.html End of explanation """ from sklearn import neighbors # ignore this, it is just technical code # should come from a lib, consider it to appear magically # http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) font_size=25 def meshGrid(x_data, y_data): h = .02 # step size in the mesh x_min, x_max = x_data.min() - 1, x_data.max() + 1 y_min, y_max = y_data.min() - 1, y_data.max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) return (xx,yy) def plotPrediction(clf, x_data, y_data, x_label, y_label, colors, title="", mesh=True): xx,yy = meshGrid(x_data, y_data) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.figure(figsize=(20,10)) if mesh: plt.pcolormesh(xx, yy, Z, cmap=cmap_light) plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.scatter(x_data, y_data, c=colors, cmap=cmap_bold, s=80, marker='o') plt.xlabel(x_label, fontsize=font_size) plt.ylabel(y_label, fontsize=font_size) plt.title(title, fontsize=font_size) """ Explanation: Wir trainieren einen einfachen KNN Klassifikator mit 2 Features und überprüfen die Ergebnisse http://scikit-learn.org/stable/modules/neighbors.html#classification End of explanation """ X_train_sepal_only = X_train[:, :2] X_test_sepal_only = X_test[:, :2] X_train_sepal_only[0] X_train[0] """ Explanation: Zuerst für die Sepal Features End of explanation """ clf_sepal = neighbors.KNeighborsClassifier(1) %time clf_sepal.fit(X_train_sepal_only, y_train) plotPrediction(clf_sepal, X_train_sepal_only[:, 0], X_train_sepal_only[:, 1], 'Sepal length', 'Sepal width', y_train, mesh=False, title="Train Data for Sepal Features") """ Explanation: Training ist sehr schnell, weil wir uns nur jeden der Punkte merken End of explanation """ # 8 ist schwer, weil direkt zwischen 1 und 2 sample_id = 8 # sample_id = 50 sample_feature = X_test_sepal_only[sample_id] sample_label = y_test[sample_id] sample_feature sample_label clf_sepal.predict([sample_feature]) """ Explanation: Ein kleiner Test mit einem einzelnen, bisher unbekannten Datensatz End of explanation """ clf_sepal.predict([[6.0, 4.5]]) # slightly different from above, still gives 0 """ Explanation: Generalisierung funktioniert grundsätzlich, wir probieren es mit einem ausgedachten Wert, der in keinem Datensatz vorkommt End of explanation """ # clf_sepal.score? clf_sepal.score(X_train_sepal_only, y_train) clf_sepal.score(X_test_sepal_only, y_test) """ Explanation: Wir berechnen nun welcher Anteil der Daten richtig vorhergesagt werden kann End of explanation """ plotPrediction(clf_sepal, X_train_sepal_only[:, 0], X_train_sepal_only[:, 1], 'Sepal length', 'Sepal width', y_train, title="Highly Fragmented Decision Boundaries for Train Data") plotPrediction(clf_sepal, X_test_sepal_only[:, 0], X_test_sepal_only[:, 1], 'Sepal length', 'Sepal width', y_test, title="Same Decision Boundaries don't work well for Test Data") """ Explanation: Scores sind ok für die Trainingsdaten, aber nicht so toll für Testdaten, das bedeutet vor allem Overfitting Um zu versehen, was das heißt und was passiert ist, zeichnen wir die Decision Boundaries ein Für jeden möglichen Datenpunkte zeichnen wir flächig die Vorhersage ein End of explanation """ # neighbors.KNeighborsClassifier? clf_sepal_10 = neighbors.KNeighborsClassifier(10) clf_sepal_10.fit(X_train_sepal_only, y_train) clf_sepal_10.score(X_train_sepal_only, y_train) clf_sepal_10.score(X_test_sepal_only, y_test) """ Explanation: Wir machen das Modell weniger komplex, allgemeiner Jetzt mit k=10 Nachbarn End of explanation """ plotPrediction(clf_sepal_10, X_train_sepal_only[:, 0], X_train_sepal_only[:, 1], 'Sepal length', 'Sepal width', y_train, title="Model too simple even for Train Data") plotPrediction(clf_sepal_10, X_test_sepal_only[:, 0], X_test_sepal_only[:, 1], 'Sepal length', 'Sepal width', y_test, title="Model also too simplefor Test Data") """ Explanation: Das ist nun klares Underfitting, das Modell ist zu simpel, sogar für die Trainingsdaten End of explanation """ X_train_petal_only = X_train[:, 2:] X_test_petal_only = X_test[:, 2:] X_train_petal_only[0] X_train[0] clf_petal_10 = neighbors.KNeighborsClassifier(10) clf_petal_10.fit(X_train_petal_only, y_train) plotPrediction(clf_petal_10, X_train_petal_only[:, 0], X_train_petal_only[:, 1], 'Petal length', 'Petal width', y_train, title="Simple model looks good for Train Data") plotPrediction(clf_petal_10, X_test_petal_only[:, 0], X_test_petal_only[:, 1], 'Petal length', 'Petal width', y_test, title="Simple model looks good even for Test Data") clf_petal_10.score(X_train_petal_only, y_train) clf_petal_10.score(X_test_petal_only, y_test) """ Explanation: Zusammenhang Overfittung / Underfitting Schwarze Punkte: Trainingsdaten Graue Punkte: Testdaten Feature Selektion Spoiler Alert: Mit den Sepal Features werden wir immer entweder overfitten oder underfitten Wir versuchen es noch einmal mit den Petal Features End of explanation """ clf = neighbors.KNeighborsClassifier(1) clf.fit(X_train, y_train) clf.score(X_train, y_train) clf.score(X_test, y_test) """ Explanation: Das klappt schon erstaunlich gut, aber was kriegen wir mit allen 4 Features hin? End of explanation """ clf = neighbors.KNeighborsClassifier(13) clf.fit(X_train, y_train) clf.score(X_train, y_train) clf.score(X_test, y_test) """ Explanation: Mit nur einem Nachbarn kriegen wir die Trainingsdaten perfekt hin, overfitten aber leicht Probieren wir es also mit mehr Nachbarn End of explanation """
adityamogadala/xLiMeSemanticIntegrator
examples/ExampleUsage.ipynb
gpl-3.0
import sys sys.path.insert(0, '../utils') import rake query = "From the engineering side, we've also been working on the ability to parallelize training of neural network" rake1 = rake.Rake("../utils/SmartStoplist.txt") vals = rake1.run(query) print vals[0][0] print vals[1][0] print vals[2][0] """ Explanation: Using Rake - Sample Code Here, we see an example of 'rake' algorithm for generating top 3 key phrases from the given text. End of explanation """ # -*- coding: utf-8 -*- import sys sys.path.insert(0, '../search') import SimpleKeywordSearch xlimerec = SimpleKeywordSearch.XlimeAdvancedRecommender() long_query = 'From the engineering side, we have also been working on the ability to parallelize training of neural network models over multiple GPU cards simultaneously.' short_query = 'GPU cards' messagelist = xlimerec.recommender(short_query) print '..........Results of Short query..........' print messagelist messagelist = xlimerec.recommender(long_query) print '..........Results of Long query..........' print messagelist """ Explanation: Using Simple Search - Sample Code Here, we see an example of simple search used to find relevant links in News, Social Media and TV with long and short queries. End of explanation """ # -*- coding: utf-8 -*- import sys sys.path.insert(0, '../docsim') import CompareTwoDocs text1 = "I do not speak english" text2 = "München bietet in seinen diversen Abteilungen immer" comparedoc = CompareTwoDocs.CompareDocContent() score = comparedoc.compare(text1,text2) # Cross-lingual print '[Score between 0 and 1]: ', score """ Explanation: Using Document Comparison - Sample Code Here, we see an example of two documents comparison (long or short) both monolingual and cross-lingual. End of explanation """ # -*- coding: utf-8 -*- import pymongo from pymongo import MongoClient import re class CountMongo: def __init__(self,configdic): self.configdict = configdic def count(self): if self.configdict['MongoDBPath']!="": client = MongoClient(self.configdict['MongoDBPath']) if self.configdict['MongoDBUserName']!="" and self.configdict['MongoDBPassword']!="": client.the_database.authenticate(self.configdict['MongoDBUserName'],self.configdict['MongoDBPassword'],source=self.configdict['MongoDBStorage']) storedb = client[self.configdict['MongoDBStorage']] collection,collection1,collection2,collection3,collection4 = storedb[self.configdict['KafkaTopicTVMetadata']], storedb[self.configdict["KafkaTopicSocialMedia"]],storedb[self.configdict['KafkaTopicNews']],storedb[self.configdict['KafkaTopicASR']],storedb[self.configdict['KafkaTopicSubtitles']] print "Total Docs in Collection [TV Metadata], [Social Media],[News],[TV ASR],[TV SubTitles]:: ", collection.find().count(), collection1.find().count(), collection2.find().count(), collection3.find().count(),collection4.find().count() def main(): configdict={} config = '../config/Config.conf' with open(config) as config_file: for lines in config_file: if re.search(r'=',lines): key = lines.strip('\n').strip().split('=') configdict[key[0]]=key[1] testmongo = CountMongo(configdict) testmongo.count() if __name__ == "__main__": main() """ Explanation: Using MongoDB collections for Analytics - Sample Code End of explanation """
scoaste/showcase
machine-learning/regression/week-3-polynomial-regression-assignment-completed.ipynb
mit
import graphlab """ Explanation: Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function to take an SArray and a degree and return an SFrame where each column is the SArray to a polynomial value up to the total degree e.g. degree = 3 then column 1 is the SArray column 2 is the SArray squared and column 3 is the SArray cubed * Use matplotlib to visualize polynomial regressions * Use matplotlib to visualize the same polynomial degree on different subsets of the data * Use a validation set to select a polynomial degree * Assess the final fit using test data We will continue to use the House data from previous notebooks. Fire up graphlab create End of explanation """ tmp = graphlab.SArray([1., 2., 3.]) tmp_cubed = tmp.apply(lambda x: x**3) print tmp print tmp_cubed """ Explanation: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers up to the maximal degree. The easiest way to apply a power to an SArray is to use the .apply() and lambda x: functions. For example to take the example array and compute the third power we can do as follows: (note running this cell the first time may take longer than expected since it loads graphlab) End of explanation """ ex_sframe = graphlab.SFrame() ex_sframe['power_1'] = tmp print ex_sframe """ Explanation: We can create an empty SFrame using graphlab.SFrame() and then add any columns to it with ex_sframe['column_name'] = value. For example we create an empty SFrame and make the column 'power_1' to be the first power of tmp (i.e. tmp itself). End of explanation """ def polynomial_sframe(feature, degree): # assume that degree >= 1 # initialize the SFrame: poly_sframe = graphlab.SFrame() # then loop over the remaining degrees: for power in range(1, degree+1): # then assign poly_sframe[name] to the appropriate power of feature poly_sframe['power_' + str(power)] = feature.apply(lambda x: x**power) return poly_sframe """ Explanation: Polynomial_sframe function Using the hints above complete the following function to create an SFrame consisting of the powers of an SArray up to a specific degree: End of explanation """ print polynomial_sframe(tmp, 3) """ Explanation: To test your function consider the smaller tmp variable and what you would expect the outcome of the following call: End of explanation """ sales = graphlab.SFrame('../Data/kc_house_data.gl/') sales.head() """ Explanation: Visualizing polynomial regression Let's use matplotlib to visualize what a polynomial regression looks like on some real data. End of explanation """ sales = sales.sort(['sqft_living', 'price']) """ Explanation: As in Week 3, we will use the sqft_living variable. For plotting purposes (connecting the dots), you'll need to sort by the values of sqft_living. For houses with identical square footage, we break the tie by their prices. End of explanation """ poly1_data = polynomial_sframe(sales['sqft_living'], 1) print poly1_data poly1_data['price'] = sales['price'] # add price to the data since it's the target print poly1_data """ Explanation: Let's start with a degree 1 polynomial using 'sqft_living' (i.e. a line) to predict 'price' and plot what it looks like. End of explanation """ model1 = graphlab.linear_regression.create(poly1_data, target = 'price', features = ['power_1'], validation_set = None) #let's take a look at the weights before we plot model1.get("coefficients") import matplotlib.pyplot as plt %matplotlib inline plt.plot(poly1_data['power_1'],poly1_data['price'],'.', poly1_data['power_1'], model1.predict(poly1_data),'-') """ Explanation: NOTE: for all the models in this notebook use validation_set = None to ensure that all results are consistent across users. End of explanation """ poly2_data = polynomial_sframe(sales['sqft_living'], 2) print poly2_data my_features = poly2_data.column_names() # get the name of the features print my_features poly2_data['price'] = sales['price'] # add price to the data since it's the target print poly2_data model2 = graphlab.linear_regression.create(poly2_data, target = 'price', features = my_features, validation_set = None) model2.get("coefficients") plt.plot(poly2_data['power_1'],poly2_data['price'],'.', poly2_data['power_1'], model2.predict(poly2_data),'-') """ Explanation: Let's unpack that plt.plot() command. The first pair of SArrays we passed are the 1st power of sqft and the actual price we then ask it to print these as dots '.'. The next pair we pass is the 1st power of sqft and the predicted values from the linear model. We ask these to be plotted as a line '-'. We can see, not surprisingly, that the predicted values all fall on a line, specifically the one with slope 280 and intercept -43579. What if we wanted to plot a second degree polynomial? End of explanation """ poly3_data = polynomial_sframe(sales['sqft_living'], 3) print poly3_data my_features3 = poly3_data.column_names() # get the name of the features print my_features3 poly3_data['price'] = sales['price'] # add price to the data since it's the target print poly3_data model3 = graphlab.linear_regression.create(poly3_data, target = 'price', features = my_features3, validation_set = None) model3.get("coefficients") plt.plot(poly3_data['power_1'],poly3_data['price'],'.', poly3_data['power_1'], model3.predict(poly3_data),'-') """ Explanation: The resulting model looks like half a parabola. Try on your own to see what the cubic looks like: End of explanation """ poly15_data = polynomial_sframe(sales['sqft_living'], 15) print poly15_data my_features15 = poly15_data.column_names() # get the name of the features print my_features15 poly15_data['price'] = sales['price'] # add price to the data since it's the target print poly15_data model15 = graphlab.linear_regression.create(poly15_data, target = 'price', features = my_features15, validation_set = None) model15.get("coefficients") plt.plot(poly15_data['power_1'],poly15_data['price'],'.', poly15_data['power_1'], model15.predict(poly15_data),'-') """ Explanation: Now try a 15th degree polynomial: End of explanation """ set_a, set_b = sales.random_split(0.5,seed=0) set_1, set_2 = set_a.random_split(0.5,seed=0) set_3, set_4 = set_b.random_split(0.5,seed=0) print len(set_1), len(set_2), len(set_3), len(set_4) """ Explanation: What do you think of the 15th degree polynomial? Do you think this is appropriate? If we were to change the data do you think you'd get pretty much the same curve? Let's take a look. Changing the data and re-learning We're going to split the sales data into four subsets of roughly equal size. Then you will estimate a 15th degree polynomial model on all four subsets of the data. Print the coefficients (you should use .print_rows(num_rows = 16) to view all of them) and plot the resulting fit (as we did above). The quiz will ask you some questions about these results. To split the sales data into four subsets, we perform the following steps: * First split sales into 2 subsets with .random_split(0.5, seed=0). * Next split the resulting subsets into 2 more subsets each. Use .random_split(0.5, seed=0). We set seed=0 in these steps so that different users get consistent results. You should end up with 4 subsets (set_1, set_2, set_3, set_4) of approximately equal size. End of explanation """ set_1_15_data = polynomial_sframe(set_1['sqft_living'], 15) set_2_15_data = polynomial_sframe(set_2['sqft_living'], 15) set_3_15_data = polynomial_sframe(set_3['sqft_living'], 15) set_4_15_data = polynomial_sframe(set_4['sqft_living'], 15) # my_features_x_15 = set_1_15_data.column_names() # get the name of the features # set_1_15_data['price'] = set_1['price'] # add price to the data since it's the target set_2_15_data['price'] = set_2['price'] # add price to the data since it's the target set_3_15_data['price'] = set_3['price'] # add price to the data since it's the target set_4_15_data['price'] = set_4['price'] # add price to the data since it's the target # model_1_15 = graphlab.linear_regression.create(set_1_15_data, target='price', features=my_features_x_15, validation_set=None) model_2_15 = graphlab.linear_regression.create(set_2_15_data, target='price', features=my_features_x_15, validation_set=None) model_3_15 = graphlab.linear_regression.create(set_3_15_data, target='price', features=my_features_x_15, validation_set=None) model_4_15 = graphlab.linear_regression.create(set_4_15_data, target='price', features=my_features_x_15, validation_set=None) model_1_15.get("coefficients").print_rows(num_rows = 16) model_2_15.get("coefficients").print_rows(num_rows = 16) model_3_15.get("coefficients").print_rows(num_rows = 16) model_4_15.get("coefficients").print_rows(num_rows = 16) plt.plot(set_1_15_data['power_1'],set_1_15_data['price'],'.',set_1_15_data['power_1'],model_1_15.predict(set_1_15_data),'-') plt.plot(set_2_15_data['power_1'],set_2_15_data['price'],'.',set_2_15_data['power_1'],model_2_15.predict(set_2_15_data),'-') plt.plot(set_3_15_data['power_1'],set_3_15_data['price'],'.',set_3_15_data['power_1'],model_3_15.predict(set_3_15_data),'-') plt.plot(set_4_15_data['power_1'],set_4_15_data['price'],'.',set_4_15_data['power_1'],model_4_15.predict(set_4_15_data),'-') """ Explanation: Fit a 15th degree polynomial on set_1, set_2, set_3, and set_4 using sqft_living to predict prices. Print the coefficients and make a plot of the resulting model. End of explanation """ training_and_validation, testing = sales.random_split(0.9,seed=1) training, validation = training_and_validation.random_split(0.5,seed=1) """ Explanation: Some questions you will be asked on your quiz: Quiz Question: Is the sign (positive or negative) for power_15 the same in all four models? no Quiz Question: (True/False) the plotted fitted lines look the same in all four plots false Selecting a Polynomial Degree Whenever we have a "magic" parameter like the degree of the polynomial there is one well-known way to select these parameters: validation set. (We will explore another approach in week 4). We split the sales dataset 3-way into training set, test set, and validation set as follows: Split our sales data into 2 sets: training_and_validation and testing. Use random_split(0.9, seed=1). Further split our training data into two sets: training and validation. Use random_split(0.5, seed=1). Again, we set seed=1 to obtain consistent results for different users. End of explanation """ def get_residual_sum_of_squares(model, data, outcome): # First get the predictions predictions = model.predict(data) # Then compute the residuals/errors residuals = predictions - outcome # Then square and add them up RSS = sum(pow(residuals,2)) return(RSS) def minimize_rss( training_data, validation_data, degrees ): degree_rss = {} for degree in range(1,degrees+1): poly_degree = polynomial_sframe(training_data['sqft_living'], degree) poly_features = poly_degree.column_names() poly_degree['price'] = training_data['price'] poly_model = graphlab.linear_regression.create( poly_degree, target='price', features=poly_features, validation_set=None, verbose=False) poly_validation_data = polynomial_sframe(validation_data['sqft_living'], degree) degree_rss[degree] = get_residual_sum_of_squares(poly_model, poly_validation_data, validation_data['price']) print (degree,degree_rss[degree]) min_value = min(degree_rss.values()) min_key = [key for key, value in degree_rss.iteritems() if value == min_value] return( min_key[0], min_value ) print minimize_rss( training, validation, 15 ) """ Explanation: Next you should write a loop that does the following: * For degree in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] (to get this in python type range(1, 15+1)) * Build an SFrame of polynomial data of train_data['sqft_living'] at the current degree * hint: my_features = poly_data.column_names() gives you a list e.g. ['power_1', 'power_2', 'power_3'] which you might find useful for graphlab.linear_regression.create( features = my_features) * Add train_data['price'] to the polynomial SFrame * Learn a polynomial regression model to sqft vs price with that degree on TRAIN data * Compute the RSS on VALIDATION data (here you will want to use .predict()) for that degree and you will need to make a polynmial SFrame using validation data. * Report which degree had the lowest RSS on validation data (remember python indexes from 0) (Note you can turn off the print out of linear_regression.create() with verbose = False) End of explanation """ print minimize_rss( training, testing, 15 ) """ Explanation: Quiz Question: Which degree (1, 2, …, 15) had the lowest RSS on Validation data? 6 Now that you have chosen the degree of your polynomial using validation data, compute the RSS of this model on TEST data. Report the RSS on your quiz. End of explanation """
sysid/kg
quora/LoadWeightsEasy.ipynb
mit
### imports from IPython.core.debugger import Tracer #Tracer()() import os, sys, time ### prevent the dying jupyter notebook stdout = sys.stdout #sys.stdout = sys.__stdout__ # did not work to restoure print -> console #sys.stdout = open('keras_output.txt', 'a+') #sys.stdout = stdout import sys, os, argparse, logging # NOQA import importlib from pprint import pprint from tqdm import tqdm import twBase from twBase import * # NOQA importlib.reload(twBase) #Allow relative imports to directories above cwd/ sys.path.insert(1, os.path.join(sys.path[0], '..')) %matplotlib inline np.random.seed(42) import twQuoraRun importlib.reload(twQuoraRun) #from twQuoraRun import * # NOQA args = twQuoraRun.process_command_line(["train"]) args P = twQuoraRun.get_parameters(args) """ Explanation: Transferring Weights This notebook transfers weights from models with similar architectures based on layer names. A mapping table has to be compiled manually via Excel. The weights are then transferred and the layers are set to trainable = False. Variables and Imports End of explanation """ import importlib import twQuoraModel importlib.reload(twQuoraModel) #from twQuoraModel import CNN1D #e1 = twQuoraRun.Evaluator(P, model=twQuoraModel.CNN1D) sourceModel = twQuoraRun.Evaluator(P, model=twQuoraModel.RNNCos) import importlib import twQuoraModel importlib.reload(twQuoraModel) #from twQuoraModel import All targetModel = twQuoraRun.Evaluator(P, model=twQuoraModel.RNNCosFix) # load the weights path = './data/out/40.300.200000/RNNCos.01.cl2/_weights_epoch_58.0.158.h5' sourceModel.model.model.load_weights(path) # sanity check source_emb = sourceModel.model.model.layers[2].get_weights() source_emb[0].shape target_emb = targetModel.model.model.layers[2].get_weights() target_emb[0].shape assert source_emb[0].shape == target_emb[0].shape """ Explanation: Load the Models The trained models are created and the weights imported. End of explanation """ # syntactic sugar sModel = sourceModel.model.model tModel = targetModel.model.model import keras source_layerlist = [] target_layerlist = [] for i, (tL, sL) in enumerate(twBase.outer_zip((tModel.layers, 'x'), (sModel.layers, '_'))): if isinstance(tL, keras.engine.Layer): name1 = tL.name else: name1 = tL if isinstance(sL, keras.engine.Layer): name2 = sL.name else: name2 = sL print("{:2d}: {:25.25} {!s:25.25}".format(i, name1, name2)) source_layerlist.append((i, name1, name2)) df = pd.DataFrame(source_layerlist, columns=['ix', 'target', 'source']) df.to_csv(os.path.join(P.DATA.BASE_DIR, 'weight_transfer_source.csv'), index=False, sep=';') """ Explanation: Create the Mapping and Tranfer the Weights End of explanation """ # manipulated weight transfer list df = pd.read_csv(os.path.join(P.DATA.BASE_DIR, 'weight_transfer_source.csv'), sep=';') df # Load Source weights into Target for i in range(len(df)): l1 = tModel.get_layer(df.ix[i, 'target']) l2 = sModel.get_layer(df.ix[i, 'source']) print("Copy weights from {} -> {}".format(l2.name, l1.name)) l1.set_weights(l2.get_weights()) l1.trainable = False # must be set BEVORE compile import keras # compile due to set trainable and save optimizer = getattr(keras.optimizers, P.MODEL.OPTIMIZER[0])(lr=P.MODEL.OPTIMIZER[1]['lr']) tModel.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy']) tModel.save(os.path.join(P.OUTPUT.MODEL_DIR, 'targetModel.preloaded.h5')) ### in case of Lamda Layer: serialization problem #tModel.save_weights(os.path.join(P.OUTPUT.MODEL_DIR, 'targetModel.preloaded_weights.h5')) # Load the model and check trainable from keras.models import load_model #del All # deletes the existing model # returns a compiled model # identical to the previous one model = load_model(os.path.join(P.OUTPUT.MODEL_DIR, 'targetModel.preloaded.h5')) model.get_layer('bidirectional_8').trainable # check layer topology n = 5 w = e1.model.model.layers[n].get_weights() len(w), type(w) w[0].shape, w[1].shape # check layer identity after copyting over the weights n = 5 w1 = e1.model.model.layers[n].get_weights() w2 = e2.model.model.layers[n].get_weights() if isinstance(w1, list): np.allclose(w1[0], w2[0]) w1[0].sum(), w2[0].sum() else: np.allclose(w1, w2) w1.sum(), w2.sum() # Get layer by name Cnn.get_layer("CNN1d.ConvL4.CNN1d") """ Explanation: Update the CSV file in Excel End of explanation """
d00d/quantNotebooks
Notebooks/quantopian_research_public/notebooks/lectures/Ranking_Universes_by_Factors/notebook.ipynb
unlicense
import numpy as np import statsmodels.api as sm import scipy.stats as stats import scipy from statsmodels import regression import matplotlib.pyplot as plt import seaborn as sns import pandas as pd """ Explanation: Ranking Universes by Factors By Delaney Granizo-Mackenzie and Gilbert Wassermann Part of the Quantopian Lecture Series: www.quantopian.com/lectures https://github.com/quantopian/research_public Notebook released under the Creative Commons Attribution 4.0 License. Please do not remove this attribution. One common technique in quantitative finance is that of ranking stocks in some way. This ranking can be whatever you come up with, but will often be a combination of fundamental factors and price-based signals. One example could be the following Score stocks based on 0.5 x the PE Ratio of that stock + 0.5 x the 30 day price momentum Rank stocks based on that score These ranking systems can be used to construct long-short equity strategies. The Long-Short Equity Lecture is recommended reading before this Lecture. In order to develop a good ranking system, we need to first understand how to evaluate ranking systems. We will show a demo here. WARNING: This notebook does analysis over thousands of equities and hundreds of timepoints. The resulting memory usage can crash the research server if you are running other notebooks. Please shut down other notebooks in the main research menu before running this notebook. You can tell if other notebooks are running by checking the color of the notebook symbol. Green indicates running, grey indicates not. End of explanation """ from quantopian.pipeline import Pipeline from quantopian.pipeline.data import morningstar from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import CustomFactor, Returns def make_pipeline(): """ Create and return our pipeline. We break this piece of logic out into its own function to make it easier to test and modify in isolation. """ pipe = Pipeline( columns = { 'Market Cap' : morningstar.valuation.market_cap.latest, 'PE Ratio' : morningstar.valuation_ratios.pe_ratio.latest, 'Monthly Returns': Returns(window_length=21), }) return pipe pipe = make_pipeline() """ Explanation: Getting Data The first thing we're gonna do is get monthly values for the Market Cap, P/E Ratio and Monthly Returns for every equity. Monthly Returns is a metric that takes the returns accrued over an entire month of trading by dividing the last close price by the first close price and subtracting 1. End of explanation """ from quantopian.research import run_pipeline start_date = '2013-01-01' end_date = '2015-02-01' data = run_pipeline(pipe, start_date, end_date) # remove NaN values data = data.dropna() # show data data """ Explanation: Let's take a look at the data to get a quick sense of what we have. This may take a while. End of explanation """ cap_data = data['Market Cap'].transpose().unstack() # extract series of data cap_data = cap_data.T.dropna().T # remove NaN values cap_data = cap_data.resample('M', how='last') # use last instance in month to aggregate pe_data = data['PE Ratio'].transpose().unstack() pe_data = pe_data.T.dropna().T pe_data = pe_data.resample('M', how='last') month_data = data['Monthly Returns'].transpose().unstack() month_data = month_data.T.dropna().T month_data = month_data.resample('M', how='last') """ Explanation: Now, we need to take each of these individual factors, clean them to remove NaN values and aggregate them for each month. End of explanation """ common_equities = cap_data.T.index.intersection(pe_data.T.index).intersection(month_data.T.index) """ Explanation: The next step is to figure out which equities we have data for. Data sources are never perfect, and stocks go in and out of existence with Mergers, Acquisitions, and Bankruptcies. We'll make a list of the stocks common to all three sources (our factor data sets) and then filter down both to just those stocks. End of explanation """ cap_data_filtered = cap_data[common_equities][:-1] month_forward_returns = month_data[common_equities][1:] pe_data_filtered = pe_data[common_equities][:-1] """ Explanation: Now, we will make sure that each time series is being run over identical an identical set of securities. End of explanation """ cap_data_filtered.head() """ Explanation: Here, is the filtered data for market cap over all equities for the first 5 months, as an example. End of explanation """ cap_data_filtered.rank().head() """ Explanation: Because we're dealing with ranking systems, at several points we're going to want to rank our data. Let's check how our data looks when ranked to get a sense for this. End of explanation """ scores = np.zeros(24) pvalues = np.zeros(24) for i in range(24): score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], month_forward_returns.iloc[i]) pvalues[i] = pvalue scores[i] = score plt.bar(range(1,25),scores) plt.hlines(np.mean(scores), 1, 25, colors='r', linestyles='dashed') plt.xlabel('Month') plt.xlim((1, 25)) plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation']) plt.ylabel('Rank correlation between Market Cap and 30-day forward returns'); """ Explanation: Looking at Correlations Over Time Now that we have the data, let's do something with it. Our first analysis will be to measure the monthly Spearman rank correlation coefficient between Market Cap and month-forward returns. In other words, how predictive of 30-day returns is ranking your universe by market cap. End of explanation """ scores = np.zeros(24) pvalues = np.zeros(24) for i in range(24): score, pvalue = stats.spearmanr(pe_data_filtered.iloc[i], month_forward_returns.iloc[i]) pvalues[i] = pvalue scores[i] = score plt.bar(range(1,25),scores) plt.hlines(np.mean(scores), 1, 25, colors='r', linestyles='dashed') plt.xlabel('Month') plt.xlim((1, 25)) plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation']) plt.ylabel('Rank correlation between PE Ratio and 30-day forward returns'); """ Explanation: We can see that the average correlation is positive, but varies a lot from month to month. Let's look at the same analysis, but with PE Ratio. End of explanation """ def compute_basket_returns(factor_data, forward_returns, number_of_baskets, month): data = pd.concat([factor_data.iloc[month-1],forward_returns.iloc[month-1]], axis=1) # Rank the equities on the factor values data.columns = ['Factor Value', 'Month Forward Returns'] data.sort('Factor Value', inplace=True) # How many equities per basket equities_per_basket = np.floor(len(data.index) / number_of_baskets) basket_returns = np.zeros(number_of_baskets) # Compute the returns of each basket for i in range(number_of_baskets): start = i * equities_per_basket if i == number_of_baskets - 1: # Handle having a few extra in the last basket when our number of equities doesn't divide well end = len(data.index) - 1 else: end = i * equities_per_basket + equities_per_basket # Actually compute the mean returns for each basket basket_returns[i] = data.iloc[start:end]['Month Forward Returns'].mean() return basket_returns """ Explanation: The correlation of PE Ratio and 30-day returns seems to be near 0 on average. It's important to note that this monthly and between 2012 and 2015. Different factors are predictive on differen timeframes and frequencies, so the fact that PE Ratio doesn't appear predictive here is not necessary throwing it out as a useful factor. Beyond it's usefulness in predicting returns, it can be used for risk exposure analysis as discussed in the Factor Risk Exposure Lecture. Basket Returns The next step is to compute the returns of baskets taken out of our ranking. If we rank all equities and then split them into $n$ groups, what would the mean return be of each group? We can answer this question in the following way. The first step is to create a function that will give us the mean return in each basket in a given the month and a ranking factor. End of explanation """ number_of_baskets = 10 mean_basket_returns = np.zeros(number_of_baskets) for m in range(1, 25): basket_returns = compute_basket_returns(cap_data_filtered, month_forward_returns, number_of_baskets, m) mean_basket_returns += basket_returns mean_basket_returns /= 24 # Plot the returns of each basket plt.bar(range(number_of_baskets), mean_basket_returns) plt.ylabel('Returns') plt.xlabel('Basket') plt.legend(['Returns of Each Basket']); """ Explanation: The first thing we'll do with this function is compute this for each month and then average. This should give us a sense of the relationship over a long timeframe. End of explanation """ f, axarr = plt.subplots(3, 4) for month in range(1, 13): basket_returns = compute_basket_returns(cap_data_filtered, month_forward_returns, 10, month) r = np.floor((month-1) / 4) c = (month-1) % 4 axarr[r, c].bar(range(number_of_baskets), basket_returns) axarr[r, c].xaxis.set_visible(False) # Hide the axis lables so the plots aren't super messy axarr[r, c].set_title('Month ' + str(month)) """ Explanation: Spread Consistency Of course, that's just the average relationship. To get a sense of how consistent this is, and whether or not we would want to trade on it, we should look at it over time. Here we'll look at the monthly spreads for the first year. We can see a lot of variation, and further analysis should be done to determine whether Market Cap is tradeable. End of explanation """ number_of_baskets = 10 mean_basket_returns = np.zeros(number_of_baskets) for m in range(1, 25): basket_returns = compute_basket_returns(pe_data_filtered, month_forward_returns, number_of_baskets, m) mean_basket_returns += basket_returns mean_basket_returns /= 24 # Plot the returns of each basket plt.bar(range(number_of_baskets), mean_basket_returns) plt.ylabel('Returns') plt.xlabel('Basket') plt.legend(['Returns of Each Basket']); f, axarr = plt.subplots(3, 4) for month in range(1, 13): basket_returns = compute_basket_returns(pe_data_filtered, month_forward_returns, 10, month) r = np.floor((month-1) / 4) c = (month-1) % 4 axarr[r, c].bar(range(10), basket_returns) axarr[r, c].xaxis.set_visible(False) # Hide the axis lables so the plots aren't super messy axarr[r, c].set_title('Month ' + str(month)) """ Explanation: We'll repeat the same analysis for PE Ratio. End of explanation """ scores = np.zeros(24) pvalues = np.zeros(24) for i in range(24): score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], pe_data_filtered.iloc[i]) pvalues[i] = pvalue scores[i] = score plt.bar(range(1,25),scores) plt.hlines(np.mean(scores), 1, 25, colors='r', linestyles='dashed') plt.xlabel('Month') plt.xlim((1, 25)) plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation']) plt.ylabel('Rank correlation between Market Cap and PE Ratio'); """ Explanation: Sometimes Factors are Just Other Factors Often times a new factor will be discovered that seems to induce spread, but it turns out that it is just a new and potentially more complicated way to compute a well known factor. Consider for instance the case in which you have poured tons of resources into developing a new factor, it looks great, but how do you know it's not just another factor in disguise? To check for this, there are many analyses that can be done. Correlation Analysis One of the most intuitive ways is to check what the correlation of the factors is over time. We'll plot that here. End of explanation """ scores = np.zeros(24) pvalues = np.zeros(24) for i in range(24): score, pvalue = stats.spearmanr(cap_data_filtered.iloc[i], pe_data_filtered.iloc[i]) pvalues[i] = pvalue scores[i] = score plt.bar(range(1,25),pvalues) plt.xlabel('Month') plt.xlim((1, 25)) plt.legend(['Mean Correlation over All Months', 'Monthly Rank Correlation']) plt.ylabel('Rank correlation between Market Cap and PE Ratio'); """ Explanation: And also the p-values because the correlations may not be that meaningful by themselves. End of explanation """ pe_dataframe = pd.DataFrame(pe_data_filtered.iloc[0]) pe_dataframe.columns = ['F1'] cap_dataframe = pd.DataFrame(cap_data_filtered.iloc[0]) cap_dataframe.columns = ['F2'] returns_dataframe = pd.DataFrame(month_forward_returns.iloc[0]) returns_dataframe.columns = ['Returns'] data = pe_dataframe.join(cap_dataframe).join(returns_dataframe) data = data.rank(method='first') heat = np.zeros((len(data), len(data))) for e in data.index: F1 = data.loc[e]['F1'] F2 = data.loc[e]['F2'] R = data.loc[e]['Returns'] heat[F1-1, F2-1] += R heat = scipy.signal.decimate(heat, 40) heat = scipy.signal.decimate(heat.T, 40).T p = sns.heatmap(heat, xticklabels=[], yticklabels=[]) # p.xaxis.set_ticks([]) # p.yaxis.set_ticks([]) p.xaxis.set_label_text('F1 Rank') p.yaxis.set_label_text('F2 Rank') p.set_title('Sum Rank of Returns vs Factor Ranking'); """ Explanation: There is interesting behavior, and further analysis would be needed to determine whether a relationship existed. End of explanation """
saudijack/unfpyboot
Day_02/00_Scipy/scipy-ODE-DoublePendulum.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt from IPython.display import Image from scipy import * """ Explanation: SciPy - Ordinary differential equations (ODEs) End of explanation """ from scipy.integrate import odeint, ode """ Explanation: SciPy provides two different ways to solve ODEs: An API based on the function odeint, and object-oriented API based on the class ode. Usually odeint is easier to get started with, but the ode class offers some finer level of control. Here we will use the odeint functions. For more information about the class ode, try help(ode). It does pretty much the same thing as odeint, but in an object-oriented fashion. To use odeint, first import it from the scipy.integrate module End of explanation """ Image(url='http://upload.wikimedia.org/wikipedia/commons/c/c9/Double-compound-pendulum-dimensioned.svg') """ Explanation: A system of ODEs are usually formulated on standard form before it is attacked numerically. The standard form is: $y' = f(y, t)$ where $y = [y_1(t), y_2(t), ..., y_n(t)]$ and $f$ is some function that gives the derivatives of the function $y_i(t)$. To solve an ODE we need to know the function $f$ and an initial condition, $y(0)$. Note that higher-order ODEs can always be written in this form by introducing new variables for the intermediate derivatives. Once we have defined the Python function f and array y_0 (that is $f$ and $y(0)$ in the mathematical formulation), we can use the odeint function as: y_t = odeint(f, y_0, t) where t is and array with time-coordinates for which to solve the ODE problem. y_t is an array with one row for each point in time in t, where each column corresponds to a solution y_i(t) at that point in time. We will see how we can implement f and y_0 in Python code in the examples below. Example: double pendulum Let's consider a physical example: The double compound pendulum, described in some detail here: http://en.wikipedia.org/wiki/Double_pendulum End of explanation """ g = 9.82 L = 0.5 m = 0.1 def dx(x, t): """ The right-hand side of the pendulum ODE """ x1, x2, x3, x4 = x[0], x[1], x[2], x[3] dx1 = 6.0/(m*L**2) * (2 * x3 - 3 * cos(x1-x2) * x4)/(16 - 9 * cos(x1-x2)**2) dx2 = 6.0/(m*L**2) * (8 * x4 - 3 * cos(x1-x2) * x3)/(16 - 9 * cos(x1-x2)**2) dx3 = -0.5 * m * L**2 * ( dx1 * dx2 * sin(x1-x2) + 3 * (g/L) * sin(x1)) dx4 = -0.5 * m * L**2 * (-dx1 * dx2 * sin(x1-x2) + (g/L) * sin(x2)) return [dx1, dx2, dx3, dx4] # choose an initial state x0 = [pi/4, pi/2, 0, 0] # time coodinate to solve the ODE for: from 0 to 10 seconds t = linspace(0, 10, 250) # solve the ODE problem x = odeint(dx, x0, t) # plot the angles as a function of time fig, axes = plt.subplots(1,2, figsize=(12,4)) axes[0].plot(t, x[:, 0], 'r', label="theta1") axes[0].plot(t, x[:, 1], 'b', label="theta2") x1 = + L * sin(x[:, 0]) y1 = - L * cos(x[:, 0]) x2 = x1 + L * sin(x[:, 1]) y2 = y1 - L * cos(x[:, 1]) axes[1].plot(x1, y1, 'r', label="pendulum1") axes[1].plot(x2, y2, 'b', label="pendulum2") axes[1].set_ylim([-1, 0]) axes[1].set_xlim([1, -1]); """ Explanation: The equations of motion of the pendulum are given on the wiki page: ${\dot \theta_1} = \frac{6}{m\ell^2} \frac{ 2 p_{\theta_1} - 3 \cos(\theta_1-\theta_2) p_{\theta_2}}{16 - 9 \cos^2(\theta_1-\theta_2)}$ ${\dot \theta_2} = \frac{6}{m\ell^2} \frac{ 8 p_{\theta_2} - 3 \cos(\theta_1-\theta_2) p_{\theta_1}}{16 - 9 \cos^2(\theta_1-\theta_2)}.$ ${\dot p_{\theta_1}} = -\frac{1}{2} m \ell^2 \left [ {\dot \theta_1} {\dot \theta_2} \sin (\theta_1-\theta_2) + 3 \frac{g}{\ell} \sin \theta_1 \right ]$ ${\dot p_{\theta_2}} = -\frac{1}{2} m \ell^2 \left [ -{\dot \theta_1} {\dot \theta_2} \sin (\theta_1-\theta_2) + \frac{g}{\ell} \sin \theta_2 \right]$ To make the Python code simpler to follow, let's introduce new variable names and the vector notation: $x = [\theta_1, \theta_2, p_{\theta_1}, p_{\theta_2}]$ ${\dot x_1} = \frac{6}{m\ell^2} \frac{ 2 x_3 - 3 \cos(x_1-x_2) x_4}{16 - 9 \cos^2(x_1-x_2)}$ ${\dot x_2} = \frac{6}{m\ell^2} \frac{ 8 x_4 - 3 \cos(x_1-x_2) x_3}{16 - 9 \cos^2(x_1-x_2)}$ ${\dot x_3} = -\frac{1}{2} m \ell^2 \left [ {\dot x_1} {\dot x_2} \sin (x_1-x_2) + 3 \frac{g}{\ell} \sin x_1 \right ]$ ${\dot x_4} = -\frac{1}{2} m \ell^2 \left [ -{\dot x_1} {\dot x_2} \sin (x_1-x_2) + \frac{g}{\ell} \sin x_2 \right]$ End of explanation """ from IPython.display import display, clear_output import time fig, ax = plt.subplots(figsize=(4,4)) for t_idx, tt in enumerate(t[:200]): x1 = + L * sin(x[t_idx, 0]) y1 = - L * cos(x[t_idx, 0]) x2 = x1 + L * sin(x[t_idx, 1]) y2 = y1 - L * cos(x[t_idx, 1]) ax.cla() ax.plot([0, x1], [0, y1], 'r.-') ax.plot([x1, x2], [y1, y2], 'b.-') ax.set_ylim([-1.5, 0.5]) ax.set_xlim([1, -1]) clear_output() display(fig) time.sleep(0.1) """ Explanation: Simple annimation of the pendulum motion. We will see how to make better animation in Lecture 4. End of explanation """ def dy(y, t, zeta, w0): """ The right-hand side of the damped oscillator ODE """ x, p = y[0], y[1] dx = p dp = -2 * zeta * w0 * p - w0**2 * x return [dx, dp] # initial state: y0 = [1.0, 0.0] # time coodinate to solve the ODE for t = linspace(0, 10, 1000) w0 = 2*pi*1.0 # solve the ODE problem for three different values of the damping ratio y1 = odeint(dy, y0, t, args=(0.0, w0)) # undamped y2 = odeint(dy, y0, t, args=(0.2, w0)) # under damped y3 = odeint(dy, y0, t, args=(1.0, w0)) # critial damping y4 = odeint(dy, y0, t, args=(5.0, w0)) # over damped fig, ax = plt.subplots() ax.plot(t, y1[:,0], 'k', label="undamped", linewidth=0.25) ax.plot(t, y2[:,0], 'r', label="under damped") ax.plot(t, y3[:,0], 'b', label=r"critical damping") ax.plot(t, y4[:,0], 'g', label="over damped") ax.legend(); """ Explanation: Example: Damped harmonic oscillator ODE problems are important in computational physics, so we will look at one more example: the damped harmonic oscillation. This problem is well described on the wiki page: http://en.wikipedia.org/wiki/Damping The equation of motion for the damped oscillator is: $\displaystyle \frac{\mathrm{d}^2x}{\mathrm{d}t^2} + 2\zeta\omega_0\frac{\mathrm{d}x}{\mathrm{d}t} + \omega^2_0 x = 0$ where $x$ is the position of the oscillator, $\omega_0$ is the frequency, and $\zeta$ is the damping ratio. To write this second-order ODE on standard form we introduce $p = \frac{\mathrm{d}x}{\mathrm{d}t}$: $\displaystyle \frac{\mathrm{d}p}{\mathrm{d}t} = - 2\zeta\omega_0 p - \omega^2_0 x$ $\displaystyle \frac{\mathrm{d}x}{\mathrm{d}t} = p$ In the implementation of this example we will add extra arguments to the RHS function for the ODE, rather than using global variables as we did in the previous example. As a consequence of the extra arguments to the RHS, we need to pass an keyword argument args to the odeint function: End of explanation """
spacecowboy/article-annriskgroups-source
RPartVariables.ipynb
gpl-3.0
# import stuffs %matplotlib inline import numpy as np import pandas as pd from pyplotthemes import get_savefig, classictheme as plt from lifelines.utils import k_fold_cross_validation plt.latex = True """ Explanation: RPartVariables This script runs repeated cross-validation as a search for suitable parameter values for RPart. It has been re-run for all data-sets and the plotted results for each were considered. It was determined that the default parameters had the best overall performance in terms of medial survival time. End of explanation """ from datasets import get_nwtco, get_colon, get_lung, get_pbc, get_flchain # Values of (trn, test) datasets = {} # Add the data sets for name, getter in zip(["pbc", "lung", "colon", "nwtco", "flchain"], [get_pbc, get_lung, get_colon, get_nwtco, get_flchain]): trn = getter(norm_in=True, norm_out=False, training=True) datasets[name] = trn cens = (trn.iloc[:, 1] == 0) censcount = np.sum(cens) / trn.shape[0] print(name, "censed:", censcount) """ Explanation: Load data End of explanation """ from pysurvival.rpart import RPartModel from stats import surv_area from lifelines.estimation import KaplanMeierFitter, median_survival_times def score(T_actual, labels, E_actual): ''' Return a score based on grouping ''' scores = [] labels = labels.ravel() for g in ['high', 'mid', 'low']: members = labels == g if np.sum(members) > 0: kmf = KaplanMeierFitter() kmf.fit(T_actual[members], E_actual[members], label='{}'.format(g)) # Last survival time if np.sum(E_actual[members]) > 0: lasttime = np.max(T_actual[members][E_actual[members] == 1]) else: lasttime = np.nan # End survival rate, median survival time, member count, last event subscore = (kmf.survival_function_.iloc[-1, 0], median_survival_times(kmf.survival_function_), np.sum(members), lasttime) else: # Rpart might fail in this respect subscore = (np.nan, np.nan, np.sum(members), np.nan) scores.append(subscore) return scores # Use for validation - should this be negative?? def high_median_time(T_actual, labels, E_actual): members = (labels == 'high').ravel() if np.sum(members) > 0: kmf = KaplanMeierFitter() kmf.fit(T_actual[members], E_actual[members]) return median_survival_times(kmf.survival_function_) else: return np.nan def area(T_actual, labels, E_actual): mem = (labels == 'high').ravel() if np.any(mem): high_area = surv_area(T_actual[mem], E_actual[mem]) else: high_area = np.nan mem = (labels == 'low').ravel() if np.any(mem): low_area = surv_area(T_actual[mem], E_actual[mem]) else: low_area = np.nan return [low_area, high_area] """ Explanation: Helper methods End of explanation """ default_values = dict(highlim=0.1, lowlim=0.1, minsplit=20, minbucket=None, xval=3, cp=0.01) possible_values = dict(cp=[0.01, 0.05, 0.1], xval=[0, 3, 5, 7, 10], minsplit=[1, 5, 10, 20, 50]) # Update values as we go along #try: # current_values #except NameError: current_values = default_values.copy() print(current_values) """ Explanation: Default and possible values End of explanation """ def get_winning_value(values, repeat_results, current_val): winner = 0, 0 for i, x in enumerate(values): mres = np.median(np.array(repeat_results)[:, i, :]) # For stability if mres > winner[0] or (x == current_val and mres >= winner[0]): winner = mres, x return winner[1] """ Explanation: Winner is determined by looking at median survival time. End of explanation """ d = datasets['colon'] durcol = d.columns[0] eventcol = d.columns[1] """ Explanation: Choose a data set End of explanation """ print("Starting values") for k, v in current_values.items(): print(" ", k, "=", v) # Repeat all variables n = 1score k = 3 repcount = 0 stable = False while repcount < 4 and not stable: repcount += 1 print(repcount) stable = True for key, values in sorted(possible_values.items()): print(key) models = [] for x in values: kwargs = current_values.copy() kwargs[key] = x model = RPartModel(**kwargs) model.var_label = key model.var_value = x models.append(model) # Train and test repeat_results = [] for rep in range(n): result = k_fold_cross_validation(models, d, durcol, eventcol, k=k, evaluation_measure=high_median_time, predictor='predict_classes') repeat_results.append(result) # See who won winval = get_winning_value(values, repeat_results, current_values[key]) if winval != current_values[key]: stable = False print(key, current_values[key], "->", winval) current_values[key] = winval print("\nValues optimized after", repcount, "iterations") for k, v in current_values.items(): print(" ", k, "=", v) # Just print results from above print("\nValues optimized after", repcount, "iterations") for k, v in current_values.items(): print(" ", k, "=", v) """ Explanation: Run comparison of parameters End of explanation """ #netcount = 6 models = [] # Try different epoch counts key = 'minsplit' for x in possible_values[key]: kwargs = current_values.copy() kwargs[key] = x e = RPartModel(**kwargs) e.var_label = key e.var_value = x models.append(e) n = 10 k = 3 # Repeated cross-validation repeat_results = [] for rep in range(n): print("n =", rep) # Training #result = k_fold_cross_validation(models, d, durcol, eventcol, k=k, evaluation_measure=logscore, predictor='get_log') # Validation result = k_fold_cross_validation(models, d, durcol, eventcol, k=k, evaluation_measure=area, predictor='predict_classes') repeat_results.append(result) #repeat_results """ Explanation: Get some plottable results Let's see how the parameters perform End of explanation """ def plot_score_multiple(repeat_results, models): boxes = [] labels = [] var_label = None for i, m in enumerate(models): labels.append(str(m.var_value)) var_label = m.var_label vals = [] for result in repeat_results: for kscore in result[i]: vals.append(kscore[1]) boxes.append(vals) plt.figure() plt.boxplot(boxes, labels=labels, vert=False, colors=plt.colors[:len(models)]) plt.ylabel(var_label) plt.title("Cross-validation: n={} k={}".format(n, k)) plt.xlabel("Something..") #plt.gca().set_xscale('log') plot_score_multiple(repeat_results, models) def plot_score(repeat_results, models): boxes = [] labels = [] var_label = None # Makes no sense for low here for many datasets... for i, m in enumerate(models): labels.append(str(m.var_value)) var_label = m.var_label vals = [] for result in repeat_results: vals.extend(result[i]) boxes.append(vals) plt.figure() plt.boxplot(boxes, labels=labels, vert=False, colors=plt.colors[:len(models)]) plt.ylabel(var_label) plt.title("Cross-validation: n={} k={}".format(n, k)) plt.xlabel("Median survival time (max={:.0f})".format(d[durcol].max())) #plt.gca().set_xscale('log') plot_score(repeat_results, models) """ Explanation: Plot results End of explanation """
thesby/CaffeAssistant
tutorial/ipynb/02-fine-tuning.ipynb
mit
caffe_root = '../' # this file should be run from {caffe_root}/examples (otherwise change this line) import sys sys.path.insert(0, caffe_root + 'python') import caffe caffe.set_device(0) caffe.set_mode_gpu() import numpy as np from pylab import * %matplotlib inline import tempfile # Helper function for deprocessing preprocessed images, e.g., for display. def deprocess_net_image(image): image = image.copy() # don't modify destructively image = image[::-1] # BGR -> RGB image = image.transpose(1, 2, 0) # CHW -> HWC image += [123, 117, 104] # (approximately) undo mean subtraction # clamp values in [0, 255] image[image < 0], image[image > 255] = 0, 255 # round and cast from float32 to uint8 image = np.round(image) image = np.require(image, dtype=np.uint8) return image """ Explanation: Fine-tuning a Pretrained Network for Style Recognition In this example, we'll explore a common approach that is particularly useful in real-world applications: take a pre-trained Caffe network and fine-tune the parameters on your custom data. The advantage of this approach is that, since pre-trained networks are learned on a large set of images, the intermediate layers capture the "semantics" of the general visual appearance. Think of it as a very powerful generic visual feature that you can treat as a black box. On top of that, only a relatively small amount of data is needed for good performance on the target task. First, we will need to prepare the data. This involves the following parts: (1) Get the ImageNet ilsvrc pretrained model with the provided shell scripts. (2) Download a subset of the overall Flickr style dataset for this demo. (3) Compile the downloaded Flickr dataset into a database that Caffe can then consume. End of explanation """ # Download just a small subset of the data for this exercise. # (2000 of 80K images, 5 of 20 labels.) # To download the entire dataset, set `full_dataset = True`. full_dataset = False if full_dataset: NUM_STYLE_IMAGES = NUM_STYLE_LABELS = -1 else: NUM_STYLE_IMAGES = 2000 NUM_STYLE_LABELS = 5 # This downloads the ilsvrc auxiliary data (mean file, etc), # and a subset of 2000 images for the style recognition task. import os os.chdir(caffe_root) # run scripts from caffe root !data/ilsvrc12/get_ilsvrc_aux.sh !scripts/download_model_binary.py models/bvlc_reference_caffenet !python examples/finetune_flickr_style/assemble_data.py \ --workers=-1 --seed=1701 \ --images=$NUM_STYLE_IMAGES --label=$NUM_STYLE_LABELS # back to examples os.chdir('examples') """ Explanation: 1. Setup and dataset download Download data required for this exercise. get_ilsvrc_aux.sh to download the ImageNet data mean, labels, etc. download_model_binary.py to download the pretrained reference model finetune_flickr_style/assemble_data.py downloadsd the style training and testing data We'll download just a small subset of the full dataset for this exercise: just 2000 of the 80K images, from 5 of the 20 style categories. (To download the full dataset, set full_dataset = True in the cell below.) End of explanation """ import os weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel' assert os.path.exists(weights) """ Explanation: Define weights, the path to the ImageNet pretrained weights we just downloaded, and make sure it exists. End of explanation """ # Load ImageNet labels to imagenet_labels imagenet_label_file = caffe_root + 'data/ilsvrc12/synset_words.txt' imagenet_labels = list(np.loadtxt(imagenet_label_file, str, delimiter='\t')) assert len(imagenet_labels) == 1000 print 'Loaded ImageNet labels:\n', '\n'.join(imagenet_labels[:10] + ['...']) # Load style labels to style_labels style_label_file = caffe_root + 'examples/finetune_flickr_style/style_names.txt' style_labels = list(np.loadtxt(style_label_file, str, delimiter='\n')) if NUM_STYLE_LABELS > 0: style_labels = style_labels[:NUM_STYLE_LABELS] print '\nLoaded style labels:\n', ', '.join(style_labels) """ Explanation: Load the 1000 ImageNet labels from ilsvrc12/synset_words.txt, and the 5 style labels from finetune_flickr_style/style_names.txt. End of explanation """ from caffe import layers as L from caffe import params as P weight_param = dict(lr_mult=1, decay_mult=1) bias_param = dict(lr_mult=2, decay_mult=0) learned_param = [weight_param, bias_param] frozen_param = [dict(lr_mult=0)] * 2 def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1, param=learned_param, weight_filler=dict(type='gaussian', std=0.01), bias_filler=dict(type='constant', value=0.1)): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, num_output=nout, pad=pad, group=group, param=param, weight_filler=weight_filler, bias_filler=bias_filler) return conv, L.ReLU(conv, in_place=True) def fc_relu(bottom, nout, param=learned_param, weight_filler=dict(type='gaussian', std=0.005), bias_filler=dict(type='constant', value=0.1)): fc = L.InnerProduct(bottom, num_output=nout, param=param, weight_filler=weight_filler, bias_filler=bias_filler) return fc, L.ReLU(fc, in_place=True) def max_pool(bottom, ks, stride=1): return L.Pooling(bottom, pool=P.Pooling.MAX, kernel_size=ks, stride=stride) def caffenet(data, label=None, train=True, num_classes=1000, classifier_name='fc8', learn_all=False): """Returns a NetSpec specifying CaffeNet, following the original proto text specification (./models/bvlc_reference_caffenet/train_val.prototxt).""" n = caffe.NetSpec() n.data = data param = learned_param if learn_all else frozen_param n.conv1, n.relu1 = conv_relu(n.data, 11, 96, stride=4, param=param) n.pool1 = max_pool(n.relu1, 3, stride=2) n.norm1 = L.LRN(n.pool1, local_size=5, alpha=1e-4, beta=0.75) n.conv2, n.relu2 = conv_relu(n.norm1, 5, 256, pad=2, group=2, param=param) n.pool2 = max_pool(n.relu2, 3, stride=2) n.norm2 = L.LRN(n.pool2, local_size=5, alpha=1e-4, beta=0.75) n.conv3, n.relu3 = conv_relu(n.norm2, 3, 384, pad=1, param=param) n.conv4, n.relu4 = conv_relu(n.relu3, 3, 384, pad=1, group=2, param=param) n.conv5, n.relu5 = conv_relu(n.relu4, 3, 256, pad=1, group=2, param=param) n.pool5 = max_pool(n.relu5, 3, stride=2) n.fc6, n.relu6 = fc_relu(n.pool5, 4096, param=param) if train: n.drop6 = fc7input = L.Dropout(n.relu6, in_place=True) else: fc7input = n.relu6 n.fc7, n.relu7 = fc_relu(fc7input, 4096, param=param) if train: n.drop7 = fc8input = L.Dropout(n.relu7, in_place=True) else: fc8input = n.relu7 # always learn fc8 (param=learned_param) fc8 = L.InnerProduct(fc8input, num_output=num_classes, param=learned_param) # give fc8 the name specified by argument `classifier_name` n.__setattr__(classifier_name, fc8) if not train: n.probs = L.Softmax(fc8) if label is not None: n.label = label n.loss = L.SoftmaxWithLoss(fc8, n.label) n.acc = L.Accuracy(fc8, n.label) # write the net to a temporary file and return its filename with tempfile.NamedTemporaryFile(delete=False) as f: f.write(str(n.to_proto())) return f.name """ Explanation: 2. Defining and running the nets We'll start by defining caffenet, a function which initializes the CaffeNet architecture (a minor variant on AlexNet), taking arguments specifying the data and number of output classes. End of explanation """ dummy_data = L.DummyData(shape=dict(dim=[1, 3, 227, 227])) imagenet_net_filename = caffenet(data=dummy_data, train=False) imagenet_net = caffe.Net(imagenet_net_filename, weights, caffe.TEST) """ Explanation: Now, let's create a CaffeNet that takes unlabeled "dummy data" as input, allowing us to set its input images externally and see what ImageNet classes it predicts. End of explanation """ def style_net(train=True, learn_all=False, subset=None): if subset is None: subset = 'train' if train else 'test' source = caffe_root + 'data/flickr_style/%s.txt' % subset transform_param = dict(mirror=train, crop_size=227, mean_file=caffe_root + 'data/ilsvrc12/imagenet_mean.binaryproto') style_data, style_label = L.ImageData( transform_param=transform_param, source=source, batch_size=50, new_height=256, new_width=256, ntop=2) return caffenet(data=style_data, label=style_label, train=train, num_classes=NUM_STYLE_LABELS, classifier_name='fc8_flickr', learn_all=learn_all) """ Explanation: Define a function style_net which calls caffenet on data from the Flickr style dataset. The new network will also have the CaffeNet architecture, with differences in the input and output: the input is the Flickr style data we downloaded, provided by an ImageData layer the output is a distribution over 20 classes rather than the original 1000 ImageNet classes the classification layer is renamed from fc8 to fc8_flickr to tell Caffe not to load the original classifier (fc8) weights from the ImageNet-pretrained model End of explanation """ untrained_style_net = caffe.Net(style_net(train=False, subset='train'), weights, caffe.TEST) untrained_style_net.forward() style_data_batch = untrained_style_net.blobs['data'].data.copy() style_label_batch = np.array(untrained_style_net.blobs['label'].data, dtype=np.int32) """ Explanation: Use the style_net function defined above to initialize untrained_style_net, a CaffeNet with input images from the style dataset and weights from the pretrained ImageNet model. Call forward on untrained_style_net to get a batch of style training data. End of explanation """ def disp_preds(net, image, labels, k=5, name='ImageNet'): input_blob = net.blobs['data'] net.blobs['data'].data[0, ...] = image probs = net.forward(start='conv1')['probs'][0] top_k = (-probs).argsort()[:k] print 'top %d predicted %s labels =' % (k, name) print '\n'.join('\t(%d) %5.2f%% %s' % (i+1, 100*probs[p], labels[p]) for i, p in enumerate(top_k)) def disp_imagenet_preds(net, image): disp_preds(net, image, imagenet_labels, name='ImageNet') def disp_style_preds(net, image): disp_preds(net, image, style_labels, name='style') batch_index = 8 image = style_data_batch[batch_index] plt.imshow(deprocess_net_image(image)) print 'actual label =', style_labels[style_label_batch[batch_index]] disp_imagenet_preds(imagenet_net, image) """ Explanation: Pick one of the style net training images from the batch of 50 (we'll arbitrarily choose #8 here). Display it, then run it through imagenet_net, the ImageNet-pretrained network to view its top 5 predicted classes from the 1000 ImageNet classes. Below we chose an image where the network's predictions happen to be reasonable, as the image is of a beach, and "sandbar" and "seashore" both happen to be ImageNet-1000 categories. For other images, the predictions won't be this good, sometimes due to the network actually failing to recognize the object(s) present in the image, but perhaps even more often due to the fact that not all images contain an object from the (somewhat arbitrarily chosen) 1000 ImageNet categories. Modify the batch_index variable by changing its default setting of 8 to another value from 0-49 (since the batch size is 50) to see predictions for other images in the batch. (To go beyond this batch of 50 images, first rerun the above cell to load a fresh batch of data into style_net.) End of explanation """ disp_style_preds(untrained_style_net, image) """ Explanation: We can also look at untrained_style_net's predictions, but we won't see anything interesting as its classifier hasn't been trained yet. In fact, since we zero-initialized the classifier (see caffenet definition -- no weight_filler is passed to the final InnerProduct layer), the softmax inputs should be all zero and we should therefore see a predicted probability of 1/N for each label (for N labels). Since we set N = 5, we get a predicted probability of 20% for each class. End of explanation """ diff = untrained_style_net.blobs['fc7'].data[0] - imagenet_net.blobs['fc7'].data[0] error = (diff ** 2).sum() assert error < 1e-8 """ Explanation: We can also verify that the activations in layer fc7 immediately before the classification layer are the same as (or very close to) those in the ImageNet-pretrained model, since both models are using the same pretrained weights in the conv1 through fc7 layers. End of explanation """ del untrained_style_net """ Explanation: Delete untrained_style_net to save memory. (Hang on to imagenet_net as we'll use it again later.) End of explanation """ from caffe.proto import caffe_pb2 def solver(train_net_path, test_net_path=None, base_lr=0.001): s = caffe_pb2.SolverParameter() # Specify locations of the train and (maybe) test networks. s.train_net = train_net_path if test_net_path is not None: s.test_net.append(test_net_path) s.test_interval = 1000 # Test after every 1000 training iterations. s.test_iter.append(100) # Test on 100 batches each time we test. # The number of iterations over which to average the gradient. # Effectively boosts the training batch size by the given factor, without # affecting memory utilization. s.iter_size = 1 s.max_iter = 100000 # # of times to update the net (training iterations) # Solve using the stochastic gradient descent (SGD) algorithm. # Other choices include 'Adam' and 'RMSProp'. s.type = 'SGD' # Set the initial learning rate for SGD. s.base_lr = base_lr # Set `lr_policy` to define how the learning rate changes during training. # Here, we 'step' the learning rate by multiplying it by a factor `gamma` # every `stepsize` iterations. s.lr_policy = 'step' s.gamma = 0.1 s.stepsize = 20000 # Set other SGD hyperparameters. Setting a non-zero `momentum` takes a # weighted average of the current gradient and previous gradients to make # learning more stable. L2 weight decay regularizes learning, to help prevent # the model from overfitting. s.momentum = 0.9 s.weight_decay = 5e-4 # Display the current training loss and accuracy every 1000 iterations. s.display = 1000 # Snapshots are files used to store networks we've trained. Here, we'll # snapshot every 10K iterations -- ten times during training. s.snapshot = 10000 s.snapshot_prefix = caffe_root + 'models/finetune_flickr_style/finetune_flickr_style' # Train on the GPU. Using the CPU to train large networks is very slow. s.solver_mode = caffe_pb2.SolverParameter.GPU # Write the solver to a temporary file and return its filename. with tempfile.NamedTemporaryFile(delete=False) as f: f.write(str(s)) return f.name """ Explanation: 3. Training the style classifier Now, we'll define a function solver to create our Caffe solvers, which are used to train the network (learn its weights). In this function we'll set values for various parameters used for learning, display, and "snapshotting" -- see the inline comments for explanations of what they mean. You may want to play with some of the learning parameters to see if you can improve on the results here! End of explanation """ def run_solvers(niter, solvers, disp_interval=10): """Run solvers for niter iterations, returning the loss and accuracy recorded each iteration. `solvers` is a list of (name, solver) tuples.""" blobs = ('loss', 'acc') loss, acc = ({name: np.zeros(niter) for name, _ in solvers} for _ in blobs) for it in range(niter): for name, s in solvers: s.step(1) # run a single SGD step in Caffe loss[name][it], acc[name][it] = (s.net.blobs[b].data.copy() for b in blobs) if it % disp_interval == 0 or it + 1 == niter: loss_disp = '; '.join('%s: loss=%.3f, acc=%2d%%' % (n, loss[n][it], np.round(100*acc[n][it])) for n, _ in solvers) print '%3d) %s' % (it, loss_disp) # Save the learned weights from both nets. weight_dir = tempfile.mkdtemp() weights = {} for name, s in solvers: filename = 'weights.%s.caffemodel' % name weights[name] = os.path.join(weight_dir, filename) s.net.save(weights[name]) return loss, acc, weights """ Explanation: Now we'll invoke the solver to train the style net's classification layer. For the record, if you want to train the network using only the command line tool, this is the command: <code> build/tools/caffe train \ -solver models/finetune_flickr_style/solver.prototxt \ -weights models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel \ -gpu 0 </code> However, we will train using Python in this example. We'll first define run_solvers, a function that takes a list of solvers and steps each one in a round robin manner, recording the accuracy and loss values each iteration. At the end, the learned weights are saved to a file. End of explanation """ niter = 200 # number of iterations to train # Reset style_solver as before. style_solver_filename = solver(style_net(train=True)) style_solver = caffe.get_solver(style_solver_filename) style_solver.net.copy_from(weights) # For reference, we also create a solver that isn't initialized from # the pretrained ImageNet weights. scratch_style_solver_filename = solver(style_net(train=True)) scratch_style_solver = caffe.get_solver(scratch_style_solver_filename) print 'Running solvers for %d iterations...' % niter solvers = [('pretrained', style_solver), ('scratch', scratch_style_solver)] loss, acc, weights = run_solvers(niter, solvers) print 'Done.' train_loss, scratch_train_loss = loss['pretrained'], loss['scratch'] train_acc, scratch_train_acc = acc['pretrained'], acc['scratch'] style_weights, scratch_style_weights = weights['pretrained'], weights['scratch'] # Delete solvers to save memory. del style_solver, scratch_style_solver, solvers """ Explanation: Let's create and run solvers to train nets for the style recognition task. We'll create two solvers -- one (style_solver) will have its train net initialized to the ImageNet-pretrained weights (this is done by the call to the copy_from method), and the other (scratch_style_solver) will start from a randomly initialized net. During training, we should see that the ImageNet pretrained net is learning faster and attaining better accuracies than the scratch net. End of explanation """ plot(np.vstack([train_loss, scratch_train_loss]).T) xlabel('Iteration #') ylabel('Loss') plot(np.vstack([train_acc, scratch_train_acc]).T) xlabel('Iteration #') ylabel('Accuracy') """ Explanation: Let's look at the training loss and accuracy produced by the two training procedures. Notice how quickly the ImageNet pretrained model's loss value (blue) drops, and that the randomly initialized model's loss value (green) barely (if at all) improves from training only the classifier layer. End of explanation """ def eval_style_net(weights, test_iters=10): test_net = caffe.Net(style_net(train=False), weights, caffe.TEST) accuracy = 0 for it in xrange(test_iters): accuracy += test_net.forward()['acc'] accuracy /= test_iters return test_net, accuracy test_net, accuracy = eval_style_net(style_weights) print 'Accuracy, trained from ImageNet initialization: %3.1f%%' % (100*accuracy, ) scratch_test_net, scratch_accuracy = eval_style_net(scratch_style_weights) print 'Accuracy, trained from random initialization: %3.1f%%' % (100*scratch_accuracy, ) """ Explanation: Let's take a look at the testing accuracy after running 200 iterations of training. Note that we're classifying among 5 classes, giving chance accuracy of 20%. We expect both results to be better than chance accuracy (20%), and we further expect the result from training using the ImageNet pretraining initialization to be much better than the one from training from scratch. Let's see. End of explanation """ end_to_end_net = style_net(train=True, learn_all=True) # Set base_lr to 1e-3, the same as last time when learning only the classifier. # You may want to play around with different values of this or other # optimization parameters when fine-tuning. For example, if learning diverges # (e.g., the loss gets very large or goes to infinity/NaN), you should try # decreasing base_lr (e.g., to 1e-4, then 1e-5, etc., until you find a value # for which learning does not diverge). base_lr = 0.001 style_solver_filename = solver(end_to_end_net, base_lr=base_lr) style_solver = caffe.get_solver(style_solver_filename) style_solver.net.copy_from(style_weights) scratch_style_solver_filename = solver(end_to_end_net, base_lr=base_lr) scratch_style_solver = caffe.get_solver(scratch_style_solver_filename) scratch_style_solver.net.copy_from(scratch_style_weights) print 'Running solvers for %d iterations...' % niter solvers = [('pretrained, end-to-end', style_solver), ('scratch, end-to-end', scratch_style_solver)] _, _, finetuned_weights = run_solvers(niter, solvers) print 'Done.' style_weights_ft = finetuned_weights['pretrained, end-to-end'] scratch_style_weights_ft = finetuned_weights['scratch, end-to-end'] # Delete solvers to save memory. del style_solver, scratch_style_solver, solvers """ Explanation: 4. End-to-end finetuning for style Finally, we'll train both nets again, starting from the weights we just learned. The only difference this time is that we'll be learning the weights "end-to-end" by turning on learning in all layers of the network, starting from the RGB conv1 filters directly applied to the input image. We pass the argument learn_all=True to the style_net function defined earlier in this notebook, which tells the function to apply a positive (non-zero) lr_mult value for all parameters. Under the default, learn_all=False, all parameters in the pretrained layers (conv1 through fc7) are frozen (lr_mult = 0), and we learn only the classifier layer fc8_flickr. Note that both networks start at roughly the accuracy achieved at the end of the previous training session, and improve significantly with end-to-end training. To be more scientific, we'd also want to follow the same additional training procedure without the end-to-end training, to ensure that our results aren't better simply because we trained for twice as long. Feel free to try this yourself! End of explanation """ test_net, accuracy = eval_style_net(style_weights_ft) print 'Accuracy, finetuned from ImageNet initialization: %3.1f%%' % (100*accuracy, ) scratch_test_net, scratch_accuracy = eval_style_net(scratch_style_weights_ft) print 'Accuracy, finetuned from random initialization: %3.1f%%' % (100*scratch_accuracy, ) """ Explanation: Let's now test the end-to-end finetuned models. Since all layers have been optimized for the style recognition task at hand, we expect both nets to get better results than the ones above, which were achieved by nets with only their classifier layers trained for the style task (on top of either ImageNet pretrained or randomly initialized weights). End of explanation """ plt.imshow(deprocess_net_image(image)) disp_style_preds(test_net, image) """ Explanation: We'll first look back at the image we started with and check our end-to-end trained model's predictions. End of explanation """ batch_index = 1 image = test_net.blobs['data'].data[batch_index] plt.imshow(deprocess_net_image(image)) print 'actual label =', style_labels[int(test_net.blobs['label'].data[batch_index])] disp_style_preds(test_net, image) """ Explanation: Whew, that looks a lot better than before! But note that this image was from the training set, so the net got to see its label at training time. Finally, we'll pick an image from the test set (an image the model hasn't seen) and look at our end-to-end finetuned style model's predictions for it. End of explanation """ disp_style_preds(scratch_test_net, image) """ Explanation: We can also look at the predictions of the network trained from scratch. We see that in this case, the scratch network also predicts the correct label for the image (Pastel), but is much less confident in its prediction than the pretrained net. End of explanation """ disp_imagenet_preds(imagenet_net, image) """ Explanation: Of course, we can again look at the ImageNet model's predictions for the above image: End of explanation """
jhprinz/openpathsampling
examples/toy_model_mstis/toy_mstis_A3_new_analysis.ipynb
lgpl-2.1
%%time storage = paths.AnalysisStorage(filename) network = storage.networks[0] scheme = storage.schemes[0] stateA = storage.volumes['A'] stateB = storage.volumes['B'] stateC = storage.volumes['C'] all_states = [stateA, stateB, stateC] # all_states gives the ordering """ Explanation: TIS Analysis Framework Examples This notebook provides an overview of the TIS analysis framework in OpenPathSampling. We start with the StandardTISAnalysis object, which will probably meet the needs of most users. Then we go into details of how to set up custom objects for analysis, and how to assemble them into a generic TISAnalysis object. End of explanation """ from openpathsampling.analysis.tis import StandardTISAnalysis # the scheme is only required if using the minus move for the flux tis_analysis = StandardTISAnalysis( network=network, scheme=scheme, max_lambda_calcs={t: {'bin_width': 0.05, 'bin_range': (0.0, 0.5)} for t in network.sampling_transitions} ) %%time tis_analysis.rate_matrix(steps=storage.steps).to_pandas(order=all_states) """ Explanation: Simplified Combined Analysis The StandardTISAnalysis object makes it very easy to perform the main TIS rate analysis. Furthermore, it caches all the intemediate results, so they can also be analyzed. End of explanation """ tis_analysis.results.keys() """ Explanation: Note that there are many options for setting up the StandardTISAnalysis object. Most customizationizations to the analysis can be performed by changing the initialization parameters of that object; see its documentation for details. Looking at the parts of the calculation Once you run the rate calculation (or if you run tis_analysis.calculate(steps), you have already cached a large number of subcalculations. All of those are available in the results dictionary, although the analysis object has a number of conveniences to access some of them. Looking at the keys of the results dictionary, we can see what has been cached: End of explanation """ tis_analysis.flux_matrix """ Explanation: In practice, however, we won't go directly to the results dictionary. We'd rather use the convenience methods that make it easier to get to the interesting results. We'll start by looking at the flux: End of explanation """ for transition in network.sampling_transitions: label = transition.name tcp = tis_analysis.total_crossing_probability[transition] plt.plot(tcp.x, np.log(tcp), label=label) plt.title("Total Crossing Probability") plt.xlabel("$\lambda$") plt.ylabel("$\ln(P(\lambda | X_0))$") plt.legend(); """ Explanation: Next we look at the total crossing probability (i.e., the crossing probability, joined by WHAM) for each sampled transition. We could also look at this per physical transition, but of course $A\to B$ and $A\to C$ are identical in MSTIS -- only the initial state matters. End of explanation """ state_pair = (stateA, stateB) trans = network.transitions[state_pair] for ens in trans.ensembles: crossing = tis_analysis.crossing_probability(ens) label = ens.name plt.plot(crossing.x, np.log(crossing), label=label) tcp = tis_analysis.total_crossing_probability[state_pair] plt.plot(tcp.x, np.log(tcp), '-k', label="total crossing probability") plt.title("Crossing Probabilities, " + stateA.name + " -> " + stateB.name) plt.xlabel("$\lambda$") plt.ylabel("$\ln(P_A(\lambda | \lambda_i))$") plt.legend(); """ Explanation: We may want to look in more detail at one of these, by checking the per-ensemble crossing probability (as well at the total crossing probability). Here we select based on the $A\to B$ transition, we would get the same results if we selected the transition using either trans = network.from_state[stateA] or trans = network.transitions[(stateA, stateC)]. End of explanation """ tis_analysis.conditional_transition_probability """ Explanation: Finally, we look at the last part of the rate calculation: the conditional transition probability. This is calculated for the outermost interface in each interface set. End of explanation """ from openpathsampling.analysis.tis import MinusMoveFlux flux_calc = MinusMoveFlux(scheme) """ Explanation: Individual components of the analysis The combined analysis is the easiest way to perform analysis, but if you need to customize things (or if you want to compare different calculation methods) you might want to create objects for components of the analysis individually. Note that unlike the StandardTISAnalysis object, these do not cache their intermediate results. Flux from the minus move End of explanation """ %%time fluxes = flux_calc.calculate(storage.steps) fluxes """ Explanation: To calculate the fluxes, we use the .calculate method of the MinusMoveFlux object: End of explanation """ %%time flux_dicts = flux_calc.intermediates(storage.steps)[0] flux_dicts """ Explanation: The minus move flux calculates some intermediate information along the way, which can be of use for further analysis. This is cached when using the StandardTISAnalysis, but can always be recalculated. The intermediate maps each (state, interface) pair to a dictionary. For details on the structure of that dictionary, see the documentation of TrajectoryTransitionAnalysis.analyze_flux. End of explanation """ from openpathsampling.analysis.tis import DictFlux dict_flux = DictFlux(fluxes) dict_flux.calculate(storage.steps) """ Explanation: Flux from existing dictionary The DictFlux class (which is required for MISTIS, and often provides better statistics than the minus move flux in other cases) takes a pre-calculated flux dictionary for initialization, and always returns that dictionary. The dictionary is in the same format as the fluxes returned by the MinusMoveFlux.calculate method; here, we'll just use the results we calculated above: End of explanation """ dict_flux.calculate(None) """ Explanation: Note that DictFlux.calculate just echoes back the dictionary we gave it, so it doesn't actually care if we give it the steps argument or not: End of explanation """ transition = network.sampling_transitions[0] print transition from openpathsampling.analysis.tis import FullHistogramMaxLambdas, TotalCrossingProbability from openpathsampling.numerics import WHAM max_lambda_calc = FullHistogramMaxLambdas( transition=transition, hist_parameters={'bin_width': 0.05, 'bin_range': (0.0, 0.5)} ) """ Explanation: This object can be used to provide the flux part of the TIS calculation, in exactly the same way a MinusMoveFlux object does. Total crossing probability function To calculate the total crossing probability, we must first calculate the individual ensemble crossing probabilities. This is done by creating a histogram of the maximum values of the order parameter. The class to do that is FullHistogramMaxLambdas. Then we'll create the TotalCrossingProbability. End of explanation """ combiner = WHAM(interfaces=transition.interfaces.lambdas) """ Explanation: We can also change the function used to calculate the maximum value of the order parameter with the max_lambda_func parameter. This can be useful to calculate the crossing probabilities along some other order parameter. To calculate the total crossing probability function, we also need a method for combining the ensemble crossing probability functions. We'll use the default WHAM here; see its documentation for details on how it can be customized. End of explanation """ total_crossing = TotalCrossingProbability( max_lambda_calc=max_lambda_calc, combiner=combiner ) tcp = total_crossing.calculate(storage.steps) plt.plot(tcp.x, np.log(tcp)) plt.title("Total Crossing Probability, exiting " + transition.stateA.name) plt.xlabel("$\lambda$") plt.ylabel("$\ln(P_A(\lambda | \lambda_i))$") """ Explanation: Now we can put these together into the total crossing probability function: End of explanation """ from openpathsampling.analysis.tis import ConditionalTransitionProbability outermost_ensembles = [trans.ensembles[-1] for trans in network.sampling_transitions] cond_transition = ConditionalTransitionProbability( ensembles=outermost_ensembles, states=network.states ) ctp = cond_transition.calculate(storage.steps) ctp """ Explanation: Conditional transition probability The last part of the standard calculation is the conditional transition probability. We'll make a version of this that works for all ensembles: End of explanation """ from openpathsampling.analysis.tis import StandardTransitionProbability, TISAnalysis """ Explanation: StandardTISAnalysis.conditional_transition_probability converts this into a pandas.DataFrame, which gives prettier printing. However, the same data in included in this dict-of-dict structure. Assembling a TIS analysis from scratch If you're using the "standard" TIS approach, then the StandardTISAnalysis object is the most efficient way to do it. However, if you want to use another analysis approach, it can be useful to see how the "standard" approach can be assembled. This won't have all the shortcuts or saved intermediates that the specialized object does, but it will use the same algorithms to get the same results. End of explanation """ tcp_methods = { trans: TotalCrossingProbability( max_lambda_calc=FullHistogramMaxLambdas( transition=trans, hist_parameters={'bin_width': 0.05, 'bin_range': (0.0, 0.5)} ) ) for trans in network.transitions.values() } """ Explanation: Some of the objects that we created in previous sections can be reused here. In particular, there is only only one flux calculation and only one conditional transitional transition probability per reaction network. However, the total crossing probability method is dependent on the transition (different order parameters might have different histrogram parameters). So we need to associate each transition with a different TotalCrossingProbability object. In this example, we take the default behavior of WHAM (instead of specifying in explicitly, as above). End of explanation """ transition_probability_methods = { trans: StandardTransitionProbability( transition=trans, tcp_method=tcp_methods[trans], ctp_method=cond_transition ) for trans in network.transitions.values() } """ Explanation: The general TISAnalysis object makes the most simple splitting: flux and transition probability. A single flux calculation is used for all transitions, but each transition has a different transition probability (since each transition can have a different total crossing probability). We make those objects here. End of explanation """ analysis = TISAnalysis( network=network, flux_method=dict_flux, transition_probability_methods=transition_probability_methods ) analysis.rate_matrix(storage.steps) """ Explanation: Finally we put this all together into a TISAnalysis object, and calculate the rate matrix. End of explanation """
DouglasLeeTucker/DECam_PGCM
notebooks/DESY6DeepFields_PhotomZPs_tied_to_fgcm.ipynb
gpl-3.0
import numpy as np import pandas as pd from scipy import interpolate import glob import math import os import subprocess import sys import gc import glob import pickle import easyaccess as ea #import AlasBabylon import fitsio from astropy.io import fits import astropy.coordinates as coord from astropy.coordinates import SkyCoord import astropy.units as u from astropy.table import Table, vstack import tempfile import matplotlib.pyplot as plt %matplotlib inline # Useful class to stop "Run All" at a cell # containing the command "raise StopExecution" class StopExecution(Exception): def _render_traceback_(self): pass """ Explanation: DES Y6 Deep Field Exposures: Photometric Zeropoints tied to FGCM 1. Setup End of explanation """ verbose = 1 tag_des = 'Y6A2_FINALCUT' # Official tag for DES Y6A2_FINALCUT tag_decade = 'DECADE_FINALCUT' # Tag for DECADE rawdata_dir = '../RawData' zeropoints_dir='../Zeropoints' bandList = ['g', 'r', 'i', 'z', 'Y'] """ Explanation: 2. User Input 2.1. General User Input End of explanation """ do_calc_fgcm_psf_zps = True do_calc_fgcm_aper8_zps = True """ Explanation: 2.2. Logical Variables to Indicate which Code Cells to Run End of explanation """ region_name_list = [ 'VVDSF14', 'VVDSF22', 'DEEP2', 'SN-E', 'SN-X_err', 'SN-X', 'ALHAMBRA2', 'SN-S', 'SN-C', 'EDFS', 'MACS0416', 'SN-S_err', 'COSMOS' ] region_ramin = { 'VVDSF14':208., 'VVDSF22':333., 'DEEP2':351., 'SN-E':6., 'SN-X_err':13., 'SN-X':32., 'ALHAMBRA2':35., 'SN-S':39.5, 'SN-C':50., 'EDFS':55., 'MACS0416':62., 'SN-S_err':83.5, 'COSMOS':148. } region_ramax = { 'VVDSF14':212., 'VVDSF22':337., 'DEEP2':354., 'SN-E':12., 'SN-X_err':17., 'SN-X':38., 'ALHAMBRA2':39., 'SN-S':44.5, 'SN-C':56., 'EDFS':67., 'MACS0416':66., 'SN-S_err':88., 'COSMOS':153. } region_decmin = { 'VVDSF14':3., 'VVDSF22':-1.5, 'DEEP2':-1.5, 'SN-E':-46., 'SN-X_err':-32., 'SN-X':-8., 'ALHAMBRA2':-0.5, 'SN-S':-2.5, 'SN-C':-31., 'EDFS':-51., 'MACS0416':-25.5, 'SN-S_err':-38., 'COSMOS':0.5 } region_decmax = { 'VVDSF14':7., 'VVDSF22':1.5, 'DEEP2':1.5, 'SN-E':-41., 'SN-X_err':-29., 'SN-X':-3., 'ALHAMBRA2':2.5, 'SN-S':1.5, 'SN-C':-25., 'EDFS':-46., 'MACS0416':-22.5, 'SN-S_err':-35., 'COSMOS':4.0 } for regionName in region_name_list: print regionName, region_ramin[regionName], region_ramax[regionName], region_decmin[regionName], region_decmax[regionName] """ Explanation: 2.3. Sky Region Definitions End of explanation """ # Check on TMPDIR... tempfile.gettempdir() # Set tmpdir variable to $TMPDIR (for future reference)... tmpdir = os.environ['TMPDIR'] """ Explanation: 2.3. Check on Location of TMPDIR... End of explanation """ # Create main Zeropoints directory, if it does not already exist... if not os.path.exists(zeropoints_dir): os.makedirs(zeropoints_dir) """ Explanation: 2.4. Create Main Zeropoints Directory (if it does not already exist)... End of explanation """ def DECam_tie_to_fgcm_stds(inputFile, outputFile, band, magType, fluxObsColName, fluxerrObsColName, aggFieldColName, verbose): import numpy as np import os import sys import datetime import pandas as pd from astropy.table import Table, vstack validBandsList = ['g', 'r', 'i', 'z', 'Y'] if band not in validBandsList: print """Filter band %s is not currently handled... Exiting now!""" % (band) return 1 reqColList = ['MAG_STD_G','MAGERR_STD_G', 'MAG_STD_R','MAGERR_STD_R', 'MAG_STD_I','MAGERR_STD_I', 'MAG_STD_Z','MAGERR_STD_Z', 'MAG_STD_Y','MAGERR_STD_Y', fluxObsColName,fluxerrObsColName, aggFieldColName] # Does the input file exist? if os.path.isfile(inputFile)==False: print """DECam_tie_to_fgcm_stds input file %s does not exist. Exiting...""" % (inputFile) return 1 # Read inputFile into a pandas DataFrame... print datetime.datetime.now() print """Reading in %s as a pandas DataFrame...""" % (inputFile) t = Table.read(inputFile) dataFrame = t.to_pandas() print datetime.datetime.now() print reqColFlag = 0 colList = dataFrame.columns.tolist() for reqCol in reqColList: if reqCol not in colList: print """ERROR: Required column %s is not in the header""" % (reqCol) reqColFlag = 1 if reqColFlag == 1: print """Missing required columns in header of %s... Exiting now!""" (inputFile) return 1 # Identify column of the standard magnitude for the given band... magStdColName = """MAG_STD_%s""" % (band.upper()) magerrStdColName = """MAGERR_STD_%s""" % (band.upper()) # Add a 'MAG_OBS' column and a 'MAG_DIFF' column to the pandas DataFrame... dataFrame['MAG_OBS'] = -2.5*np.log10(dataFrame[fluxObsColName]) dataFrame['MAG_DIFF'] = dataFrame[magStdColName]-dataFrame['MAG_OBS'] ############################################### # Aggregate by aggFieldColName ############################################### # Make a copy of original dataFrame... df = dataFrame.copy() # Create an initial mask... mask1 = ( (df[magStdColName] >= 0.) & (df[magStdColName] <= 25.) ) mask1 = ( mask1 & (df[fluxObsColName] > 10.) & (df['FLAGS'] < 2) & (np.abs(df['SPREAD_MODEL']) < 0.01)) if magerrStdColName != 'None': mask1 = ( mask1 & (df[magerrStdColName] < 0.1) ) magDiffGlobalMedian = df[mask1]['MAG_DIFF'].median() magDiffMin = magDiffGlobalMedian - 5.0 magDiffMax = magDiffGlobalMedian + 5.0 mask2 = ( (df['MAG_DIFF'] > magDiffMin) & (df['MAG_DIFF'] < magDiffMax) ) mask = mask1 & mask2 # Iterate over the copy of dataFrame 3 times, removing outliers... # We are using "Method 2/Group by item" from # http://nbviewer.jupyter.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/07%20-%20Lesson.ipynb print "Sigma-clipping..." niter = 0 for i in range(3): niter = i + 1 print """ iter%d...""" % ( niter ) # make a copy of original df, and then delete the old one... newdf = df[mask].copy() del df # group by aggFieldColName... grpnewdf = newdf.groupby([aggFieldColName]) # add/update new columns to newdf print datetime.datetime.now() newdf['Outlier'] = grpnewdf['MAG_DIFF'].transform( lambda x: abs(x-x.mean()) > 3.00*x.std() ) #newdf['Outlier'] = grpnewdf['MAG_DIFF'].transform( lambda x: abs(x-x.mean()) > 2.00*x.std() ) print datetime.datetime.now() del grpnewdf print datetime.datetime.now() #print newdf nrows = newdf['MAG_DIFF'].size print """ Number of rows remaining: %d""" % ( nrows ) df = newdf mask = ( df['Outlier'] == False ) # Perform pandas grouping/aggregating functions on sigma-clipped Data Frame... print datetime.datetime.now() print 'Performing grouping/aggregating functions on sigma-clipped pandas DataFrame...' groupedDataFrame = df.groupby([aggFieldColName]) magZeroMedian = groupedDataFrame['MAG_DIFF'].median() magZeroMean = groupedDataFrame['MAG_DIFF'].mean() magZeroStd = groupedDataFrame['MAG_DIFF'].std() magZeroNum = groupedDataFrame['MAG_DIFF'].count() magZeroErr = magZeroStd/np.sqrt(magZeroNum-1) print datetime.datetime.now() print # Rename these pandas series... magZeroMedian.name = 'MAG_ZERO_MEDIAN' magZeroMean.name = 'MAG_ZERO_MEAN' magZeroStd.name = 'MAG_ZERO_STD' magZeroNum.name = 'MAG_ZERO_NUM' magZeroErr.name = 'MAG_ZERO_MEAN_ERR' # Also, calculate group medians for all columns in df that have a numerical data type... numericalColList = df.select_dtypes(include=[np.number]).columns.tolist() groupedDataMedian = {} for numericalCol in numericalColList: groupedDataMedian[numericalCol] = groupedDataFrame[numericalCol].median() groupedDataMedian[numericalCol].name = """%s_MEDIAN""" % (numericalCol) # Create new data frame containing all the relevant aggregate quantities #newDataFrame = pd.concat( [magZeroMedian, magZeroMean, magZeroStd, \ # magZeroErr, magZeroNum], \ # join='outer', axis=1 ) seriesList = [] for numericalCol in numericalColList: seriesList.append(groupedDataMedian[numericalCol]) seriesList.extend([magZeroMedian, magZeroMean, magZeroStd, \ magZeroErr, magZeroNum]) #print seriesList newDataFrame = pd.concat( seriesList, join='outer', axis=1 ) #newDataFrame.index.rename('FILENAME', inplace=True) # Saving catname-based results to output files... print datetime.datetime.now() print """Writing %s output file (using pandas to_csv method)...""" % (outputFile) newDataFrame.to_csv(outputFile, float_format='%.4f') print datetime.datetime.now() print return 0 """ Explanation: 3. Useful Modules End of explanation """ %%time if do_calc_fgcm_psf_zps: fluxObsColName = 'FLUX_PSF' fluxerrObsColName = 'FLUXERR_PSF' aggFieldColName = 'FILENAME' magType = 'psf' subdir = """DES_%s""" % (tag_des) tmpdir = os.environ['TMPDIR'] for regionName in region_name_list: print print """# # # # # # # # # # # # # # #""" print """Working on region %s""" % (regionName) print """# # # # # # # # # # # # # # #""" print for band in bandList: input_file_template = """cat_%s.%s.?.%s.fgcm_%s.fits""" % (subdir, regionName, band, magType) input_file_template = os.path.join(rawdata_dir, 'ExpCatFITS', subdir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) for inputFile in input_file_list: print inputFile if os.path.exists(inputFile): #outputFile = os.path.splitext(inputFile)[0] + '.zps.csv' #print outputFile outputFile = os.path.splitext(os.path.basename(inputFile))[0]+'.csv' outputFile = 'zps_' + outputFile[4:] outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile status = DECam_tie_to_fgcm_stds(inputFile, outputFile, band, magType, fluxObsColName, fluxerrObsColName, aggFieldColName, verbose) if status > 0: print 'ERROR: %s FAILED! Continuing...' else: print """%s does not exist... skipping...""" % (inputFile) print """ Explanation: 4. Zeropoints by tying to FGCM PSF Standard Stars We will first work with the DES data, and then we will repeat for the DECADE data. DES: Calculate zeropoints region by region... End of explanation """ %%time if do_calc_fgcm_psf_zps: magType = 'psf' subdir = """DES_%s""" % (tag_des) tmpdir = os.environ['TMPDIR'] for band in bandList: print print """# # # # # # # # # # # # # # #""" print """Working on band %s""" % (band) print """# # # # # # # # # # # # # # #""" print outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) input_file_template = """zps_%s.*.?.%s.fgcm_%s.csv""" % (subdir, band, magType) input_file_template = os.path.join(zeropoints_dir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) continue df_comb = pd.concat(pd.read_csv(inputFile) for inputFile in input_file_list) outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile df_comb.to_csv(outputFile, index=False) del df_comb """ Explanation: Combine region-by-region results into a single file... End of explanation """ %%time if do_calc_fgcm_psf_zps: fluxObsColName = 'FLUX_PSF' fluxerrObsColName = 'FLUXERR_PSF' aggFieldColName = 'FILENAME' magType = 'psf' subdir = """%s""" % (tag_decade) tmpdir = os.environ['TMPDIR'] for regionName in region_name_list: print print """# # # # # # # # # # # # # # #""" print """Working on region %s""" % (regionName) print """# # # # # # # # # # # # # # #""" print for band in bandList: input_file_template = """cat_%s.%s.?.%s.fgcm_%s.fits""" % (subdir, regionName, band, magType) input_file_template = os.path.join(rawdata_dir, 'ExpCatFITS', subdir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) for inputFile in input_file_list: print inputFile if os.path.exists(inputFile): #outputFile = os.path.splitext(inputFile)[0] + '.zps.csv' #print outputFile outputFile = os.path.splitext(os.path.basename(inputFile))[0]+'.csv' outputFile = 'zps_' + outputFile[4:] outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile status = DECam_tie_to_fgcm_stds(inputFile, outputFile, band, magType, fluxObsColName, fluxerrObsColName, aggFieldColName, verbose) if status > 0: print """ERROR: %s FAILED! Continuing...""" % (cmd) else: print """%s does not exist... skipping...""" % (inputFile) print """ Explanation: DECADE: Calculate zeropoints region by region... End of explanation """ %%time if do_calc_fgcm_psf_zps: magType = 'psf' subdir = """%s""" % (tag_decade) tmpdir = os.environ['TMPDIR'] for band in bandList: print print """# # # # # # # # # # # # # # #""" print """Working on band %s""" % (band) print """# # # # # # # # # # # # # # #""" print outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) input_file_template = """zps_%s.*.?.%s.fgcm_%s.csv""" % (subdir, band, magType) input_file_template = os.path.join(zeropoints_dir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) continue df_comb = pd.concat(pd.read_csv(inputFile) for inputFile in input_file_list) outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile df_comb.to_csv(outputFile, index=False) del df_comb """ Explanation: Combine region-by-region results into a single file... End of explanation """ %%time if do_calc_fgcm_aper8_zps: fluxObsColName = 'FLUX_APER_08' fluxerrObsColName = 'FLUXERR_APER_08' aggFieldColName = 'FILENAME' magType = 'aper8' subdir = """DES_%s""" % (tag_des) tmpdir = os.environ['TMPDIR'] for regionName in region_name_list: print print """# # # # # # # # # # # # # # #""" print """Working on region %s""" % (regionName) print """# # # # # # # # # # # # # # #""" print for band in bandList: input_file_template = """cat_%s.%s.?.%s.fgcm_%s.fits""" % (subdir, regionName, band, magType) input_file_template = os.path.join(rawdata_dir, 'ExpCatFITS', subdir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) for inputFile in input_file_list: print inputFile if os.path.exists(inputFile): #outputFile = os.path.splitext(inputFile)[0] + '.zps.csv' #print outputFile outputFile = os.path.splitext(os.path.basename(inputFile))[0]+'.csv' outputFile = 'zps_' + outputFile[4:] outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile status = DECam_tie_to_fgcm_stds(inputFile, outputFile, band, magType, fluxObsColName, fluxerrObsColName, aggFieldColName, verbose) if status > 0: print 'ERROR: %s FAILED! Continuing...' else: print """%s does not exist... skipping...""" % (inputFile) print """ Explanation: 5. Zeropoints by tying to FGCM Aper8 Standard Stars We will first work with the DES data, and then we will repeat for the DECADE data. DES: Calculate zeropoints region by region... End of explanation """ %%time if do_calc_fgcm_aper8_zps: magType = 'aper8' subdir = """DES_%s""" % (tag_des) tmpdir = os.environ['TMPDIR'] for band in bandList: print print """# # # # # # # # # # # # # # #""" print """Working on band %s""" % (band) print """# # # # # # # # # # # # # # #""" print outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) input_file_template = """zps_%s.*.?.%s.fgcm_%s.csv""" % (subdir, band, magType) input_file_template = os.path.join(zeropoints_dir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) continue df_comb = pd.concat(pd.read_csv(inputFile) for inputFile in input_file_list) outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile df_comb.to_csv(outputFile, index=False) del df_comb """ Explanation: Combine region-by-region results into a single file... End of explanation """ %%time if do_calc_fgcm_aper8_zps: fluxObsColName = 'FLUX_APER_08' fluxerrObsColName = 'FLUXERR_APER_08' aggFieldColName = 'FILENAME' magType = 'aper8' subdir = """%s""" % (tag_decade) tmpdir = os.environ['TMPDIR'] for regionName in region_name_list: print print """# # # # # # # # # # # # # # #""" print """Working on region %s""" % (regionName) print """# # # # # # # # # # # # # # #""" print for band in bandList: input_file_template = """cat_%s.%s.?.%s.fgcm_%s.fits""" % (subdir, regionName, band, magType) input_file_template = os.path.join(rawdata_dir, 'ExpCatFITS', subdir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) for inputFile in input_file_list: print inputFile if os.path.exists(inputFile): #outputFile = os.path.splitext(inputFile)[0] + '.zps.csv' #print outputFile outputFile = os.path.splitext(os.path.basename(inputFile))[0]+'.csv' outputFile = 'zps_' + outputFile[4:] outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile status = DECam_tie_to_fgcm_stds(inputFile, outputFile, band, magType, fluxObsColName, fluxerrObsColName, aggFieldColName, verbose) if status > 0: print """ERROR: %s FAILED! Continuing...""" % (cmd) else: print """%s does not exist... skipping...""" % (inputFile) print """ Explanation: DECADE: Calculate zeropoints region by region... End of explanation """ %%time if do_calc_fgcm_aper8_zps: magType = 'aper8' subdir = """%s""" % (tag_decade) tmpdir = os.environ['TMPDIR'] for band in bandList: print print """# # # # # # # # # # # # # # #""" print """Working on band %s""" % (band) print """# # # # # # # # # # # # # # #""" print outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) input_file_template = """zps_%s.*.?.%s.fgcm_%s.csv""" % (subdir, band, magType) input_file_template = os.path.join(zeropoints_dir, input_file_template) input_file_list = glob.glob(input_file_template) input_file_list = np.sort(input_file_list) if np.size(input_file_list) == 0: print "No files matching template %s" % (input_file_template) continue df_comb = pd.concat(pd.read_csv(inputFile) for inputFile in input_file_list) outputFile = """zps_%s.%s.fgcm_%s.csv""" % (subdir, band, magType) outputFile = outputFile = os.path.join(zeropoints_dir, outputFile) print outputFile df_comb.to_csv(outputFile, index=False) del df_comb """ Explanation: Combine region-by-region results into a single file... End of explanation """
SheffieldML/notebook
compbio/tSNE-over-interpretation.ipynb
bsd-3-clause
n = 200 m = 40 np.random.seed(1) x = np.random.uniform(-1, 1, n) c = np.digitize(x, np.linspace(-1,1,12))-1 cols = np.asarray(sns.color_palette('spectral_r',12))[c] """ Explanation: t-SNE structure in linear data by Max Zwiessele Recently a tweet https://twitter.com/mikelove/status/738021869341839360 shook data scientists awake, showing that one of the most used dimensionality reduction techniques stochastic neighberhood embedding is 'making up' structure in a linear embedding. Their plots show incredible detailed structure in a high dimensional dataset containing only a one dimensional linear embedded input. Here we explore the same problem using python's implementations of tSNE and show that GPLVM and Bayesian GPLVM do not suffer from this problem. End of explanation """ plt.scatter(x, np.zeros(n), c=cols, cmap='spectral_r', lw=0) """ Explanation: Linear embedding The embedded linear structure. It is just a point cloud on a line betwenn -1 and 1. End of explanation """ r = np.random.normal(0,1,[m,1]) M = np.eye(m)-2*(r.dot(r.T)/r.T.dot(r)) X = np.c_[x, np.zeros((n,m-1))].dot(M) plt.scatter(*X[:,1:3].T, c=x, cmap='spectral', lw=0) """ Explanation: Embed into higher dimensions We embedd this linear point cloud in a 40 dimensional space using a 40 dimensional set of 40 orthogonal bases. End of explanation """ from sklearn.decomposition import PCA Xpca = PCA(2).fit_transform(X) plt.scatter(*Xpca.T, c=x, cmap='spectral', lw=0) """ Explanation: PCA The algorithm PCA finds the linear point cloud and is able to reproduce the original. End of explanation """ fig, axes = plt.subplots(2,3,tight_layout=True,figsize=(15,10)) axit = axes.flat for lr in range(6): ax = next(axit) Xtsne = tsne.bh_sne(X.copy()) ax.scatter(*Xtsne.T, c=cols, cmap='spectral', lw=0) ax.set_title('restart: ${}$'.format(lr)) """ Explanation: Barnes_hut implementation This implementation of tSNE is taken from https://github.com/danielfrg/tsne. Note the 'artificial' structure in the embeddings. It is not as detailed ('bad') as in the original R implementation of tSNE, but still it introduces some structure and non-linearities. For other implementations in R have a look at https://gist.github.com/mikelove/74bbf5c41010ae1dc94281cface90d32, where others looked at different implementations of tSNE in R. End of explanation """ from sklearn.manifold import TSNE fig, axes = plt.subplots(2,3,tight_layout=True,figsize=(15,10)) axit = axes.flat for perplexity in [30,60]: for lr in [200, 500, 1000]: ax = next(axit) Xtsne = TSNE(perplexity=perplexity, learning_rate=lr, init='pca').fit_transform(X.copy()) ax.scatter(*Xtsne.T, c=cols, cmap='spectral', lw=0) ax.set_title('perp=${}$, learn-rate=${}$'.format(perplexity, lr)) """ Explanation: scikit-learn emplementation Careful with the scikit-learn implementation, the parameters and convergence seems to be unstable. A too high learning rate can lead to a completely random picture. Note that a learning rate of 1000. is the standard in the library. It seems that the scikit-learn implementation suffers from high dependence on the parameters chosen for learning. Beware of this, when using this implementation of tSNE. End of explanation """ from mpl_toolkits.axes_grid.inset_locator import inset_axes fig, axes = plt.subplots(2,3,tight_layout=True,figsize=(15,10)) axit = axes.flat for lr in range(6): ax = next(axit) m = GPy.models.GPLVM(X.copy(), 2) m.optimize(messages=1, gtol=0, clear_after_finish=True) msi = m.get_most_significant_input_dimensions()[:2] is_ = m.kern.input_sensitivity().copy() is_ /= is_.max() XBGPLVM = m.X[:,msi] * is_[np.array(msi)] #m.kern.plot_ARD(ax=ax) ax.scatter(*XBGPLVM.T, c=cols, cmap='spectral', lw=0) ax.set_title('restart: ${}$'.format(lr)) ax.set_xlabel('dimension ${}$'.format(msi[0])) ax.set_ylabel('dimension ${}$'.format(msi[1])) a = inset_axes(ax, width="30%", # width = 30% of parent_bbox height='20%', # height : 1 inch loc=1) sns.barplot(np.array(msi), is_[np.array(msi)], label='input-sens', ax=a) a.set_title('sensitivity') a.set_xlabel('dimension') """ Explanation: GPLVM We show the performance of GPLVM on the dataset provided. The top right bar plot shows the sensitivity to the dimensions of the embedding. When the sensitivity is high, the dimension is used. End of explanation """ from mpl_toolkits.axes_grid.inset_locator import inset_axes fig, axes = plt.subplots(2,3,tight_layout=True,figsize=(15,10)) axit = axes.flat for lr in range(6): ax = next(axit) m = GPy.models.BayesianGPLVM(X, 5, num_inducing=25) m.optimize(messages=1, gtol=0, clear_after_finish=True) msi = m.get_most_significant_input_dimensions()[:2] is_ = m.kern.input_sensitivity() is_ /= is_.max() XBGPLVM = m.X.mean[:,msi] * is_[np.array(msi)] #m.kern.plot_ARD(ax=ax) ax.scatter(*XBGPLVM.T, c=cols, cmap='spectral', lw=0) ax.set_title('restart: ${}$'.format(lr)) ax.set_xlabel('dimension ${}$'.format(msi[0])) ax.set_ylabel('dimension ${}$'.format(msi[1])) a = inset_axes(ax, width="30%", # width = 30% of parent_bbox height='20%', # height : 1 inch loc=1) sns.barplot(range(m.input_dim), is_, label='input-sens') a.set_title('sensitivity') """ Explanation: Bayesian GPLVM Last, we want to show the ability of Bayesian GPLVM to not only find the linear imbedding, but also determine the number of necessary dimensions to embedd the data in. We start at a dimensionality of 5 and show that Bayesian GPLVM is capable of identifying one dimension as the significant one and switches off the other ones. See for that the significance of the dimensions in the top right of each subplot. End of explanation """
Nathx/think_stats
resolved/chap02ex.ipynb
gpl-3.0
%matplotlib inline from operator import itemgetter import chap01soln """ Explanation: Exercise from Think Stats, 2nd Edition (thinkstats2.com)<br> Allen Downey Read the female respondent file and display the variables names. End of explanation """ import thinkstats2 hist = thinkstats2.Hist(resp.totincr) resp = chap01soln.ReadFemResp() resp.columns """ Explanation: Make a histogram of <tt>totincr</tt> the total income for the respondent's family. To interpret the codes see the codebook. End of explanation """ import thinkplot thinkplot.Hist(hist, label='totincr') thinkplot.Show() """ Explanation: Display the histogram. End of explanation """ hist2 = thinkstats2.Hist(resp.age_r) thinkplot.Hist(hist2, label='age_r') thinkplot.Show() """ Explanation: Make a histogram of <tt>age_r</tt>, the respondent's age at the time of interview. End of explanation """ hist3 = thinkstats2.Hist(resp.numfmhh) thinkplot.Hist(hist3, label='numfmhh') thinkplot.Show() """ Explanation: Make a histogram of <tt>numfmhh</tt>, the number of people in the respondent's household. End of explanation """ hist4 = thinkstats2.Hist(resp.parity) thinkplot.Hist(hist4, label='parity') thinkplot.Show() """ Explanation: Make a histogram of <tt>parity</tt>, the number children the respondent has borne. How would you describe this distribution? End of explanation """ hist4.Largest() """ Explanation: Use Hist.Largest to find the largest values of <tt>parity</tt>. End of explanation """ hist5 = thinkstats2.Hist(resp.parity[resp.totincr == 14]) thinkplot.Hist(hist5, label='parity_hi') thinkplot.Show() """ Explanation: Use <tt>totincr</tt> to select the respondents with the highest income. Compute the distribution of <tt>parity</tt> for just the high income respondents. End of explanation """ hist5.Largest() """ Explanation: Find the largest parities for high income respondents. End of explanation """ hi_par = resp.parity[resp.totincr == 14] par = resp.parity hi_par.mean(), par.mean() """ Explanation: Compare the mean <tt>parity</tt> for high income respondents and others. End of explanation """ hi_par.std(), par.std() def Mode(h): max = 0 for i in h: if h.Freq(i) > h.Freq(max): max = i return max def AllModes(h): hist = h.Copy() result = [] while len(hist) > 0: max = Mode(hist) result.append((max, hist.Freq(max))) hist.Remove(max) return result def AllModes2(hist): """Returns value-freq pairs in decreasing order of frequency. hist: Hist object returns: iterator of value-freq pairs """ return sorted(hist.Items(), key=itemgetter(1), reverse=True) %timeit AllModes(hist2) %timeit AllModes2(hist2) %timeit? """ Explanation: Investigate any other variables that look interesting. End of explanation """
tensorflow/docs-l10n
site/ja/probability/examples/Bayesian_Switchpoint_Analysis.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ import tensorflow.compat.v2 as tf tf.enable_v2_behavior() import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (15,8) %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd """ Explanation: ベイジアンスイッチポイント解析 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/probability/examples/Bayesian_Switchpoint_Analysis"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/probability/examples/Bayesian_Switchpoint_Analysis.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/probability/examples/Bayesian_Switchpoint_Analysis.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png"> GitHub でソースを表示</a></td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/probability/examples/Bayesian_Switchpoint_Analysis.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a></td> </table> このノートブックは、pymc3 ドキュメントに含まれるベイズの「Change point analysis」の例を再実装し、拡張したものです。 前提条件 End of explanation """ disaster_data = np.array([ 4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6, 3, 3, 5, 4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2, 5, 2, 2, 3, 4, 2, 1, 3, 2, 2, 1, 1, 1, 1, 3, 0, 0, 1, 0, 1, 1, 0, 0, 3, 1, 0, 3, 2, 2, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 1, 0, 2, 3, 3, 1, 1, 2, 1, 1, 1, 1, 2, 4, 2, 0, 0, 1, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]) years = np.arange(1851, 1962) plt.plot(years, disaster_data, 'o', markersize=8); plt.ylabel('Disaster count') plt.xlabel('Year') plt.title('Mining disaster data set') plt.show() """ Explanation: データセット データセットはこちらを使用します。この例の別のバージョンが出回っていますが、データが「欠落」しているため、欠落している値によって問題が起きてしまいます。(そうでなくとも、尤度関数が未定義となるため、モデルは初期パラメータから抜けることができません。) End of explanation """ def disaster_count_model(disaster_rate_fn): disaster_count = tfd.JointDistributionNamed(dict( e=tfd.Exponential(rate=1.), l=tfd.Exponential(rate=1.), s=tfd.Uniform(0., high=len(years)), d_t=lambda s, l, e: tfd.Independent( tfd.Poisson(rate=disaster_rate_fn(np.arange(len(years)), s, l, e)), reinterpreted_batch_ndims=1) )) return disaster_count def disaster_rate_switch(ys, s, l, e): return tf.where(ys < s, e, l) def disaster_rate_sigmoid(ys, s, l, e): return e + tf.sigmoid(ys - s) * (l - e) model_switch = disaster_count_model(disaster_rate_switch) model_sigmoid = disaster_count_model(disaster_rate_sigmoid) """ Explanation: 確率的モデル このモデルは、「スイッチポイント」(安全規制が変更される年など)と、一定した(ただし潜在的に異なる)率によるそのスイッチポイントの前と後のポワソン分布の災害発生率を使用します。 実際の災害発生数は固定(観測済み)です。このモデルのすべてのモデルはスイッチポイントと災害の「早期」と「後期」の発生率の両方を指定する必要があります。 pymc3 ドキュメントの例に含まれる元のモデル: $$ \begin{align} (D_t|s,e,l)&amp;\sim \text{Poisson}(r_t), \ &amp; ,\quad\text{with}; r_t = \begin{cases}e &amp; \text{if}; t &lt; s\l &amp;\text{if}; t \ge s\end{cases} \ s&amp;\sim\text{Discrete Uniform}(t_l,,t_h) \ e&amp;\sim\text{Exponential}(r_e)\ l&amp;\sim\text{Exponential}(r_l) \end{align} $$ しかし、平均災害発生率 $r_t$ には、スイッチポイント $s$ での不連続点があります。そのため、これは微分不可能です。したがって、ハミルトニアンモンテカルロ(HMC)アルゴリズムに勾配信号は送られません。ただし、$s$ より前は連続であるため、HMC はランダムウォーク(酔歩)にフォールバックします。この例の確立室用の高い領域を見つけるには十分です。 2 つ目のモデルとして、トランジションを微分可能にするためにシグモイド関数の「switch」を e と l の間に使用して元のモデルを変更し、スイッチポイント $s$ の連続一様分布を使用します。(平均発生率の「スイッチ」の期間は何年にもなる可能性があるため、このモデルはより現実的ということもできます。)したがって、新しいモデルは次のようになります。 $$ \begin{align} (D_t|s,e,l)&amp;\sim\text{Poisson}(r_t), \ &amp; ,\quad \text{with}; r_t = e + \frac{1}{1+\exp(s-t)}(l-e) \ s&amp;\sim\text{Uniform}(t_l,,t_h) \ e&amp;\sim\text{Exponential}(r_e)\ l&amp;\sim\text{Exponential}(r_l) \end{align} $$ その他の情報がない状態で、$r_e = r_l = 1$ を事前確率のパラメータとして使用します。両方のモデルを実行して、推論の結果を比較してみましょう。 End of explanation """ def target_log_prob_fn(model, s, e, l): return model.log_prob(s=s, e=e, l=l, d_t=disaster_data) models = [model_switch, model_sigmoid] print([target_log_prob_fn(m, 40., 3., .9).numpy() for m in models]) # Somewhat likely result print([target_log_prob_fn(m, 60., 1., 5.).numpy() for m in models]) # Rather unlikely result print([target_log_prob_fn(m, -10., 1., 1.).numpy() for m in models]) # Impossible result """ Explanation: 上記のコードは、JointDistributionSequential 分布を介してモデルを定義しています。disaster_rate 関数は、[0, ..., len(years)-1] の配列とともに呼び出され、len(years) ランダム変数のベクトルを生成します。(シグモイドトランジションを法として)switchpoint より前の年は early_disaster_rate で、後の年は late_disaster_rate です。 健全性チェックは次のとおりになります。ターゲットの対数確率関数は健全です。 End of explanation """ num_results = 10000 num_burnin_steps = 3000 @tf.function(autograph=False, jit_compile=True) def make_chain(target_log_prob_fn): kernel = tfp.mcmc.TransformedTransitionKernel( inner_kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_log_prob_fn, step_size=0.05, num_leapfrog_steps=3), bijector=[ # The switchpoint is constrained between zero and len(years). # Hence we supply a bijector that maps the real numbers (in a # differentiable way) to the interval (0;len(yers)) tfb.Sigmoid(low=0., high=tf.cast(len(years), dtype=tf.float32)), # Early and late disaster rate: The exponential distribution is # defined on the positive real numbers tfb.Softplus(), tfb.Softplus(), ]) kernel = tfp.mcmc.SimpleStepSizeAdaptation( inner_kernel=kernel, num_adaptation_steps=int(0.8*num_burnin_steps)) states = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=[ # The three latent variables tf.ones([], name='init_switchpoint'), tf.ones([], name='init_early_disaster_rate'), tf.ones([], name='init_late_disaster_rate'), ], trace_fn=None, kernel=kernel) return states switch_samples = [s.numpy() for s in make_chain( lambda *args: target_log_prob_fn(model_switch, *args))] sigmoid_samples = [s.numpy() for s in make_chain( lambda *args: target_log_prob_fn(model_sigmoid, *args))] switchpoint, early_disaster_rate, late_disaster_rate = zip( switch_samples, sigmoid_samples) """ Explanation: HMC でベイジアン推論を行う 結果数と必要なバーンインステップを定義します。このコードはほぼ、tfp.mcmc.HamiltonianMonteCarlo のドキュメントを模倣したものです。適応ステップサイズを使用しています(そうでなければ、結果は選択されたステップサイズ値の影響を大きく受けるためです)。チェーンの初期状態として 1 の値を使用します。 ただし、これは完全なストーリーではありません。上記のモデル定義に戻ると、一部の確率分布は実数線全体においてうまく定義されていません。したがって、HMC カーネルを前方 Bijector を指定する TransformedTransitionKernel でラップして実数を確率分布が定義されている領域に変換することで、HMC が調べる空間を制約します(以下のコードのコメントをご覧ください)。 End of explanation """ def _desc(v): return '(median: {}; 95%ile CI: $[{}, {}]$)'.format( *np.round(np.percentile(v, [50, 2.5, 97.5]), 2)) for t, v in [ ('Early disaster rate ($e$) posterior samples', early_disaster_rate), ('Late disaster rate ($l$) posterior samples', late_disaster_rate), ('Switch point ($s$) posterior samples', years[0] + switchpoint), ]: fig, ax = plt.subplots(nrows=1, ncols=2, sharex=True) for (m, i) in (('Switch', 0), ('Sigmoid', 1)): a = ax[i] a.hist(v[i], bins=50) a.axvline(x=np.percentile(v[i], 50), color='k') a.axvline(x=np.percentile(v[i], 2.5), color='k', ls='dashed', alpha=.5) a.axvline(x=np.percentile(v[i], 97.5), color='k', ls='dashed', alpha=.5) a.set_title(m + ' model ' + _desc(v[i])) fig.suptitle(t) plt.show() """ Explanation: 両方のモデルを並行して実行します。 結果を視覚化する 結果は、早期と後期の災害発生率を表す事後確率分布のサンプルとスイッチポイントを含むヒストグラムとして視覚化します。ヒストグラムには、サンプルの中央値を表す実線と、95 パーセンタイルの信頼区間の境界を表す破線をオーバーレイします。 End of explanation """
TeamHG-Memex/eli5
notebooks/TextExplainer.ipynb
mit
from sklearn.datasets import fetch_20newsgroups categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med'] twenty_train = fetch_20newsgroups( subset='train', categories=categories, shuffle=True, random_state=42, remove=('headers', 'footers'), ) twenty_test = fetch_20newsgroups( subset='test', categories=categories, shuffle=True, random_state=42, remove=('headers', 'footers'), ) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import SVC from sklearn.decomposition import TruncatedSVD from sklearn.pipeline import Pipeline, make_pipeline vec = TfidfVectorizer(min_df=3, stop_words='english', ngram_range=(1, 2)) svd = TruncatedSVD(n_components=100, n_iter=7, random_state=42) lsa = make_pipeline(vec, svd) clf = SVC(C=150, gamma=2e-2, probability=True) pipe = make_pipeline(lsa, clf) pipe.fit(twenty_train.data, twenty_train.target) pipe.score(twenty_test.data, twenty_test.target) """ Explanation: TextExplainer: debugging black-box text classifiers While eli5 supports many classifiers and preprocessing methods, it can't support them all. If a library is not supported by eli5 directly, or the text processing pipeline is too complex for eli5, eli5 can still help - it provides an implementation of LIME (Ribeiro et al., 2016) algorithm which allows to explain predictions of arbitrary classifiers, including text classifiers. eli5.lime can also help when it is hard to get exact mapping between model coefficients and text features, e.g. if there is dimension reduction involved. Example problem: LSA+SVM for 20 Newsgroups dataset Let's load "20 Newsgroups" dataset and create a text processing pipeline which is hard to debug using conventional methods: SVM with RBF kernel trained on LSA features. End of explanation """ def print_prediction(doc): y_pred = pipe.predict_proba([doc])[0] for target, prob in zip(twenty_train.target_names, y_pred): print("{:.3f} {}".format(prob, target)) doc = twenty_test.data[0] print_prediction(doc) """ Explanation: The dimension of the input documents is reduced to 100, and then a kernel SVM is used to classify the documents. This is what the pipeline returns for a document - it is pretty sure the first message in test data belongs to sci.med: End of explanation """ import eli5 from eli5.lime import TextExplainer te = TextExplainer(random_state=42) te.fit(doc, pipe.predict_proba) te.show_prediction(target_names=twenty_train.target_names) """ Explanation: TextExplainer Such pipelines are not supported by eli5 directly, but one can use eli5.lime.TextExplainer to debug the prediction - to check what was important in the document to make this decision. Create a TextExplainer instance, then pass the document to explain and a black-box classifier (a function which returns probabilities) to the TextExplainer.fit method, then check the explanation: End of explanation """ import re doc2 = re.sub(r'(recall|kidney|stones|medication|pain|tech)', '', doc, flags=re.I) print_prediction(doc2) """ Explanation: Why it works Explanation makes sense - we expect reasonable classifier to take highlighted words in account. But how can we be sure this is how the pipeline works, not just a nice-looking lie? A simple sanity check is to remove or change the highlighted words, to confirm that they change the outcome: End of explanation """ print(te.samples_[0]) """ Explanation: Predicted probabilities changed a lot indeed. And in fact, TextExplainer did something similar to get the explanation. TextExplainer generated a lot of texts similar to the document (by removing some of the words), and then trained a white-box classifier which predicts the output of the black-box classifier (not the true labels!). The explanation we saw is for this white-box classifier. This approach follows the LIME algorithm; for text data the algorithm is actually pretty straightforward: generate distorted versions of the text; predict probabilities for these distorted texts using the black-box classifier; train another classifier (one of those eli5 supports) which tries to predict output of a black-box classifier on these texts. The algorithm works because even though it could be hard or impossible to approximate a black-box classifier globally (for every possible text), approximating it in a small neighbourhood near a given text often works well, even with simple white-box classifiers. Generated samples (distorted texts) are available in samples_ attribute: End of explanation """ len(te.samples_) """ Explanation: By default TextExplainer generates 5000 distorted texts (use n_samples argument to change the amount): End of explanation """ te.vec_, te.clf_ """ Explanation: Trained white-box classifier and vectorizer are available as vec_ and clf_ attributes: End of explanation """ te.metrics_ """ Explanation: Should we trust the explanation? Ok, this sounds fine, but how can we be sure that this simple text classification pipeline approximated the black-box classifier well? One way to do that is to check the quality on a held-out dataset (which is also generated). TextExplainer does that by default and stores metrics in metrics_ attribute: End of explanation """ import numpy as np def predict_proba_len(docs): # nasty predict_proba - the result is based on document length, # and also on a presence of "medication" proba = [ [0, 0, 1.0, 0] if len(doc) % 2 or 'medication' in doc else [1.0, 0, 0, 0] for doc in docs ] return np.array(proba) te3 = TextExplainer().fit(doc, predict_proba_len) te3.show_prediction(target_names=twenty_train.target_names) """ Explanation: 'score' is an accuracy score weighted by cosine distance between generated sample and the original document (i.e. texts which are closer to the example are more important). Accuracy shows how good are 'top 1' predictions. 'mean_KL_divergence' is a mean Kullback–Leibler divergence for all target classes; it is also weighted by distance. KL divergence shows how well are probabilities approximated; 0.0 means a perfect match. In this example both accuracy and KL divergence are good; it means our white-box classifier usually assigns the same labels as the black-box classifier on the dataset we generated, and its predicted probabilities are close to those predicted by our LSA+SVM pipeline. So it is likely (though not guaranteed, we'll discuss it later) that the explanation is correct and can be trusted. When working with LIME (e.g. via TextExplainer) it is always a good idea to check these scores. If they are not good then you can tell that something is not right. Let's make it fail By default TextExplainer uses a very basic text processing pipeline: Logistic Regression trained on bag-of-words and bag-of-bigrams features (see te.clf_ and te.vec_ attributes). It limits a set of black-box classifiers it can explain: because the text is seen as "bag of words/ngrams", the default white-box pipeline can't distinguish e.g. between the same word in the beginning of the document and in the end of the document. Bigrams help to alleviate the problem in practice, but not completely. Black-box classifiers which use features like "text length" (not directly related to tokens) can be also hard to approximate using the default bag-of-words/ngrams model. This kind of failure is usually detectable though - scores (accuracy and KL divergence) will be low. Let's check it on a completely synthetic example - a black-box classifier which assigns a class based on oddity of document length and on a presence of 'medication' word. End of explanation """ te3.metrics_ """ Explanation: TextExplainer correctly figured out that 'medication' is important, but failed to account for "len(doc) % 2" condition, so the explanation is incomplete. We can detect this failure by looking at metrics - they are low: End of explanation """ from sklearn.pipeline import make_union from sklearn.feature_extraction.text import CountVectorizer from sklearn.base import TransformerMixin class DocLength(TransformerMixin): def fit(self, X, y=None): # some boilerplate return self def transform(self, X): return [ # note that we needed both positive and negative # feature - otherwise for linear model there won't # be a feature to show in a half of the cases [len(doc) % 2, not len(doc) % 2] for doc in X ] def get_feature_names(self): return ['is_odd', 'is_even'] vec = make_union(DocLength(), CountVectorizer(ngram_range=(1,2))) te4 = TextExplainer(vec=vec).fit(doc[:-1], predict_proba_len) print(te4.metrics_) te4.explain_prediction(target_names=twenty_train.target_names) """ Explanation: If (a big if...) we suspect that the fact document length is even or odd is important, it is possible to customize TextExplainer to check this hypothesis. To do that, we need to create a vectorizer which returns both "is odd" feature and bag-of-words features, and pass this vectorizer to TextExplainer. This vectorizer should follow scikit-learn API. The easiest way is to use FeatureUnion - just make sure all transformers joined by FeatureUnion have get_feature_names() methods. End of explanation """ from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier vec_char = HashingVectorizer(analyzer='char_wb', ngram_range=(4,5)) clf_char = SGDClassifier(loss='log') pipe_char = make_pipeline(vec_char, clf_char) pipe_char.fit(twenty_train.data, twenty_train.target) pipe_char.score(twenty_test.data, twenty_test.target) """ Explanation: Much better! It was a toy example, but the idea stands - if you think something could be important, add it to the mix as a feature for TextExplainer. Let's make it fail, again Another possible issue is the dataset generation method. Not only feature extraction should be powerful enough, but auto-generated texts also should be diverse enough. TextExplainer removes random words by default, so by default it can't e.g. provide a good explanation for a black-box classifier which works on character level. Let's try to use TextExplainer to explain a classifier which uses char ngrams as features: End of explanation """ eli5.show_prediction(clf_char, doc, vec=vec_char, targets=['sci.med'], target_names=twenty_train.target_names) """ Explanation: This pipeline is supported by eli5 directly, so in practice there is no need to use TextExplainer for it. We're using this pipeline as an example - it is possible check the "true" explanation first, without using TextExplainer, and then compare the results with TextExplainer results. End of explanation """ te = TextExplainer(random_state=42).fit(doc, pipe_char.predict_proba) print(te.metrics_) te.show_prediction(targets=['sci.med'], target_names=twenty_train.target_names) """ Explanation: TextExplainer produces a different result: End of explanation """ te = TextExplainer(char_based=True, random_state=42) te.fit(doc, pipe_char.predict_proba) print(te.metrics_) te.show_prediction(targets=['sci.med'], target_names=twenty_train.target_names) """ Explanation: Scores look OK but not great; the explanation kind of makes sense on a first sight, but we know that the classifier works in a different way. To explain such black-box classifiers we need to change both dataset generation method (change/remove individual characters, not only words) and feature extraction method (e.g. use char ngrams instead of words and word ngrams). TextExplainer has an option (char_based=True) to use char-based sampling and char-based classifier. If this makes a more powerful explanation engine why not always use it? End of explanation """ te = TextExplainer(char_based=True, n_samples=50000, random_state=42) te.fit(doc, pipe_char.predict_proba) print(te.metrics_) te.show_prediction(targets=['sci.med'], target_names=twenty_train.target_names) """ Explanation: Hm, the result look worse. TextExplainer detected correctly that only the first part of word "medication" is important, but the result is noisy overall, and scores are bad. Let's try it with more samples: End of explanation """ from eli5.lime.samplers import MaskingTextSampler sampler = MaskingTextSampler( # Regex to split text into tokens. # "." means any single character is a token, i.e. # we work on chars. token_pattern='.', # replace no more than 3 tokens max_replace=3, # by default all tokens are replaced; # replace only a token at a given position. bow=False, ) samples, similarity = sampler.sample_near(doc) print(samples[0]) te = TextExplainer(char_based=True, sampler=sampler, random_state=42) te.fit(doc, pipe_char.predict_proba) print(te.metrics_) te.show_prediction(targets=['sci.med'], target_names=twenty_train.target_names) """ Explanation: It is getting closer, but still not there yet. The problem is that it is much more resource intensive - you need a lot more samples to get non-noisy results. Here explaining a single example took more time than training the original pipeline. Generally speaking, to do an efficient explanation we should make some assumptions about black-box classifier, such as: it uses words as features and doesn't take word position in account; it uses words as features and takes word positions in account; it uses words ngrams as features; it uses char ngrams as features, positions don't matter (i.e. an ngram means the same everywhere); it uses arbitrary attention over the text characters, i.e. every part of text could be potentionally important for a classifier on its own; it is important to have a particular token at a particular position, e.g. "third token is X", and if we delete 2nd token then prediction changes not because 2nd token changed, but because 3rd token is shifted. Depending on assumptions we should choose both dataset generation method and a white-box classifier. There is a tradeoff between generality and speed. Simple bag-of-words assumptions allow for fast sample generation, and just a few hundreds of samples could be required to get an OK quality if the assumption is correct. But such generation methods / models will fail to explain a more complex classifier properly (they could still provide an explanation which is useful in practice though). On the other hand, allowing for each character to be important is a more powerful method, but it can require a lot of samples (maybe hundreds thousands) and a lot of CPU time to get non-noisy results. What's bad about this kind of failure (wrong assumption about the black-box pipeline) is that it could be impossible to detect the failure by looking at the scores. Scores could be high because generated dataset is not diverse enough, not because our approximation is good. The takeaway is that it is important to understand the "lenses" you're looking through when using LIME to explain a prediction. Customizing TextExplainer: sampling TextExplainer uses MaskingTextSampler or MaskingTextSamplers instances to generate texts to train on. MaskingTextSampler is the main text generation class; MaskingTextSamplers provides a way to combine multiple samplers in a single object with the same interface. A custom sampler instance can be passed to TextExplainer if we want to experiment with sampling. For example, let's try a sampler which replaces no more than 3 characters in the text (default is to replace a random number of characters): End of explanation """ from sklearn.tree import DecisionTreeClassifier te5 = TextExplainer(clf=DecisionTreeClassifier(max_depth=2), random_state=0) te5.fit(doc, pipe.predict_proba) print(te5.metrics_) te5.show_weights() """ Explanation: Note that accuracy score is perfect, but KL divergence is bad. It means this sampler was not very useful: most generated texts were "easy" in sense that most (or all?) of them should be still classified as sci.med, so it was easy to get a good accuracy. But because generated texts were not diverse enough classifier haven't learned anything useful; it's having a hard time predicting the probability output of the black-box pipeline on a held-out dataset. By default TextExplainer uses a mix of several sampling strategies which seems to work OK for token-based explanations. But a good sampling strategy which works for many real-world tasks could be a research topic on itself. If you've got some experience with it we'd love to hear from you - please share your findings in eli5 issue tracker ( https://github.com/TeamHG-Memex/eli5/issues )! Customizing TextExplainer: classifier In one of the previous examples we already changed the vectorizer TextExplainer uses (to take additional features in account). It is also possible to change the white-box classifier - for example, use a small decision tree: End of explanation """ print("both words removed::") print_prediction(re.sub(r"(kidney|pain)", "", doc, flags=re.I)) print("\nonly 'pain' removed:") print_prediction(re.sub(r"pain", "", doc, flags=re.I)) """ Explanation: How to read it: "kidney <= 0.5" means "word 'kidney' is not in the document" (we're explaining the orginal LDA+SVM pipeline again). So according to this tree if "kidney" is not in the document and "pain" is not in the document then the probability of a document belonging to sci.med drops to 0.65. If at least one of these words remain sci.med probability stays 0.9+. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/nims-kma/cmip6/models/sandbox-2/ocnbgchem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-2', 'ocnbgchem') """ Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracers. Properties: 65 (37 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:29 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks 4. Key Properties --&gt; Transport Scheme 5. Key Properties --&gt; Boundary Forcing 6. Key Properties --&gt; Gas Exchange 7. Key Properties --&gt; Carbon Chemistry 8. Tracers 9. Tracers --&gt; Ecosystem 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton 11. Tracers --&gt; Ecosystem --&gt; Zooplankton 12. Tracers --&gt; Disolved Organic Matter 13. Tracers --&gt; Particules 14. Tracers --&gt; Dic Alkalinity 1. Key Properties Ocean Biogeochemistry key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of ocean biogeochemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean biogeochemistry model code (PISCES 2.0,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Geochemical" # "NPZD" # "PFT" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Model Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of ocean biogeochemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Fixed" # "Variable" # "Mix of both" # TODO - please enter value(s) """ Explanation: 1.4. Elemental Stoichiometry Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe elemental stoichiometry (fixed, variable, mix of the two) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.5. Elemental Stoichiometry Details Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe which elements have fixed/variable stoichiometry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all prognostic tracer variables in the ocean biogeochemistry component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.diagnostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.7. Diagnostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all diagnotic tracer variables in the ocean biogeochemistry component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.damping') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.8. Damping Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any tracer damping used (such as artificial correction or relaxation to climatology,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport Time stepping method for passive tracers transport in ocean biogeochemistry 2.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for passive tracers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 2.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for passive tracers (if different from ocean) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks Time stepping framework for biology sources and sinks in ocean biogeochemistry 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for biology sources and sinks End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for biology sources and sinks (if different from ocean) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline" # "Online" # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Transport Scheme Transport scheme in ocean biogeochemistry 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of transport scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Use that of ocean model" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 4.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Transport scheme used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.use_different_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.3. Use Different Scheme Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Decribe transport scheme if different than that of ocean model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.atmospheric_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Atmospheric Chemistry model" # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Boundary Forcing Properties of biogeochemistry boundary forcing 5.1. Atmospheric Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how atmospheric deposition is modeled End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.river_input') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Land Surface model" # TODO - please enter value(s) """ Explanation: 5.2. River Input Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how river input is modeled End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_boundary_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.3. Sediments From Boundary Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from boundary condition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_explicit_model') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.4. Sediments From Explicit Model Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from explicit sediment model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6. Key Properties --&gt; Gas Exchange *Properties of gas exchange in ocean biogeochemistry * 6.1. CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CO2 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.2. CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe CO2 gas exchange End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.3. O2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is O2 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.4. O2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe O2 gas exchange End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.5. DMS Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is DMS gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.6. DMS Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify DMS gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.7. N2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.8. N2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.9. N2O Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2O gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.10. N2O Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2O gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.11. CFC11 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC11 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.12. CFC11 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC11 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.13. CFC12 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC12 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.14. CFC12 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC12 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.15. SF6 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is SF6 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.16. SF6 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify SF6 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.17. 13CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 13CO2 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.18. 13CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 13CO2 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.19. 14CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 14CO2 gas exchange modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.20. 14CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 14CO2 gas exchange scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.other_gases') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6.21. Other Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify any other gas exchange End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other protocol" # TODO - please enter value(s) """ Explanation: 7. Key Properties --&gt; Carbon Chemistry Properties of carbon chemistry biogeochemistry 7.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how carbon chemistry is modeled End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.pH_scale') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Sea water" # "Free" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 7.2. PH Scale Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, describe pH scale. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.constants_if_not_OMIP') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.3. Constants If Not OMIP Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, list carbon chemistry constants. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Tracers Ocean biogeochemistry tracers 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of tracers in ocean biogeochemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.sulfur_cycle_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 8.2. Sulfur Cycle Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sulfur cycle modeled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nutrients_present') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrogen (N)" # "Phosphorous (P)" # "Silicium (S)" # "Iron (Fe)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.3. Nutrients Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List nutrient species present in ocean biogeochemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_species_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrates (NO3)" # "Amonium (NH4)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.4. Nitrous Species If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous species. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_processes_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Dentrification" # "N fixation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.5. Nitrous Processes If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous processes. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_definition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Tracers --&gt; Ecosystem Ecosystem properties in ocean biogeochemistry 9.1. Upper Trophic Levels Definition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Definition of upper trophic level (e.g. based on size) ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.2. Upper Trophic Levels Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Define how upper trophic level are treated End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "PFT including size based (specify both below)" # "Size based only (specify below)" # "PFT only (specify below)" # TODO - please enter value(s) """ Explanation: 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton Phytoplankton properties in ocean biogeochemistry 10.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of phytoplankton End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.pft') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Diatoms" # "Nfixers" # "Calcifiers" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.2. Pft Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton functional types (PFT) (if applicable) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microphytoplankton" # "Nanophytoplankton" # "Picophytoplankton" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.3. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton size classes (if applicable) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "Size based (specify below)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11. Tracers --&gt; Ecosystem --&gt; Zooplankton Zooplankton properties in ocean biogeochemistry 11.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of zooplankton End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microzooplankton" # "Mesozooplankton" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Zooplankton size classes (if applicable) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.bacteria_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 12. Tracers --&gt; Disolved Organic Matter Disolved organic matter properties in ocean biogeochemistry 12.1. Bacteria Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there bacteria representation ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.lability') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Labile" # "Semi-labile" # "Refractory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.2. Lability Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe treatment of lability in dissolved organic matter End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Diagnostic" # "Diagnostic (Martin profile)" # "Diagnostic (Balast)" # "Prognostic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13. Tracers --&gt; Particules Particulate carbon properties in ocean biogeochemistry 13.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is particulate carbon represented in ocean biogeochemistry? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.types_if_prognostic') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "POC" # "PIC (calcite)" # "PIC (aragonite" # "BSi" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Types If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If prognostic, type(s) of particulate matter taken into account End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "No size spectrum used" # "Full size spectrum" # "Discrete size classes (specify which below)" # TODO - please enter value(s) """ Explanation: 13.3. Size If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, describe if a particule size spectrum is used to represent distribution of particules in water volume End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_discrete') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13.4. Size If Discrete Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic and discrete size, describe which size classes are used End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.sinking_speed_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Function of particule size" # "Function of particule type (balast)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.5. Sinking Speed If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, method for calculation of sinking speed of particules End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.carbon_isotopes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "C13" # "C14)" # TODO - please enter value(s) """ Explanation: 14. Tracers --&gt; Dic Alkalinity DIC and alkalinity properties in ocean biogeochemistry 14.1. Carbon Isotopes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which carbon isotopes are modelled (C13, C14)? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.abiotic_carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.2. Abiotic Carbon Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is abiotic carbon modelled ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.alkalinity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Prognostic" # "Diagnostic)" # TODO - please enter value(s) """ Explanation: 14.3. Alkalinity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is alkalinity modelled ? End of explanation """
peastman/deepchem
examples/tutorials/Multisequence_Alignments.ipynb
mit
!wget -c https://repo.anaconda.com/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh !chmod +x Miniconda3-4.5.4-Linux-x86_64.sh !bash ./Miniconda3-4.5.4-Linux-x86_64.sh -b -f -p /usr/local """ Explanation: Multisequence Alignment (MSA) Proteins are made up of sequences of amino acids chained together. Their amino acid sequence determines their structure and function. Finding proteins with similar sequences, or homologous proteins, is very useful in identifying the structures and functions of newly discovered proteins as well as identifying their ancestry. Below is an example of what a protein amino acid multisequence alignment may look like, taken from [2]. Colab This tutorial and the rest in this sequence can be done in Google colab. If you'd like to open this notebook in colab, you can use the following link. HH-suite This tutorial will show you the basics of how to use hh-suite. hh-suite is an open source package for searching protein sequence alignments for homologous proteins. It is the current state of the art for building highly accurate multisequence alignments (MSA) from a single sequence or from MSAs. References: [1] Steinegger M, Meier M, Mirdita M, Vöhringer H, Haunsberger S J, and Söding J (2019) HH-suite3 for fast remote homology detection and deep protein annotation, BMC Bioinformatics, 473. doi: 10.1186/s12859-019-3019-7 [2] Kunzmann, P., Mayer, B.E. & Hamacher, K. Substitution matrix based color schemes for sequence alignment visualization. BMC Bioinformatics 21, 209 (2020). https://doi.org/10.1186/s12859-020-3526-6 Setup Let's quickly install anaconda and use it to properly install hhsuite. End of explanation """ !conda install -c conda-forge -c bioconda hhsuite """ Explanation: Be sure to input 'y' into the cell below to allow conda to install hh-suite to this colab. End of explanation """ !hhsearch """ Explanation: Using hhsearch hhblits and hhsearch are the main functions in hhsuite which identify homologous proteins. They do this by calculating a profile hidden Markov model (HMM) from a given alignment and searching over a reference HMM proteome database using the Viterbi algorithm. Then the most similar HMMs are realigned and output to the user. To learn more, check out the original paper in the references above. Run a function from hhsuite with no parameters to read its documentation. End of explanation """ %%bash cd /content/ mkdir hh cd hh mkdir databases; cd databases wget http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs/dbCAN-fam-V9.tar.gz tar xzvf dbCAN-fam-V9.tar.gz """ Explanation: Let's do an example. Say we have a protein which we want to compare to a MSA in order to identify any homologous regions. For this we can use hhsearch. Let's start by downloading a database to work with. hh-suite provides a set of HMM databases that will work with the software, which you can find here: http://wwwuser.gwdg.de/~compbiol/data/hhsuite/databases/hhsuite_dbs dbCAN is a good one for this tutorial because it is a small download. End of explanation """ with open('protein.fasta', 'w') as f: f.write(""" >Uncharacterized bovine protein (Fragment) --PAGGQCtgiWHLLTRPLRP--QGRLPGLRVKYVFLVWLGVFAGSWMAYTHYSSYAELCRGHICQVVICDQFRKGIISGSICQDLCHLHQVEWRTCLSSVPGQQVYSGLWQGKEVTIKCGIEESLNSKAGSDGAPRRELVLFDKPSRGTSIKEFREMTLSFLKANLGDLPSLPALVGRVLLMADFNKDNRVSLAEAKSVWALLQRNEFLLLLSLQEKEHASRLLGYCGDLYVTEGVPLSSWPGATLPPLLRPLLPPALHGALQQWLGPAWPWRAKIAMGLLEFVEDLFHGAYGNFYMCETTLANVGYTAKYDFRMADLQQVAPEAAVRRFLRGRRCEHSADCTYGRDCRAPCDTLMRQCKGDLVQPNLAKVCELLRDYLLPGAPAALRPELGKQLRTCTTLSGLASQVEAHHSLVLSHLKSLLWKEISDSRYT """) """ Explanation: Now let's take some protein sequence and search through the dbCAN database to see if we can find any potential homologous regions. First we will specify the sequence and save it as a FASTA file or a3m file in order to be readable by hhsearch. I pulled this sequence from the example query.a3m in the hhsuite data directory. End of explanation """ !hhsearch -i /content/protein.fasta -d /content/hh/databases/dbCAN-fam-V9 -o /content/protein.hhr """ Explanation: Then we can call hhsearch, specifying the query sequence with the -i flag, the database to search through with -d, and the output with -o. End of explanation """ with open('protein2.fasta', 'w') as f: f.write(""">dockerin,22,NCBI-Bacteria,gi|125972715|ref|YP_001036625.1|,162-245,0.033 SCADLNGDGKITSSDYNLLKRYILHLIDKFPIGNDETDEGINDGFNDETDEDINDSFIEANSKFAFDIFKQISKDEQGKNVFIS """) !hhsearch -i /content/protein2.fasta -d /content/hh/databases/dbCAN-fam-V9 -o /content/protein2.hhr """ Explanation: The 'Prob' column describes the estimated probability of the query sequence being at least partially homologous to the template. Probabilities of 95% or more are nearly certain, and probabilities of 30% or more call for closer consideration. The E value tells you how many random matches with a better score would be expected if the searched database was unrelated to the query sequence. These results show that none of the sequences align well with our randomly chosen protein, which is to be expected because our query sequence was chosen at random. Now let's check the results if we use a sequence that we know will align with something in the dbCAN database. I pulled this protein from the dockerin.faa file in dbCAN. End of explanation """ !wget -O protein3.fasta https://www.uniprot.org/uniprot/G8M3C3.fasta !hhblits -i /content/protein3.fasta -d /content/hh/databases/dbCAN-fam-V9 -oa3m query.a3m -n 2 """ Explanation: As you can see, there are 2 sequences which are a match for our query sequence. Using hhblits hhblits works in much the same way as hhsearch, but it is much faster and slightly less sensitive. This would be more suited to searching very large databases, or producing a MSA with multiple sequences instead of just one. Let's make use of that by using our query sequence to create an MSA. We could then use that MSA, with its family of proteins, to search a larger database for potential matches. This will be much more effective than searching a large database with a single sequence. We will use the same dbCAN database. I will pull a glycoside hydrolase protein from UnipProt, so it will likely be related to some proteins in dbCAN, which has carbohydrate-active enzymes. The option -oa3m will tell hhblits to output an MSA as an a3m file. The -n option specifies the number of iterations. This is recommended to keep between 1 and 4, we will try 2. End of explanation """
adityaka/misc_scripts
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/02_06/Final/Merge.ipynb
bsd-3-clause
import pandas as pd import numpy as np starting_date = '20160701' sample_numpy_data = np.array(np.arange(24)).reshape((6,4)) dates_index = pd.date_range(starting_date, periods=6) sample_df = pd.DataFrame(sample_numpy_data, index=dates_index, columns=list('ABCD')) sample_df_2 = sample_df.copy() sample_df_2['Fruits'] = ['apple', 'orange','banana','strawberry','blueberry','pineapple'] sample_series = pd.Series([1,2,3,4,5,6], index=pd.date_range(starting_date, periods=6)) sample_df_2['Extra Data'] = sample_series *3 +1 second_numpy_array = np.array(np.arange(len(sample_df_2))) *100 + 7 sample_df_2['G'] = second_numpy_array sample_df_2 """ Explanation: Merge Concat Join Append End of explanation """ pieces = [sample_df_2[:2], sample_df_2[2:4], sample_df_2[4:]] pieces """ Explanation: concat() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html separate data frame into a list with 3 elements End of explanation """ new_list = pieces[0], pieces[2] pd.concat(new_list) """ Explanation: concatenate first and last elements End of explanation """ new_last_row = sample_df_2.iloc[2] sample_df_2.append(new_last_row) sample_df_2 """ Explanation: append() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html End of explanation """ left = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) result = pd.merge(left, right, on='my_key') result """ Explanation: merge() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html Merge DataFrame objects by performing a database-style join operation by columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. End of explanation """
mne-tools/mne-tools.github.io
stable/_downloads/a3f6a5e6550d5cc477c48007e697532b/ems_filtering.ipynb
bsd-3-clause
# Author: Denis Engemann <denis.engemann@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD-3-Clause import numpy as np import matplotlib.pyplot as plt import mne from mne import io, EvokedArray from mne.datasets import sample from mne.decoding import EMS, compute_ems from sklearn.model_selection import StratifiedKFold print(__doc__) data_path = sample.data_path() # Preprocess the data meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif' event_fname = meg_path / 'sample_audvis_filt-0-40_raw-eve.fif' event_ids = {'AudL': 1, 'VisL': 3} # Read data and create epochs raw = io.read_raw_fif(raw_fname, preload=True) raw.filter(0.5, 45, fir_design='firwin') events = mne.read_events(event_fname) picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=True, exclude='bads') epochs = mne.Epochs(raw, events, event_ids, tmin=-0.2, tmax=0.5, picks=picks, baseline=None, reject=dict(grad=4000e-13, eog=150e-6), preload=True) epochs.drop_bad() epochs.pick_types(meg='grad') # Setup the data to use it a scikit-learn way: X = epochs.get_data() # The MEG data y = epochs.events[:, 2] # The conditions indices n_epochs, n_channels, n_times = X.shape # Initialize EMS transformer ems = EMS() # Initialize the variables of interest X_transform = np.zeros((n_epochs, n_times)) # Data after EMS transformation filters = list() # Spatial filters at each time point # In the original paper, the cross-validation is a leave-one-out. However, # we recommend using a Stratified KFold, because leave-one-out tends # to overfit and cannot be used to estimate the variance of the # prediction within a given fold. for train, test in StratifiedKFold(n_splits=5).split(X, y): # In the original paper, the z-scoring is applied outside the CV. # However, we recommend to apply this preprocessing inside the CV. # Note that such scaling should be done separately for each channels if the # data contains multiple channel types. X_scaled = X / np.std(X[train]) # Fit and store the spatial filters ems.fit(X_scaled[train], y[train]) # Store filters for future plotting filters.append(ems.filters_) # Generate the transformed data X_transform[test] = ems.transform(X_scaled[test]) # Average the spatial filters across folds filters = np.mean(filters, axis=0) # Plot individual trials plt.figure() plt.title('single trial surrogates') plt.imshow(X_transform[y.argsort()], origin='lower', aspect='auto', extent=[epochs.times[0], epochs.times[-1], 1, len(X_transform)], cmap='RdBu_r') plt.xlabel('Time (ms)') plt.ylabel('Trials (reordered by condition)') # Plot average response plt.figure() plt.title('Average EMS signal') mappings = [(key, value) for key, value in event_ids.items()] for key, value in mappings: ems_ave = X_transform[y == value] plt.plot(epochs.times, ems_ave.mean(0), label=key) plt.xlabel('Time (ms)') plt.ylabel('a.u.') plt.legend(loc='best') plt.show() # Visualize spatial filters across time evoked = EvokedArray(filters, epochs.info, tmin=epochs.tmin) evoked.plot_topomap(time_unit='s', scalings=1) """ Explanation: Compute effect-matched-spatial filtering (EMS) This example computes the EMS to reconstruct the time course of the experimental effect as described in :footcite:SchurgerEtAl2013. This technique is used to create spatial filters based on the difference between two conditions. By projecting the trial onto the corresponding spatial filters, surrogate single trials are created in which multi-sensor activity is reduced to one time series which exposes experimental effects, if present. We will first plot a trials × times image of the single trials and order the trials by condition. A second plot shows the average time series for each condition. Finally a topographic plot is created which exhibits the temporal evolution of the spatial filters. End of explanation """ epochs.equalize_event_counts(event_ids) X_transform, filters, classes = compute_ems(epochs) """ Explanation: Note that a similar transformation can be applied with compute_ems However, this function replicates Schurger et al's original paper, and thus applies the normalization outside a leave-one-out cross-validation, which we recommend not to do. End of explanation """