markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Linear Regression: Rounding and Subclassing In this notebook we investigate the influence of <em style="color:blue;">rounding</em> and <em style="color:blue;">subclassing</em> on linear regression. To begin, we import all the libraries we need.
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import sklearn.linear_model as lm
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We will work with artificially generated data. The independent variable X is a numpy array of $\texttt{N}=400$ random numbers that have a <em style="color:blue;">normal</em> distribution with mean $\mu = 10$ and standard deviation $1$. The data is created from random numbers. In order to be able to reproduce our results, we use the method numpy.random.seed.
np.random.seed(1) N = 400 𝜇 = 10 X = np.random.randn(N) + 𝜇
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The dependent variable Y is created by adding some noise to the independent variable X. This noise is <em style="color:blue;">normally</em> distributed with mean $0$ and standard deviation $0.5$.
noise = 0.5 * np.random.randn(len(X)) Y = X + noise
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We build a linear model for X and Y.
model = lm.LinearRegression()
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
In order to use SciKit-Learn we have to reshape the array X into a matrix.
X = np.reshape(X, (len(X), 1))
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We train the model and compute its score.
M = model.fit(X, Y) M.score(X, Y)
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
In order to plot the data together with the linear model, we extract the coefficients.
ϑ0 = M.intercept_ ϑ1 = M.coef_[0]
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We plot Y versus X and the linear regression line.
xMax = np.max(X) + 0.2 xMin = np.min(X) - 0.2 %matplotlib inline plt.figure(figsize=(15, 10)) sns.set(style='darkgrid') plt.scatter(X, Y, c='b') # 'b' is blue color plt.xlabel('X values') plt.ylabel('true values + noise') plt.title('Influence of rounding on explained variance') plt.show(plt.plot([xMin, xMax], [ϑ0 + ϑ1 * xMin, ϑ0 + ϑ1 * xMax], c='r'))
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
As we want to study the effect of <em style="color:blue;">rounding</em>, the values of the dependent variable X are rounded to the nearest integer. To this end, the values are transformed to another unit, rounded and then transformed back to the original unkit. This way we can investigate how the performance of linear regression degrades if the precision of the measurements of the independent variable is low.
X = np.round(X * 0.8) / 0.8
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We create a new <em style="color:blue;">linear model</em>, fit it to the data and compute its score.
model = lm.LinearRegression() M = model.fit(X, Y) M.score(X, Y)
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We can see that the performance of the linear model has degraded considerably.
ϑ0 = M.intercept_ ϑ1 = M.coef_[0] xMax = max(X) + 0.2 xMin = min(X) - 0.2 plt.figure(figsize=(12, 10)) sns.set(style='darkgrid') plt.scatter(X, Y, c='b') plt.plot([xMin, xMax], [ϑ0 + ϑ1 * xMin, ϑ0 + ϑ1 * xMax], c='r') plt.xlabel('rounded X values') plt.ylabel('true X values + noise') plt.title('Influence of rounding on explained variance') plt.show()
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Next, we investigate the effect of <em style="color:blue;">subclassing</em>. We will only keep those values such that $X > 11$.
X.shape selectorX = (X > 11) selectorY = np.reshape(selectorX, (N,)) XS = X[selectorX] XS = np.reshape(XS, (len(XS), 1)) YS = Y[selectorY]
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Again, we fit a linear model.
model = lm.LinearRegression() M = model.fit(XS, YS) M.score(XS, YS)
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
We see that the performance of linear regression has degraded considerably. Let's plot this.
ϑ0 = M.intercept_ ϑ1 = M.coef_[0] xMax = max(XS) + 0.2 xMin = min(XS) - 0.2 plt.figure(figsize=(12, 10)) sns.set(style='darkgrid') plt.scatter(XS, YS, c='b') plt.plot([xMin, xMax], [ϑ0 + ϑ1 * xMin, ϑ0 + ϑ1 * xMax], c='r') plt.xlabel('rounded X values') plt.ylabel('true X values + noise') plt.title('Influence of subclassing on explained variance') plt.show()
Python/5 Linear Regression/Linear-Regression-Rounding.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Problem statement We are interested in solving $$x^* = \arg \min_x f(x)$$ under the constraints that $f$ is a black box for which no closed form is known (nor its gradients); $f$ is expensive to evaluate; and evaluations of $y = f(x)$ may be noisy. Disclaimer. If you do not have these constraints, then there is certainly a better optimization algorithm than Bayesian optimization. Bayesian optimization loop For $t=1:T$: Given observations $(x_i, y_i=f(x_i))$ for $i=1:t$, build a probabilistic model for the objective $f$. Integrate out all possible true functions, using Gaussian process regression. optimize a cheap acquisition/utility function $u$ based on the posterior distribution for sampling the next point. $$x_{t+1} = \arg \min_x u(x)$$ Exploit uncertainty to balance exploration against exploitation. Sample the next observation $y_{t+1}$ at $x_{t+1}$. Acquisition functions Acquisition functions $\text{u}(x)$ specify which sample $x$ should be tried next: Expected improvement (default): $-\text{EI}(x) = -\mathbb{E} [f(x) - f(x_t^+)] $; Lower confidence bound: $\text{LCB}(x) = \mu_{GP}(x) + \kappa \sigma_{GP}(x)$; Probability of improvement: $-\text{PI}(x) = -P(f(x) \geq f(x_t^+) + \kappa) $; where $x_t^+$ is the best point observed so far. In most cases, acquisition functions provide knobs (e.g., $\kappa$) for controlling the exploration-exploitation trade-off. - Search in regions where $\mu_{GP}(x)$ is high (exploitation) - Probe regions where uncertainty $\sigma_{GP}(x)$ is high (exploration) Toy example Let assume the following noisy function $f$:
noise_level = 0.1 def f(x, noise_level=noise_level): return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) + np.random.randn() * noise_level
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Note. In skopt, functions $f$ are assumed to take as input a 1D vector $x$ represented as an array-like and to return a scalar $f(x)$.
# Plot f(x) + contours x = np.linspace(-2, 2, 400).reshape(-1, 1) fx = [f(x_i, noise_level=0.0) for x_i in x] plt.plot(x, fx, "r--", label="True (unknown)") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate(([fx_i - 1.9600 * noise_level for fx_i in fx], [fx_i + 1.9600 * noise_level for fx_i in fx[::-1]])), alpha=.2, fc="r", ec="None") plt.legend() plt.grid() plt.show()
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Bayesian optimization based on gaussian process regression is implemented in skopt.gp_minimize and can be carried out as follows:
from skopt import gp_minimize res = gp_minimize(f, # the function to minimize [(-2.0, 2.0)], # the bounds on each dimension of x acq_func="EI", # the acquisition function n_calls=15, # the number of evaluations of f n_random_starts=5, # the number of random initialization points noise=0.1**2, # the noise level (optional) random_state=123) # the random seed
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Accordingly, the approximated minimum is found to be:
"x^*=%.4f, f(x^*)=%.4f" % (res.x[0], res.fun)
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
For further inspection of the results, attributes of the res named tuple provide the following information: x [float]: location of the minimum. fun [float]: function value at the minimum. models: surrogate models used for each iteration. x_iters [array]: location of function evaluation for each iteration. func_vals [array]: function value for each iteration. space [Space]: the optimization space. specs [dict]: parameters passed to the function.
print(res)
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Together these attributes can be used to visually inspect the results of the minimization, such as the convergence trace or the acquisition function at the last iteration:
from skopt.plots import plot_convergence plot_convergence(res);
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Let us now visually examine The approximation of the fit gp model to the original function. The acquistion values that determine the next point to be queried.
from skopt.acquisition import gaussian_ei plt.rcParams["figure.figsize"] = (8, 14) x = np.linspace(-2, 2, 400).reshape(-1, 1) x_gp = res.space.transform(x.tolist()) fx = np.array([f(x_i, noise_level=0.0) for x_i in x]) # Plot the 5 iterations following the 5 random points for n_iter in range(5): gp = res.models[n_iter] curr_x_iters = res.x_iters[:5+n_iter] curr_func_vals = res.func_vals[:5+n_iter] # Plot true function. plt.subplot(5, 2, 2*n_iter+1) plt.plot(x, fx, "r--", label="True (unknown)") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([fx - 1.9600 * noise_level, fx[::-1] + 1.9600 * noise_level]), alpha=.2, fc="r", ec="None") # Plot GP(x) + contours y_pred, sigma = gp.predict(x_gp, return_std=True) plt.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.2, fc="g", ec="None") # Plot sampled points plt.plot(curr_x_iters, curr_func_vals, "r.", markersize=8, label="Observations") # Adjust plot layout plt.grid() if n_iter == 0: plt.legend(loc="best", prop={'size': 6}, numpoints=1) if n_iter != 4: plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') # Plot EI(x) plt.subplot(5, 2, 2*n_iter+2) acq = gaussian_ei(x_gp, gp, y_opt=np.min(curr_func_vals)) plt.plot(x, acq, "b", label="EI(x)") plt.fill_between(x.ravel(), -2.0, acq.ravel(), alpha=0.3, color='blue') next_x = res.x_iters[5+n_iter] next_acq = gaussian_ei(res.space.transform([next_x]), gp, y_opt=np.min(curr_func_vals)) plt.plot(next_x, next_acq, "bo", markersize=6, label="Next query point") # Adjust plot layout plt.ylim(0, 0.1) plt.grid() if n_iter == 0: plt.legend(loc="best", prop={'size': 6}, numpoints=1) if n_iter != 4: plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') plt.show()
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
The first column shows the following: The true function. The approximation to the original function by the gaussian process model How sure the GP is about the function. The second column shows the acquisition function values after every surrogate model is fit. It is possible that we do not choose the global minimum but a local minimum depending on the minimizer used to minimize the acquisition function. At the points closer to the points previously evaluated at, the variance dips to zero. Finally, as we increase the number of points, the GP model approaches the actual function. The final few points are clustered around the minimum because the GP does not gain anything more by further exploration:
plt.rcParams["figure.figsize"] = (6, 4) # Plot f(x) + contours x = np.linspace(-2, 2, 400).reshape(-1, 1) x_gp = res.space.transform(x.tolist()) fx = [f(x_i, noise_level=0.0) for x_i in x] plt.plot(x, fx, "r--", label="True (unknown)") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate(([fx_i - 1.9600 * noise_level for fx_i in fx], [fx_i + 1.9600 * noise_level for fx_i in fx[::-1]])), alpha=.2, fc="r", ec="None") # Plot GP(x) + contours gp = res.models[-1] y_pred, sigma = gp.predict(x_gp, return_std=True) plt.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.2, fc="g", ec="None") # Plot sampled points plt.plot(res.x_iters, res.func_vals, "r.", markersize=15, label="Observations") plt.title(r"$x^* = %.4f, f(x^*) = %.4f$" % (res.x[0], res.fun)) plt.legend(loc="best", prop={'size': 8}, numpoints=1) plt.grid() plt.show()
examples/bayesian-optimization.ipynb
betatim/BlackBox
bsd-3-clause
Raw data
# Whenever you type "something =" it defines a new variable, "something", # and sets it equal to whatever follows the equals sign. That could be a number, # another variable, or in this case an entire table of numbers. # enter raw data data = pd.DataFrame.from_items([ ('time (s)', [0,1,2,3]), ('position (m)', [0,2,4,6]) ]) # display data table data
Motion.ipynb
merryjman/astronomy
gpl-3.0
Plotting the data
# set variables = data['column label'] time = data['time (s)'] pos = data['position (m)'] # Uncomment the next line to make it look like a graph from xkcd.com # plt.xkcd() # to make normal-looking plots again execute: # mpl.rcParams.update(inline_rc) # this makes a scatterplot of the data # plt.scatter(x values, y values) plt.scatter(time, pos) plt.title("Constant Speed?") plt.xlabel("Time (s)") plt.ylabel("Position (cm)") plt.autoscale(tight=True) # calculate a trendline equation # np.polyfit( x values, y values, polynomial order) trend = np.polyfit(time, pos, 1) # plot trendline # plt.plot(x values, y values, other parameters) plt.plot(time, np.poly1d(trend)(time), label='trendline') plt.legend(loc='upper left') # display the trendline's coefficients (slope, y-int) trend
Motion.ipynb
merryjman/astronomy
gpl-3.0
Calculate and plot velocity
# create a new empty column data['velocity (m/s)'] = '' data # np.diff() calculates the difference between a value and the one after it vel = np.diff(pos) / np.diff(time) # fill the velocity column with values from the formula data['velocity (m/s)'] = pd.DataFrame.from_items([('', vel)]) # display the data table data # That last velocity value will cause problems for further coding # Make a new table using only rows 0 through 2 data2 = data.loc[0:2,['time (s)', 'velocity (m/s)']] data2 # set new variables to plot time2 = data2['time (s)'] vel2 = data2['velocity (m/s)'] # plot data just like before plt.scatter(time2, vel2) plt.title("Constant Speed?") plt.xlabel("Time (s)") plt.ylabel("Velocity (m)") plt.autoscale(tight=True) # calculate trendline equation like before trend2 = np.polyfit(time2, vel2, 1) # plot trendline like before plt.plot(time2, np.poly1d(trend2)(time2), label='trendline') plt.legend(loc='lower left') # display the trendline's coefficients (slope, y-int) trend2
Motion.ipynb
merryjman/astronomy
gpl-3.0
Modeling with MKS In this example the MKS equation will be used to predict microstructure at the next time step using $$p[s, 1] = \sum_{r=0}^{S-1} \alpha[l, r, 1] \sum_{l=0}^{L-1} m[l, s - r, 0] + ...$$ where $p[s, n + 1]$ is the concentration field at location $s$ and at time $n + 1$, $r$ is the convolution dummy variable and $l$ indicates the local states varable. $\alpha[l, r, n]$ are the influence coefficients and $m[l, r, 0]$ the microstructure function given to the model. $S$ is the total discretized volume and $L$ is the total number of local states n_states choosen to use. The model will march forward in time by recussively replacing discretizing $p[s, n]$ and substituing it back for $m[l, s - r, n]$. Calibration Datasets Unlike the elastostatic examples, the microstructure (concentration field) for this simulation doesn't have discrete phases. The microstructure is a continuous field that can have a range of values which can change over time, therefore the first order influence coefficients cannot be calibrated with delta microstructures. Instead a large number of simulations with random initial conditions are used to calibrate the first order influence coefficients using linear regression. The function make_cahn_hilliard from pymks.datasets provides an interface to generate calibration datasets for the influence coefficients. To use make_cahn_hilliard, we need to set the number of samples we want to use to calibrate the influence coefficients using n_samples, the size of the simulation domain using size and the time step using dt.
import pymks from pymks.datasets import make_cahn_hilliard n = 41 n_samples = 400 dt = 1e-2 np.random.seed(99) X, y = make_cahn_hilliard(n_samples=n_samples, size=(n, n), dt=dt)
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
The function make_cahnHilliard generates n_samples number of random microstructures, X, and the associated updated microstructures, y, after one time step y. The following cell plots one of these microstructures along with its update.
from pymks.tools import draw_concentrations draw_concentrations((X[0], y[0]), labels=('Input Concentration', 'Output Concentration'))
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Calibrate Influence Coefficients As mentioned above, the microstructures (concentration fields) does not have discrete phases. This leaves the number of local states in local state space as a free hyper parameter. In previous work it has been shown that as you increase the number of local states, the accuracy of MKS model increases (see Fast et al.), but as the number of local states increases, the difference in accuracy decreases. Some work needs to be done in order to find the practical number of local states that we will use. Optimizing the Number of Local States Let's split the calibrate dataset into testing and training datasets. The function train_test_split for the machine learning python module sklearn provides a convenient interface to do this. 80% of the dataset will be used for training and the remaining 20% will be used for testing by setting test_size equal to 0.2. The state of the random number generator used to make the split can be set using random_state.
import sklearn from sklearn.cross_validation import train_test_split split_shape = (X.shape[0],) + (np.product(X.shape[1:]),) X_train, X_test, y_train, y_test = train_test_split(X.reshape(split_shape), y.reshape(split_shape), test_size=0.5, random_state=3)
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
We are now going to calibrate the influence coefficients while varying the number of local states from 2 up to 20. Each of these models will then predict the evolution of the concentration fields. Mean square error will be used to compared the results with the testing dataset to evaluate how the MKS model's performance changes as we change the number of local states. First we need to import the class MKSLocalizationModel from pymks.
from pymks import MKSLocalizationModel from pymks.bases import PrimitiveBasis
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Next we will calibrate the influence coefficients while varying the number of local states and compute the mean squared error. The following demonstrates how to use Scikit-learn's GridSearchCV to optimize n_states as a hyperparameter. Of course, the best fit is always with a larger value of n_states. Increasing this parameter does not overfit the data.
from sklearn.grid_search import GridSearchCV parameters_to_tune = {'n_states': np.arange(2, 11)} prim_basis = PrimitiveBasis(2, [-1, 1]) model = MKSLocalizationModel(prim_basis) gs = GridSearchCV(model, parameters_to_tune, cv=5, fit_params={'size': (n, n)}) gs.fit(X_train, y_train) print(gs.best_estimator_) print(gs.score(X_test, y_test)) from pymks.tools import draw_gridscores draw_gridscores(gs.grid_scores_, 'n_states', score_label='R-squared', param_label='L-Number of Local States')
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
As expected the accuracy of the MKS model monotonically increases as we increase n_states, but accuracy doesn't improve significantly as n_states gets larger than signal digits. In order to save on computation costs let's set calibrate the influence coefficients with n_states equal to 6, but realize that if we need slightly more accuracy the value can be increased.
model = MKSLocalizationModel(basis=PrimitiveBasis(6, [-1, 1])) model.fit(X, y)
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Here are the first 4 influence coefficients.
from pymks.tools import draw_coeff draw_coeff(model.coeff[...,:4])
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Predict Microstructure Evolution With the calibrated influence coefficients, we are ready to predict the evolution of a concentration field. In order to do this, we need to have the Cahn-Hilliard simulation and the MKS model start with the same initial concentration phi0 and evolve in time. In order to do the Cahn-Hilliard simulation we need an instance of the class CahnHilliardSimulation.
from pymks.datasets.cahn_hilliard_simulation import CahnHilliardSimulation np.random.seed(191) phi0 = np.random.normal(0, 1e-9, (1, n, n)) ch_sim = CahnHilliardSimulation(dt=dt) phi_sim = phi0.copy() phi_pred = phi0.copy()
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
In order to move forward in time, we need to feed the concentration back into the Cahn-Hilliard simulation and the MKS model.
time_steps = 10 for ii in range(time_steps): ch_sim.run(phi_sim) phi_sim = ch_sim.response phi_pred = model.predict(phi_pred)
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Let's take a look at the concentration fields.
from pymks.tools import draw_concentrations_compare draw_concentrations((phi_sim[0], phi_pred[0]), labels=('Simulation', 'MKS'))
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
The MKS model was able to capture the microstructure evolution with 6 local states. Resizing the Coefficients to use on Larger Systems Now let's try and predict a larger simulation by resizing the coefficients and provide a larger initial concentratio field.
m = 3 * n model.resize_coeff((m, m)) phi0 = np.random.normal(0, 1e-9, (1, m, m)) phi_sim = phi0.copy() phi_pred = phi0.copy()
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Once again we are going to march forward in time by feeding the concentration fields back into the Cahn-Hilliard simulation and the MKS model.
for ii in range(1000): ch_sim.run(phi_sim) phi_sim = ch_sim.response phi_pred = model.predict(phi_pred)
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Let's take a look at the results.
from pymks.tools import draw_concentrations_compare draw_concentrations_compare((phi_sim[0], phi_pred[0]), labels=('Simulation', 'MKS'))
notebooks/cahn_hilliard.ipynb
XinyiGong/pymks
mit
Notebook Author: @SauravMaheshkar Introduction
import trax
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Serial Fn In Trax, we use combinators to build input pipelines, much like building deep learning models. The Serial combinator applies layers serially using function composition and uses stack semantics to manage data. Trax has the following definition for a Serial combinator. def Serial(*fns): def composed_fns(generator=None): for f in fastmath.tree_flatten(fns): generator = f(generator) return generator return composed_fns The Serial function has the following structure: It takes as input arbitrary number of functions Convert the structure into lists Iterate through the list and apply the functions Serially The fastmath.tree_flatten() function, takes a tree as a input and returns a flattened list. This way we can use various generator functions like Tokenize and Shuffle, and apply them serially by 'iterating' through the list. Initially, we've defined generator to None. Thus, in the first iteration we have no input and thus the first step executes the first function in our tree structure. In the next iteration, the generator variable is updated to be the output of the next function in the list. Log Function ``` def Log(n_steps_per_example=1, only_shapes=True): def log(stream): counter = 0 for example in stream: item_to_log = example if only_shapes: item_to_log = fastmath.nested_map(shapes.signature, example) if counter % n_steps_per_example == 0: logging.info(str(item_to_log)) print(item_to_log) counter += 1 yield example return log Every Deep Learning Framework needs to have a logging component for efficient debugging. trax.data.Log generator uses the absl package for logging. It uses a fastmath.nested_map function that maps a certain function recursively inside a object. In the case depicted below, the function maps the shapes.signature recursively inside the input stream, thus giving us the shapes of the various objects in our stream. -- The following two cells show the difference between when we set the only_shapes variable to False
data_pipeline = trax.data.Serial( trax.data.TFDS('imdb_reviews', keys=('text', 'label'), train=True), trax.data.Tokenize(vocab_dir='gs://trax-ml/vocabs/', vocab_file='en_8k.subword', keys=[0]), trax.data.Log(only_shapes=False) ) example = data_pipeline() print(next(example)) data_pipeline = trax.data.Serial( trax.data.TFDS('imdb_reviews', keys=('text', 'label'), train=True), trax.data.Tokenize(vocab_dir='gs://trax-ml/vocabs/', vocab_file='en_8k.subword', keys=[0]), trax.data.Log(only_shapes=True) ) example = data_pipeline() print(next(example))
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Shuffling our datasets Trax offers two generator functions to add shuffle functionality in our input pipelines. The shuffle function shuffles a given stream The Shuffle function returns a shuffle function instead shuffle ``` def shuffle(samples, queue_size): if queue_size < 1: raise ValueError(f'Arg queue_size ({queue_size}) is less than 1.') if queue_size == 1: logging.warning('Queue size of 1 results in no shuffling.') queue = [] try: queue.append(next(samples)) i = np.random.randint(queue_size) yield queue[i] queue[i] = sample except StopIteration: logging.warning( 'Not enough samples (%d) to fill initial queue (size %d).', len(queue), queue_size) np.random.shuffle(queue) for sample in queue: yield sample The shuffle function takes two inputs, the data stream and the queue size (minimum number of samples within which the shuffling takes place). Apart from the usual warnings, for negative and unity queue sizes, this generator function shuffles the given stream using np.random.randint() by randomly picks out integers using the queue_size as a range and then shuffle this new stream again using the np.random.shuffle()
sentence = ['Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?', 'But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum', 'At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.'] def sample_generator(x): for i in x: yield i example_shuffle = list(trax.data.inputs.shuffle(sample_generator(sentence), queue_size = 2)) example_shuffle
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Shuffle ``` def Shuffle(queue_size=1024): return lambda g: shuffle(g, queue_size) This function returns the aforementioned shuffle function and is mostly used in input pipelines. Batch Generators batch This function, creates batches for the input generator function. ``` def batch(generator, batch_size): if batch_size <= 0: raise ValueError(f'Batch size must be positive, but is {batch_size}.') buf = [] for example in generator: buf.append(example) if len(buf) == batch_size: batched_example = tuple(np.stack(x) for x in zip(*buf)) yield batched_example buf = [] It keeps adding objects from the generator into a list until the size becomes equal to the batch_size and then creates batches using the np.stack() function. It also raises an error for non-positive batch_sizes. Batch ``` def Batch(batch_size): return lambda g: batch(g, batch_size) This Function returns the aforementioned batch function with given batch size. Pad to Maximum Dimensions This function is used to pad a tuple of tensors to a joint dimension and return their batch. For example, in this case a pair of tensors (1,2) and ( (3,4) , (5,6) ) is changed to (1,2,0) and ( (3,4) , (5,6) , 0)
import numpy as np tensors = np.array([(1.,2.), ((3.,4.),(5.,6.))]) padded_tensors = trax.data.inputs.pad_to_max_dims(tensors=tensors, boundary=3) padded_tensors
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Creating Buckets For training Recurrent Neural Networks, with large vocabulary a method called Bucketing is usually applied. The usual technique of using padding ensures that all occurences within a mini-batch are of the same length. But this reduces the inter-batch variability and intuitively puts similar sentences into the same batch therefore, reducing the overall robustness of the system. Thus, we use Bucketing where multiple buckets are created depending on the length of the sentences and these occurences are assigned to buckets on the basis of which bucket corresponds to it's length. We need to ensure that the bucket sizes are large for adding some variablity to the system. bucket_by_length ``` def bucket_by_length(generator, length_fn, boundaries, batch_sizes,strict_pad_on_len=False): buckets = [[] for _ in range(len(batch_sizes))] boundaries = boundaries + [math.inf] for example in generator: length = length_fn(example) bucket_idx = min([i for i, b in enumerate(boundaries) if length <= b]) buckets[bucket_idx].append(example) if len(buckets[bucket_idx]) == batch_sizes[bucket_idx]: batched = zip(*buckets[bucket_idx]) boundary = boundaries[bucket_idx] boundary = None if boundary == math.inf else boundary padded_batch = tuple( pad_to_max_dims(x, boundary, strict_pad_on_len) for x in batched) yield padded_batch buckets[bucket_idx] = [] This function can be summarised as: Create buckets as per the lengths given in the batch_sizes array Assign sentences into buckets if their length matches the bucket size If padding is required, we use the pad_to_max_dims function Parameters generator: The input generator function length_fn: A custom length function for determing the length of functions, not necessarily len() boundaries: A python list containing corresponding bucket boundaries batch_sizes: A python list containing batch sizes strict_pad_on_len: – A python boolean variable (True or False). If set to true then the function pads on the length dimension, where dim[0] is strictly a multiple of boundary. BucketByLength ``` def BucketByLength(boundaries, batch_sizes,length_keys=None, length_axis=0, strict_pad_on_len=False): length_keys = length_keys or [0, 1] length_fn = lambda x: _length_fn(x, length_axis, length_keys) return lambda g: bucket_by_length(g, length_fn, boundaries, batch_sizes, strict_pad_on_len) This function, is usually used inside input pipelines(combinators) and uses the afforementioned bucket_by_length. It applies a predefined length_fn which chooses the maximum shape on length_axis over length_keys. It's use is illustrated below
data_pipeline = trax.data.Serial( trax.data.TFDS('imdb_reviews', keys=('text', 'label'), train=True), trax.data.Tokenize(vocab_dir='gs://trax-ml/vocabs/', vocab_file='en_8k.subword', keys=[0]), trax.data.BucketByLength(boundaries=[32, 128, 512, 2048], batch_sizes=[512, 128, 32, 8, 1], length_keys=[0]), trax.data.Log(only_shapes=True) ) example = data_pipeline() print(next(example))
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Filter by Length ``` def FilterByLength(max_length,length_keys=None, length_axis=0): length_keys = length_keys or [0, 1] length_fn = lambda x: _length_fn(x, length_axis, length_keys) def filtered(gen): for example in gen: if length_fn(example) <= max_length: yield example return filtered This function used the same predefined length_fn to only include those instances which are less than the given max_length parameter.
Filtered = trax.data.Serial( trax.data.TFDS('imdb_reviews', keys=('text', 'label'), train=True), trax.data.Tokenize(vocab_dir='gs://trax-ml/vocabs/', vocab_file='en_8k.subword', keys=[0]), trax.data.BucketByLength(boundaries=[32, 128, 512, 2048], batch_sizes=[512, 128, 32, 8, 1], length_keys=[0]), trax.data.FilterByLength(max_length=2048, length_keys=[0]), trax.data.Log(only_shapes=True) ) filtered_example = Filtered() print(next(filtered_example))
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Adding Loss Weights add_loss_weights ``` def add_loss_weights(generator, id_to_mask=None): for example in generator: if len(example) > 3 or len(example) < 2: assert id_to_mask is None, 'Cannot automatically mask this stream.' yield example else: if len(example) == 2: weights = np.ones_like(example[1]).astype(np.float32) else: weights = example[2].astype(np.float32) mask = 1.0 - np.equal(example[1], id_to_mask).astype(np.float32) weights *= mask yield (example[0], example[1], weights) This function essentially adds a loss mask (tensor of ones of the same shape) to the input stream. Masking is essentially a way to tell sequence-processing layers that certain timesteps in an input are missing, and thus should be skipped when processing the data. Thus, it adds 'weights' to the system. Parameters generator: The input data generator id_to_mask: The value with which to mask. Can be used as &lt;PAD&gt; in NLP. ``` train_generator = trax.data.inputs.add_loss_weights( data_generator(batch_size, x_train, y_train,vocab['<PAD>'], True), id_to_mask=vocab['<PAD>']) ``` For example, in this case I used the add_loss_weights function to add padding while implementing Named Entity Recogntion using the Reformer Architecture. You can read more about the project here. AddLossWeights This function performs the afforementioned add_loss_weights to the data stream. ``` def AddLossWeights(id_to_mask=None): return lambda g: add_loss_weights(g,id_to_mask=id_to_mask)
data_pipeline = trax.data.Serial( trax.data.TFDS('imdb_reviews', keys=('text', 'label'), train=True), trax.data.Tokenize(vocab_dir='gs://trax-ml/vocabs/', vocab_file='en_8k.subword', keys=[0]), trax.data.Shuffle(), trax.data.FilterByLength(max_length=2048, length_keys=[0]), trax.data.BucketByLength(boundaries=[ 32, 128, 512, 2048], batch_sizes=[512, 128, 32, 8, 1], length_keys=[0]), trax.data.AddLossWeights(), trax.data.Log(only_shapes=True) ) example = data_pipeline() print(next(example))
trax/examples/trax_data_Explained.ipynb
google/trax
apache-2.0
Load airports of each country
L=json.loads(file('../json/L.json','r').read()) M=json.loads(file('../json/M.json','r').read()) N=json.loads(file('../json/N.json','r').read()) import requests AP={} for c in M: if c not in AP:AP[c]={} for i in range(len(L[c])): AP[c][N[c][i]]=L[c][i]
code/airport_dest_parser2.ipynb
csaladenes/aviation
mit
record schedules for 2 weeks, then augment count with weekly flight numbers. seasonal and seasonal charter will count as once per week for 3 months, so 12/52 per week. TGM separate, since its history is in the past. parse Departures
baseurl='https://www.airportia.com/' import requests, urllib2 def urlgetter(url): s = requests.Session() cookiesopen = s.get(url) cookies=str(s.cookies) fcookies=[[k[:k.find('=')],k[k.find('=')+1:k.find(' for ')]] for k in cookies[cookies.find('Cookie '):].split('Cookie ')[1:]] #push token opener = urllib2.build_opener() for k in fcookies: opener.addheaders.append(('Cookie', k[0]+'='+k[1])) #read html return s.get(url).content
code/airport_dest_parser2.ipynb
csaladenes/aviation
mit
good dates
SD={} SC=json.loads(file('../json/SC2.json','r').read()) for h in range(2,5):#len(AP.keys())): c=AP.keys()[h] #country not parsed yet if c in SC: if c not in SD: SD[c]=[] print h,c airportialinks=AP[c] sch={} #all airports of country, where there is traffic for i in airportialinks: if i in SC[c]: print i, if i not in sch:sch[i]={} url=baseurl+airportialinks[i] m=urlgetter(url) for d in range (3,7): #date not parsed yet if d not in sch[i]: url=baseurl+airportialinks[i]+'departures/201704'+str(d) m=urlgetter(url) soup = BeautifulSoup(m, "lxml") #if there are flights at all if len(soup.findAll('table'))>0: sch[i][d]=pd.read_html(m)[0] else: print '--W-',d, SD[c]=sch print
code/airport_dest_parser2.ipynb
csaladenes/aviation
mit
Save
cnc_path='../../universal/countries/' cnc=pd.read_excel(cnc_path+'cnc.xlsx').set_index('Name') MDF=pd.DataFrame() for c in SD: sch=SD[c] mdf=pd.DataFrame() for i in sch: for d in sch[i]: df=sch[i][d].drop(sch[i][d].columns[3:],axis=1).drop(sch[i][d].columns[0],axis=1) df['From']=i df['Date']=d mdf=pd.concat([mdf,df]) mdf=mdf.replace('Hahn','Frankfurt') mdf=mdf.replace('Hahn HHN','Frankfurt HHN') mdf['City']=[i[:i.rfind(' ')] for i in mdf['To']] mdf['Airport']=[i[i.rfind(' ')+1:] for i in mdf['To']] file('../countries/'+cnc.T.loc[c]['ISO2'].lower()+"/json/mdf_dest.json",'w').write(json.dumps(mdf.reset_index().to_json())) MDF=pd.concat([MDF,mdf]) MDF.reset_index().to_json('../json/MDF.json')
code/airport_dest_parser2.ipynb
csaladenes/aviation
mit
The estimation game Root mean squared error is one of several ways to summarize the average error of an estimation process.
def RMSE(estimates, actual): """Computes the root mean squared error of a sequence of estimates. estimate: sequence of numbers actual: actual value returns: float RMSE """ e2 = [(estimate-actual)**2 for estimate in estimates] mse = np.mean(e2) return np.sqrt(mse)
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The following function simulates experiments where we try to estimate the mean of a population based on a sample with size n=7. We run iters=1000 experiments and collect the mean and median of each sample.
import random def Estimate1(n=7, iters=1000): """Evaluates RMSE of sample mean and median as estimators. n: sample size iters: number of iterations """ mu = 0 sigma = 1 means = [] medians = [] for _ in range(iters): xs = [random.gauss(mu, sigma) for _ in range(n)] xbar = np.mean(xs) median = np.median(xs) means.append(xbar) medians.append(median) print('Experiment 1') print('rmse xbar', RMSE(means, mu)) print('rmse median', RMSE(medians, mu)) Estimate1()
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Using $\bar{x}$ to estimate the mean works a little better than using the median; in the long run, it minimizes RMSE. But using the median is more robust in the presence of outliers or large errors. Estimating variance The obvious way to estimate the variance of a population is to compute the variance of the sample, $S^2$, but that turns out to be a biased estimator; that is, in the long run, the average error doesn't converge to 0. The following function computes the mean error for a collection of estimates.
def MeanError(estimates, actual): """Computes the mean error of a sequence of estimates. estimate: sequence of numbers actual: actual value returns: float mean error """ errors = [estimate-actual for estimate in estimates] return np.mean(errors)
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The following function simulates experiments where we try to estimate the variance of a population based on a sample with size n=7. We run iters=1000 experiments and two estimates for each sample, $S^2$ and $S_{n-1}^2$.
def Estimate2(n=7, iters=1000): mu = 0 sigma = 1 estimates1 = [] estimates2 = [] for _ in range(iters): xs = [random.gauss(mu, sigma) for i in range(n)] biased = np.var(xs) unbiased = np.var(xs, ddof=1) estimates1.append(biased) estimates2.append(unbiased) print('mean error biased', MeanError(estimates1, sigma**2)) print('mean error unbiased', MeanError(estimates2, sigma**2)) Estimate2()
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The mean error for $S^2$ is non-zero, which suggests that it is biased. The mean error for $S_{n-1}^2$ is close to zero, and gets even smaller if we increase iters. The sampling distribution The following function simulates experiments where we estimate the mean of a population using $\bar{x}$, and returns a list of estimates, one from each experiment.
def SimulateSample(mu=90, sigma=7.5, n=9, iters=1000): xbars = [] for j in range(iters): xs = np.random.normal(mu, sigma, n) xbar = np.mean(xs) xbars.append(xbar) return xbars xbars = SimulateSample()
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Here's the "sampling distribution of the mean" which shows how much we should expect $\bar{x}$ to vary from one experiment to the next.
cdf = thinkstats2.Cdf(xbars) thinkplot.Cdf(cdf) thinkplot.Config(xlabel='Sample mean', ylabel='CDF')
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The mean of the sample means is close to the actual value of $\mu$.
np.mean(xbars)
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
An interval that contains 90% of the values in the sampling disrtribution is called a 90% confidence interval.
ci = cdf.Percentile(5), cdf.Percentile(95) ci
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
And the RMSE of the sample means is called the standard error.
stderr = RMSE(xbars, 90) stderr
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Confidence intervals and standard errors quantify the variability in the estimate due to random sampling. Estimating rates The following function simulates experiments where we try to estimate the mean of an exponential distribution using the mean and median of a sample.
def Estimate3(n=7, iters=1000): lam = 2 means = [] medians = [] for _ in range(iters): xs = np.random.exponential(1.0/lam, n) L = 1 / np.mean(xs) Lm = np.log(2) / thinkstats2.Median(xs) means.append(L) medians.append(Lm) print('rmse L', RMSE(means, lam)) print('rmse Lm', RMSE(medians, lam)) print('mean error L', MeanError(means, lam)) print('mean error Lm', MeanError(medians, lam)) Estimate3()
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The RMSE is smaller for the sample mean than for the sample median. But neither estimator is unbiased. Exercises Exercise: Suppose you draw a sample with size n=10 from an exponential distribution with λ=2. Simulate this experiment 1000 times and plot the sampling distribution of the estimate L. Compute the standard error of the estimate and the 90% confidence interval. Repeat the experiment with a few different values of n and make a plot of standard error versus n.
# Solution def SimulateSample(lam=2, n=10, iters=1000): """Sampling distribution of L as an estimator of exponential parameter. lam: parameter of an exponential distribution n: sample size iters: number of iterations """ def VertLine(x, y=1): thinkplot.Plot([x, x], [0, y], color='0.8', linewidth=3) estimates = [] for _ in range(iters): xs = np.random.exponential(1.0/lam, n) lamhat = 1.0 / np.mean(xs) estimates.append(lamhat) stderr = RMSE(estimates, lam) print('standard error', stderr) cdf = thinkstats2.Cdf(estimates) ci = cdf.Percentile(5), cdf.Percentile(95) print('confidence interval', ci) VertLine(ci[0]) VertLine(ci[1]) # plot the CDF thinkplot.Cdf(cdf) thinkplot.Config(xlabel='estimate', ylabel='CDF', title='Sampling distribution') return stderr SimulateSample() # Solution # My conclusions: # 1) With sample size 10: # standard error 0.762510819389 # confidence interval (1.2674054394352277, 3.5377353792673705) # 2) As sample size increases, standard error and the width of # the CI decrease: # 10 0.90 (1.3, 3.9) # 100 0.21 (1.7, 2.4) # 1000 0.06 (1.9, 2.1) # All three confidence intervals contain the actual value, 2.
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Exercise: In games like hockey and soccer, the time between goals is roughly exponential. So you could estimate a team’s goal-scoring rate by observing the number of goals they score in a game. This estimation process is a little different from sampling the time between goals, so let’s see how it works. Write a function that takes a goal-scoring rate, lam, in goals per game, and simulates a game by generating the time between goals until the total time exceeds 1 game, then returns the number of goals scored. Write another function that simulates many games, stores the estimates of lam, then computes their mean error and RMSE. Is this way of making an estimate biased?
def SimulateGame(lam): """Simulates a game and returns the estimated goal-scoring rate. lam: actual goal scoring rate in goals per game """ goals = 0 t = 0 while True: time_between_goals = random.expovariate(lam) t += time_between_goals if t > 1: break goals += 1 # estimated goal-scoring rate is the actual number of goals scored L = goals return L # Solution # The following function simulates many games, then uses the # number of goals scored as an estimate of the true long-term # goal-scoring rate. def Estimate6(lam=2, m=1000000): estimates = [] for i in range(m): L = SimulateGame(lam) estimates.append(L) print('Experiment 4') print('rmse L', RMSE(estimates, lam)) print('mean error L', MeanError(estimates, lam)) pmf = thinkstats2.Pmf(estimates) thinkplot.Hist(pmf) thinkplot.Config(xlabel='Goals scored', ylabel='PMF') Estimate6() # Solution # My conclusions: # 1) RMSE for this way of estimating lambda is 1.4 # 2) The mean error is small and decreases with m, so this estimator # appears to be unbiased. # One note: If the time between goals is exponential, the distribution # of goals scored in a game is Poisson. # See https://en.wikipedia.org/wiki/Poisson_distribution
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Exercise: In this chapter we used $\bar{x}$ and median to estimate µ, and found that $\bar{x}$ yields lower MSE. Also, we used $S^2$ and $S_{n-1}^2$ to estimate σ, and found that $S^2$ is biased and $S_{n-1}^2$ unbiased. Run similar experiments to see if $\bar{x}$ and median are biased estimates of µ. Also check whether $S^2$ or $S_{n-1}^2$ yields a lower MSE.
# Solution def Estimate4(n=7, iters=100000): """Mean error for xbar and median as estimators of population mean. n: sample size iters: number of iterations """ mu = 0 sigma = 1 means = [] medians = [] for _ in range(iters): xs = [random.gauss(mu, sigma) for i in range(n)] xbar = np.mean(xs) median = np.median(xs) means.append(xbar) medians.append(median) print('Experiment 1') print('mean error xbar', MeanError(means, mu)) print('mean error median', MeanError(medians, mu)) Estimate4() # Solution def Estimate5(n=7, iters=100000): """RMSE for biased and unbiased estimators of population variance. n: sample size iters: number of iterations """ mu = 0 sigma = 1 estimates1 = [] estimates2 = [] for _ in range(iters): xs = [random.gauss(mu, sigma) for i in range(n)] biased = np.var(xs) unbiased = np.var(xs, ddof=1) estimates1.append(biased) estimates2.append(unbiased) print('Experiment 2') print('RMSE biased', RMSE(estimates1, sigma**2)) print('RMSE unbiased', RMSE(estimates2, sigma**2)) Estimate5() # Solution # My conclusions: # 1) xbar and median yield lower mean error as m increases, so neither # one is obviously biased, as far as we can tell from the experiment. # 2) The biased estimator of variance yields lower RMSE than the unbiased # estimator, by about 10%. And the difference holds up as m increases.
solutions/chap08soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
0. load clean data
df = pd.read_csv('./data/I-SPY_1_clean_data.csv') df.head(2)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
1. Inferential_statistics: Categorical vs Categorical (Chi-2 test) 1. 1 Effect of categorical predictors on Pathological complete response (PCR)
# example of contingency table inferential_statistics.contingency_table('PCR', 'ER+',df) # Perform chi-2 test on all categorical variables predictors = ['White', 'ER+', 'PR+', 'HR+','Right_Breast'] outcome = 'PCR' inferential_statistics.categorical_data(outcome, predictors, df)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
<h3><center> 1.1.2 Conclusion: Only `ER+` , `PR+`, and `HR+` have an effect on `PCR`</center></h3> 1. 2 Effect of categorical predictors on Survival (Alive)
predictors = ['White', 'ER+', 'PR+', 'HR+','Right_Breast','PCR'] outcome = 'Alive' inferential_statistics.categorical_data(outcome, predictors, df)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
<h3><center> 1.2.2 Conclusion: Only `ER+` and `HR+` have an effect on `Alive`</center></h3> 2. Inferential_statistics: Continous vs Categorical (ANOVA) 2.1 Effect of Age on PCR
predictor= ['age'] outcome = 'PCR' anova_table, OLS = inferential_statistics.linear_models(df, outcome, predictor); sns.boxplot(x= outcome, y=predictor[0], data=df, palette="Set3");
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
2.2 Effect of Age on Survival
predictor= ['age'] outcome = 'Alive' anova_table, OLS = inferential_statistics.linear_models(df, outcome, predictor); sns.boxplot(x= outcome, y=predictor[0], data=df, palette="Set3");
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
2.3 Explore interactions between age, survival, and PCR
# create a boxplot to visualize this interaction ax = sns.boxplot(x= 'PCR', y='age', hue ='Alive',data=df, palette="Set3"); ax.set_title('Interactions between age, survival, and PCR'); # create dataframe only for patients with PCR = Yes df_by_PCR = df.loc[df.PCR=='No',:] df_by_PCR.head() # Anova age vs Alive predictor= ['age'] outcome = 'Alive' anova_table, OLS = inferential_statistics.linear_models(df_by_PCR, outcome, predictor); # estimate the effect size mri_features = ['age'] outcome = 'Alive' # Effect Size inferential_statistics.effect_size( df_by_PCR, mri_features, outcome)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
Conclusion. age has an important effect on Alive for patients with PCR = Yes To quantitify this effect a logistic regression is needed 2.4 Effect of MRI measurements on PCR ANOVA
R = inferential_statistics.anova_MRI('PCR', df);
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
Estimate the effect size
mri_features = ['MRI_LD_Baseline', 'MRI_LD_1_3dAC', 'MRI_LD_Int_Reg', 'MRI_LD_PreSurg'] outcome = 'PCR' # Effect Size inferential_statistics.effect_size( df, mri_features, outcome)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
2.5 Effect of MRI measurements on Survival ANOVA
outcome = 'Alive' R = inferential_statistics.anova_MRI(outcome, df); mri_features = ['MRI_LD_Baseline', 'MRI_LD_1_3dAC', 'MRI_LD_Int_Reg', 'MRI_LD_PreSurg'] outcome = 'Alive' # Effect Size inferential_statistics.effect_size( df, mri_features, outcome)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
stratify analysis by PCR
# predictors and outcomes predictors= ['MRI_LD_Baseline', 'MRI_LD_1_3dAC', 'MRI_LD_Int_Reg', 'MRI_LD_PreSurg'] # split data and run anova PCR_outcomes = ['No','Yes'] for out in PCR_outcomes: df_by_PCR = df.loc[df.PCR == out,:] print('Outcome = Alive' + ' | ' + 'PCR = ' + out) # Anova anova_table, OLS = inferential_statistics.linear_models(df_by_PCR, 'Alive', predictors); # Effect Size print(inferential_statistics.effect_size( df_by_PCR, predictors, 'Alive')) print('\n' * 2)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
Conclusion The largest tumor dimension measured at baseline (MRI_LD_Baseline) is not a statistically different between patients who achieved complete pathological response (PCR)and those who did not. While all other MRI measurements are statistically different between PCR = Yes, and PCR = No All MRI measurements of the tumor dimension are different between patients who are Alive at the end of the trial and those who did not. These results do not indicate anything about the size of these effects. An statistically significant effect is not always clinically significant The estimated effect sizes are very small, and most likley not clinically significant
## 3. Inferential_statistics: Continous vs Categorical (ANOVA)
2-Inferential_Stats.ipynb
JCardenasRdz/Insights-into-the-I-SPY-clinical-trial
mit
There's a peak at value around 1.0 which represents quiet.
plt.hist(x_rms_instruments_notes[x_rms_instruments_notes <= 1].flatten(), 200); plt.hist(x_rms_instruments_notes[x_rms_instruments_notes > 1].flatten(), 200);
instrument-classification/analyze_instrument_ranges.ipynb
bzamecnik/ml
mit
The range of instruments split into quiet (black) and sounding (white) regions. We can limit the pitches to the sounding ones.
plt.imshow(x_rms_instruments_notes > 1, interpolation='none', cmap='gray') plt.grid(True) plt.suptitle('MIDI instruments range - RMS power') plt.xlabel('MIDI note') plt.ylabel('MIDI instrument') plt.savefig('data/working/instrument_ranges_binary.png');
instrument-classification/analyze_instrument_ranges.ipynb
bzamecnik/ml
mit
Model Inputs First we need to create the inputs for our graph. We need two inputs, one for the discriminator and one for the generator. Here we'll call the discriminator input inputs_real and the generator input inputs_z. We'll assign them the appropriate sizes for each of the networks. Exercise: Finish the model_inputs function below. Create the placeholders for inputs_real and inputs_z using the input sizes real_dim and z_dim respectively.
def model_inputs(real_dim, z_dim): inputs_real = tf.placeholder(tf.float32, shape = (None, real_dim), name="inputs_real") inputs_z = tf.placeholder(tf.float32, shape = (None, z_dim), name ="inputs_z") return inputs_real, inputs_z
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Generator network Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values. Variable Scope Here we need to use tf.variable_scope for two reasons. Firstly, we're going to make sure all the variable names start with generator. Similarly, we'll prepend discriminator to the discriminator variables. This will help out later when we're training the separate networks. We could just use tf.name_scope to set the names, but we also want to reuse these networks with different inputs. For the generator, we're going to train it, but also sample from it as we're training and after training. The discriminator will need to share variables between the fake and real input images. So, we can use the reuse keyword for tf.variable_scope to tell TensorFlow to reuse the variables instead of creating new ones if we build the graph again. To use tf.variable_scope, you use a with statement: python with tf.variable_scope('scope_name', reuse=False): # code here Here's more from the TensorFlow documentation to get another look at using tf.variable_scope. Leaky ReLU TensorFlow doesn't provide an operation for leaky ReLUs, so we'll need to make one . For this you can use take the outputs from a linear fully connected layer and pass them to tf.maximum. Typically, a parameter alpha sets the magnitude of the output for negative values. So, the output for negative input (x) values is alpha*x, and the output for positive x is x: $$ f(x) = max(\alpha * x, x) $$ Tanh Output The generator has been found to perform the best with $tanh$ for the generator output. This means that we'll have to rescale the MNIST images to be between -1 and 1, instead of 0 and 1. Exercise: Implement the generator network in the function below. You'll need to return the tanh output. Make sure to wrap your code in a variable scope, with 'generator' as the scope name, and pass the reuse keyword argument from the function to tf.variable_scope.
def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01): ''' Build the generator network. Arguments --------- z : Input tensor for the generator out_dim : Shape of the generator output n_units : Number of units in hidden layer reuse : Reuse the variables with tf.variable_scope alpha : leak parameter for leaky ReLU Returns ------- out, logits: ''' with tf.variable_scope('Generator', reuse=reuse): # Hidden layer h1 = tf.layers.dense(z, n_units, activation = None) # Leaky ReLU h1 = tf.maximum( (alpha * h1), h1) # Logits and tanh output logits = tf.layers.dense(h1, out_dim, activation = None) out = tf.tanh(logits) return out
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Discriminator The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer. Exercise: Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a variable scope, with 'discriminator' as the scope name, and pass the reuse keyword argument from the function arguments to tf.variable_scope.
def discriminator(x, n_units=128, reuse=False, alpha=0.01): ''' Build the discriminator network. Arguments --------- x : Input tensor for the discriminator n_units: Number of units in hidden layer reuse : Reuse the variables with tf.variable_scope alpha : leak parameter for leaky ReLU Returns ------- out, logits: ''' with tf.variable_scope('Discriminator', reuse=reuse): # Hidden layer h1 = tf.layers.dense(x, n_units, activation = None) # Leaky ReLU h1 = tf.maximum ( (alpha * h1), h1) logits = tf.layers.dense(h1, 1, activation = None) out = tf.sigmoid(logits) return out, logits
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Hyperparameters
# Size of input image to discriminator input_size = 784 # 28x28 MNIST images flattened # Size of latent vector to generator z_size = 784 # Sizes of hidden layers in generator and discriminator g_hidden_size = 256 d_hidden_size = 256 # Leak factor for leaky ReLU alpha = 0.01 # Label smoothing smooth = 0.1
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Build network Now we're building the network from the functions defined above. First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z. Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes. Then the discriminators. We'll build two of them, one for real data and one for fake data. Since we want the weights to be the same for both real and fake data, we need to reuse the variables. For the fake data, we're getting it from the generator as g_model. So the real data discriminator is discriminator(input_real) while the fake discriminator is discriminator(g_model, reuse=True). Exercise: Build the network from the functions you defined earlier.
tf.reset_default_graph() # Create our input placeholders input_real, input_z = model_inputs(input_size, z_size) # Generator network here g_model = generator(input_z, input_size) # g_model is the generator output # Disriminator network here d_model_real, d_logits_real = discriminator(input_real) d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Discriminator and Generator Losses Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropys, which we can get with tf.nn.sigmoid_cross_entropy_with_logits. We'll also wrap that in tf.reduce_mean to get the mean for all the images in the batch. So the losses will look something like python tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels)) For the real image logits, we'll use d_logits_real which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example, using the parameter smooth. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like labels = tf.ones_like(tensor) * (1 - smooth) The discriminator loss for the fake data is similar. The logits are d_logits_fake, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that. Finally, the generator losses are using d_logits_fake, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images. Exercise: Calculate the losses for the discriminator and the generator. There are two discriminator losses, one for real images and one for fake images. For the real image loss, use the real logits and (smoothed) labels of ones. For the fake image loss, use the fake logits with labels of all zeros. The total discriminator loss is the sum of those two losses. Finally, the generator loss again uses the fake logits from the discriminator, but this time the labels are all ones because the generator wants to fool the discriminator.
# Calculate losses # One's like for real labels for Discriminator real_labels = tf.ones_like(d_logits_real) * (1 - smooth) d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits = d_logits_real, labels=real_labels)) # Zeros's like for real labels for Discriminator fake_labels = tf.zeros_like(d_logits_real) d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( logits = d_logits_fake, labels= fake_labels)) d_loss = d_loss_real + d_loss_fake # One's like for fake labels for generator generated_labels = tf.ones_like(d_logits_fake) g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = d_logits_fake, labels = generated_labels))
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Optimizers We want to update the generator and discriminator variables separately. So we need to get the variables for each part build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph. For the generator optimizer, we only want to generator variables. Our past selves were nice and used a variable scope to start all of our generator variable names with generator. So, we just need to iterate through the list from tf.trainable_variables() and keep variables to start with generator. Each variable object has an attribute name which holds the name of the variable as a string (var.name == 'weights_0' for instance). We can do something similar with the discriminator. All the variables in the discriminator start with discriminator. Then, in the optimizer we pass the variable lists to var_list in the minimize method. This tells the optimizer to only update the listed variables. Something like tf.train.AdamOptimizer().minimize(loss, var_list=var_list) will only train the variables in var_list. Exercise: Below, implement the optimizers for the generator and discriminator. First you'll need to get a list of trainable variables, then split that list into two lists, one for the generator variables and another for the discriminator variables. Finally, using AdamOptimizer, create an optimizer for each network that update the network variables separately.
# Optimizers learning_rate = 0.002 # Get the trainable_variables, split into G and D parts t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if var.name.startswith('Generator')] d_vars = [var for var in t_vars if var.name.startswith('Discriminator')] d_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list = d_vars) g_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list = g_vars)
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Training
batch_size = 100 epochs = 80 samples = [] losses = [] saver = tf.train.Saver(var_list = g_vars) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for e in range(epochs): for ii in range(mnist.train.num_examples//batch_size): batch = mnist.train.next_batch(batch_size) # Get images, reshape and rescale to pass to D batch_images = batch[0].reshape((batch_size, 784)) batch_images = batch_images*2 - 1 # Sample random noise for G batch_z = np.random.uniform(-1, 1, size=(batch_size, z_size)) # Run optimizers _ = sess.run(d_train_opt, feed_dict={input_real: batch_images, input_z: batch_z}) _ = sess.run(g_train_opt, feed_dict={input_z: batch_z}) # At the end of each epoch, get the losses and print them out train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images}) train_loss_g = g_loss.eval({input_z: batch_z}) print("Epoch {}/{}...".format(e+1, epochs), "Discriminator Loss: {:.4f}...".format(train_loss_d), "Generator Loss: {:.4f}".format(train_loss_g), "Difference Loss: {:.4f}...".format(train_loss_d-train_loss_g), ) # Save losses to view after training losses.append((train_loss_d, train_loss_g)) # Sample from generator as we're training for viewing afterwards sample_z = np.random.uniform(-1, 1, size=(16, z_size)) gen_samples = sess.run( generator(input_z, input_size, reuse=True), feed_dict={input_z: sample_z}) samples.append(gen_samples) saver.save(sess, './checkpoints/generator.ckpt') # Save training generator samples with open('train_samples.pkl', 'wb') as f: pkl.dump(samples, f)
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Results with 128 hidden units Epoch 72/100... Discriminator Loss: 1.2292... Generator Loss: 1.0937 Difference Loss: 0.1355... Epoch 73/100... Discriminator Loss: 1.1977... Generator Loss: 1.0838 Difference Loss: 0.1139... Epoch 74/100... Discriminator Loss: 1.0160... Generator Loss: 1.4791 Difference Loss: -0.4632... Epoch 75/100... Discriminator Loss: 1.1122... Generator Loss: 1.0486 Difference Loss: 0.0637... Epoch 76/100... Discriminator Loss: 1.0662... Generator Loss: 1.5303 Difference Loss: -0.4641... Epoch 77/100... Discriminator Loss: 1.1943... Generator Loss: 1.1728 Difference Loss: 0.0215... Epoch 78/100... Discriminator Loss: 1.1579... Generator Loss: 1.3853 Difference Loss: -0.2274... Epoch 79/100... Discriminator Loss: 1.1481... Generator Loss: 1.1773 Difference Loss: -0.0292... Epoch 80/100... Discriminator Loss: 1.1529... Generator Loss: 1.6801 Difference Loss: -0.5272... Training loss Here we'll check out the training losses for the generator and discriminator.
%matplotlib inline import matplotlib.pyplot as plt # With 128 hidden fig, ax = plt.subplots() losses = np.array(losses) plt.plot(losses.T[0], label='Discriminator') plt.plot(losses.T[1], label='Generator') plt.title("Training Losses") plt.legend() # With 256 hidden fig, ax = plt.subplots() losses = np.array(losses) plt.plot(losses.T[0], label='Discriminator') plt.plot(losses.T[1], label='Generator') plt.title("Training Losses") plt.legend()
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Generator samples from training Here we can view samples of images from the generator. First we'll look at images taken while training.
def view_samples(epoch, samples): fig, axes = plt.subplots(figsize=(7,7), nrows=4, ncols=4, sharey=True, sharex=True) for ax, img in zip(axes.flatten(), samples[epoch]): ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) im = ax.imshow(img.reshape((28,28)), cmap='Greys_r') return fig, axes # Load samples from generator taken while training with open('train_samples.pkl', 'rb') as f: samples = pkl.load(f) plt.imshow(mnist.train.images[3].reshape(28,28), cmap='Greys_r')
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
These are samples from the final training epoch. You can see the generator is able to reproduce numbers like 5, 7, 3, 0, 9. Since this is just a sample, it isn't representative of the full range of images this generator can make.
# with 128 _ = view_samples(-1, samples) # with 256 _ = view_samples(-1, samples)
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Below I'm showing the generated images as the network was training, every 10 epochs. With bonus optical illusion!
# with 256 rows, cols = 10, 6 fig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True) for sample, ax_row in zip(samples[::int(len(samples)/rows)], axes): for img, ax in zip(sample[::int(len(sample)/cols)], ax_row): ax.imshow(img.reshape((28,28)), cmap='Greys_r') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) # with 128 rows, cols = 10, 6 fig, axes = plt.subplots(figsize=(7,12), nrows=rows, ncols=cols, sharex=True, sharey=True) for sample, ax_row in zip(samples[::int(len(samples)/rows)], axes): for img, ax in zip(sample[::int(len(sample)/cols)], ax_row): ax.imshow(img.reshape((28,28)), cmap='Greys_r') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False)
gans/gan_mnist/Intro_to_GANs_Exercises.ipynb
swirlingsand/deep-learning-foundations
mit
Hyperparameters The following are hyperparameters that will have an impact on the learning algorithm.
# Architecture N_HIDDEN = [800,800] NON_LINEARITY = lasagne.nonlinearities.rectify # Dropout parameters #DROP_INPUT = 0.2 #DROP_HIDDEN = 0.5 DROP_INPUT = None DROP_HIDDEN = None # Number of epochs to train the net NUM_EPOCHS = 50 # Optimization learning rate LEARNING_RATE = 0.01 # Batch Size BATCH_SIZE = 128 # Optimizer eta = theano.shared(lasagne.utils.floatX(LEARNING_RATE)) my_optimizer = lambda loss, params: lasagne.updates.nesterov_momentum( loss, params, learning_rate=eta, momentum=0.9)
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
An optimizer can be seen as a function that takes a gradient, obtained by backpropagation, and returns an update to be applied to the current parameters. Other optimizers can be found in: optimizer reference. In order to be able to change the learning rate dynamically, we must use a shared variable that will be accessible afterwards. Dataset In this example, we are using the celebrated MNIST dataset. The following are functions that download the MNIST dataset, resize it into a convenient numpy array for images of size (n_example, n_channel, img_width, img_height) and split the dataset into a train set (50k images) and a validation set (10k images). The pixels are normalized by 255.
import os def load_mnist(): """ A dataloader for MNIST """ from urllib.request import urlretrieve def download(filename, source='http://yann.lecun.com/exdb/mnist/'): print("Downloading %s" % filename) urlretrieve(source + filename, filename) # We then define functions for loading MNIST images and labels. # For convenience, they also download the requested files if needed. import gzip def load_mnist_images(filename): if not os.path.exists(filename): download(filename) # Read the inputs in Yann LeCun's binary format. with gzip.open(filename, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=16) # The inputs are vectors now, we reshape them to monochrome 2D images, # following the shape convention: (examples, channels, rows, columns) data = data.reshape(-1, 1, 28, 28) # The inputs come as bytes, we convert them to float32 in range [0,1]. return data / np.float32(255) def load_mnist_labels(filename): if not os.path.exists(filename): download(filename) # Read the labels in Yann LeCun's binary format. with gzip.open(filename, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=8) # The labels are vectors of integers now, that's exactly what we want. return data # We can now download and read the training and test set images and labels. X_train = load_mnist_images('train-images-idx3-ubyte.gz') y_train = load_mnist_labels('train-labels-idx1-ubyte.gz') X_test = load_mnist_images('t10k-images-idx3-ubyte.gz') y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz') # We reserve the last 10000 training examples for validation. X_train, X_val = X_train[:-10000], X_train[-10000:] y_train, y_val = y_train[:-10000], y_train[-10000:] # We just return all the arrays in order, as expected in main(). # (It doesn't matter how we do this as long as we can read them again.) return X_train, y_train, X_val, y_val, X_test, y_test # Load the dataset print("Loading data...") X_train, y_train, X_val, y_val, X_test, y_test = load_mnist() n_train = X_train.shape[0] input_shape = X_train[0].shape print(input_shape) input_shape = (None, input_shape[0], input_shape[1], input_shape[2]) %matplotlib inline import matplotlib.pyplot as plt n_img_row = 3 n_img_col = 3 plt.rcParams['figure.figsize'] = (12,12) # Make the figures a bit bigger for i in range(n_img_row*n_img_col): plt.subplot(n_img_row,n_img_col,i+1) plt.axis('off') idx = np.random.randint(n_train) plt.imshow(X_train[idx][0], cmap='gray') plt.title("Label {}".format(y_train[idx]))
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
The following auxiliary function creates a minibatch in a 3D tensor (batch_size, img_width, img_height).
def iterate_minibatches(inputs, targets, batchsize, shuffle=False): """ Return a minibatch of images with the associated targets Keyword arguments: :type inputs: numpy.ndarray :param inputs: the dataset of images :type targets: numpy.ndarray :param targets: the targets associated to the dataset :type batchsize: int :param batchsize: the number of datapoints in the minibatch :type shuffle: bool :param shuffle: a flag if we want to shuffle the dataset """ assert len(inputs) == len(targets) if shuffle: indices = np.arange(len(inputs)) np.random.shuffle(indices) for start_idx in range(0, len(inputs) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield inputs[excerpt], targets[excerpt]
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
Model definition The next two functions are general functions for creating multi-layer perceptron (mlp) and convolutional neural networks (cnn).
def create_mlp( input_shape, input_var=None, nonlinearity = lasagne.nonlinearities.rectify, n_hidden=[800], drop_input=.2, drop_hidden=.5): """ A generic function for creating a multi-layer perceptron. If n_hidden is given as a list, then depth is ignored. :type input_shape: tuple :param input_shape: a tuple containing the shape of the input :type input_var: theano.tensor.var.TensorVariable :param input_var: a theano symbolic variable, created automatically if None :type nonlinearity: lasagne.nonlinearities :param nonlinearity: a nonlinearity function that follows all dense layers :type n_hidden: list :param n_hidden: number of hidden units per layer :type drop_input: float :param drop_input: the probability of dropout for the input :type drop_hidden: float :param drop_hidden: the probability of dropout for the hidden units """ # if input_shape is None, then the mlp is used on top of an existing model if input_shape: # if input_var is None, lasagne create # automatically the associated theano variable network = lasagne.layers.InputLayer( shape=input_shape, input_var=input_var) if drop_input: network = lasagne.layers.dropout( incoming=network, p=drop_input) else: network = input_var for i in range(len(n_hidden)): network = lasagne.layers.DenseLayer( incoming=network, num_units=n_hidden[i], nonlinearity=nonlinearity ) if drop_hidden: network = lasagne.layers.dropout( incoming=network, p=drop_hidden ) network = lasagne.layers.DenseLayer( incoming=network, num_units=10, nonlinearity=lasagne.nonlinearities.softmax ) return network # Create a network input_var = T.tensor4('inputs') target_var = T.ivector('targets') network = create_mlp( input_shape, input_var=input_var, nonlinearity=NON_LINEARITY, n_hidden=N_HIDDEN, drop_input=DROP_INPUT, drop_hidden=DROP_HIDDEN)
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
Optimization In the following, we want to maximize the probability to output the right digit given the image. To do this, we retrieve the output of our model, which is a softmax (probability distribution) over the 10 digits, and we compare it to the actual target. Finally, since we are using minibatches of size BATCH_SIZE, we compute the mean over the examples of the minibatch.
# Create a loss expression for training prediction = lasagne.layers.get_output(network) loss = lasagne.objectives.categorical_crossentropy(prediction, target_var).mean() params = lasagne.layers.get_all_params(network, trainable=True) updates = my_optimizer(loss, params) # Compile a function performing a training step on a mini-batch (by giving # the updates dictionary) and returning the corresponding training loss: train_fn = theano.function([input_var, target_var], loss, updates=updates) # Create a loss expression for validation/testing. The crucial difference # here is that we do a deterministic forward pass through the network, # disabling dropout layers. valid_prediction = lasagne.layers.get_output(network, deterministic=True) valid_loss = lasagne.objectives.categorical_crossentropy(valid_prediction, target_var).mean() # We also create an expression for the classification accuracy: valid_acc = lasagne.objectives.categorical_accuracy(valid_prediction, target_var).mean() # Compile a second function computing the validation loss and accuracy: valid_fn = theano.function([input_var, target_var], [valid_loss, valid_acc])
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
Training loop The following training loop is minimal and often insufficient for real-world purposes. The idea here is to show the minimal requirements for training a neural network. Also, we plot to show the evolution of the train and validation losses.|
#%matplotlib notebook plt.rcParams['figure.figsize'] = (4,4) # Make the figures a bit bigger import time def train( train_fn, X_train, y_train, valid_fn, X_valid, y_valid, num_epochs=50, batchsize=100): ################### # code for plotting ################### fig,ax = plt.subplots(1,1) ax.set_xlabel('Epoch') ax.set_ylabel('NLL') ax.set_xlim(0,50) ax.set_ylim(0,0.5) train_log = [] valid_log = [] ################### n_train_batches = X_train.shape[0] // batchsize # Warning last examples are not used n_valid_batches = X_valid.shape[0] // batchsize for epoch in range(num_epochs): train_loss = 0 for inputs, targets in iterate_minibatches(X_train, y_train, batchsize, shuffle=True): train_loss += train_fn(inputs, targets) valid_loss = 0 for inputs, targets in iterate_minibatches(X_valid, y_valid, batchsize, shuffle=False): loss,_ = valid_fn(inputs, targets) valid_loss += loss ################### # code for plotting ################### train_log.append(train_loss/n_train_batches) valid_log.append(valid_loss/n_valid_batches) #print(train_loss/n_train_batches, valid_loss/n_valid_batches) if ax.lines: ax.lines[0].set_xdata(range(0,epoch+1)) ax.lines[0].set_ydata(train_log) ax.lines[1].set_xdata(range(0,epoch+1)) ax.lines[1].set_ydata(valid_log) else: ax.plot(epoch, train_log[epoch], 'b', label='train') ax.plot(epoch, valid_log[epoch], 'r', label='valid') ax.legend() ax.grid() fig.canvas.draw() time.sleep(0.1) ################### train(train_fn, X_train, y_train, valid_fn, X_val, y_val)
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
The following training loop contains features that are interesting to consider: - early-stopping - logging and filenames - checkpointing - adaptive step-size (optional) The first three are the most important ones.
import time import pickle def train( train_fn, X_train, y_train, valid_fn, X_valid, y_valid, num_epochs=100, batchsize=64): print("Starting training...") train_loss_array = [] valid_loss_array = [] # early-stopping parameters n_iter = 0 n_train_batches = X_train.shape[0] // batchsize # Warning last examples are not used n_valid_batches = X_valid.shape[0] // batchsize patience = 10 * n_train_batches # look as this many examples regardless patience_increase = 2. # wait this much longer when a new best is # found improvement_threshold = 0.995 # a relative improvement of this much is # considered significant validation_frequency = min(n_train_batches, patience // 2) # go through this many # minibatche before checking the network # on the validation set; in this case we # check every epoch best_valid_loss = np.inf best_iter = 0 test_score = 0. epoch = 0 done_looping = False if not isinstance(N_HIDDEN, list): n_hidden = [N_HIDDEN] * DEPTH else: n_hidden = N_HIDDEN exp_log_filename = 'mlp_lr-{}_arch-{}_bs-{}_seed-{}.log'.format( LEARNING_RATE, '-'.join(str(i) for i in n_hidden), batchsize, seed ) with open(exp_log_filename, 'w') as f: log_line = '{} \t\t{} \t\t{} \t\t{} \n'.format('epoch', 'train_loss', 'valid_loss', 'valid_acc') f.write(log_line) while epoch < num_epochs and not done_looping: train_loss = 0 start_time = time.time() for inputs, targets in iterate_minibatches(X_train, y_train, batchsize, shuffle=True): train_loss += train_fn(inputs, targets) # And a full pass over the validation data: valid_loss = 0 valid_acc = 0 for inputs, targets in iterate_minibatches(X_valid, y_valid, batchsize, shuffle=False): loss, acc = valid_fn(inputs, targets) valid_loss += loss valid_acc += acc # Then we print the results for this epoch: avg_train_loss = train_loss / n_train_batches avg_valid_loss = valid_loss / n_valid_batches avg_valid_acc = valid_acc / n_valid_batches * 100 print("Epoch {} of {} took {:.3f}s".format( epoch + 1, num_epochs, time.time() - start_time)) print(" training loss:\t\t{:.6f}".format(avg_train_loss)) print(" validation loss:\t\t{:.6f}".format(avg_valid_loss)) print(" validation accuracy:\t\t{:.2f} %".format(avg_valid_acc)) train_loss_array.append(avg_train_loss) valid_loss_array.append(avg_valid_loss) with open(exp_log_filename, 'a') as f: log_line = '{} \t\t{:.6f} \t\t{:.6f} \t\t{:.2f} \n'.format(epoch, avg_train_loss, avg_valid_loss, avg_valid_acc) f.write(log_line) # if we got the best validation score until now n_iter += n_train_batches if valid_loss < best_valid_loss: #improve patience if loss improvement is good enough if valid_loss < best_valid_loss * improvement_threshold: patience = max(patience, n_iter * patience_increase) best_valid_loss = valid_loss best_iter = n_iter # save the best model with open('best_model.pkl', 'wb') as f: all_params_values = lasagne.layers.get_all_param_values(network) pickle.dump(all_params_values, f) eta.set_value(lasagne.utils.floatX(eta.get_value() * 1.2)) if patience <= n_iter: done_looping = True break else: all_params_values = pickle.load(open('best_model.pkl','rb')) lasagne.layers.set_all_param_values(network, all_params_values) eta.set_value(lasagne.utils.floatX(eta.get_value() * 0.5)) epoch += 1 train_log, valid_log = train(train_fn, X_train, y_train, valid_fn, X_val, y_val) !ls !tail mlp_lr-0.01_arch-800-800_bs-64_seed-1.log # load the saved model all_params_values = pickle.load(open('best_model.pkl','rb')) lasagne.layers.set_all_param_values(network, all_params_values) # After training, we compute the test error. test_loss, test_acc = valid_fn(X_test, y_test) print("Final results:") print(" test loss:\t\t\t {:.6f}".format(np.asscalar(test_loss))) print(" test accuracy:\t\t {:.2f} %".format(np.asscalar(test_acc*100)))
notebooks/classification/lasagne_nn.ipynb
gmarceaucaron/ecole-apprentissage-profond
bsd-3-clause
Now we'll start by invoking the GPIO class, which will identify our board and initialize the pins. We will use two pins for input for scrolling through the slideshow. We default to the spidev device at <code>/dev/spidev0.0</code> for the minnow Additionally, the Data/Command and Reset pins are defined for the TFT LCD display.
myGPIO = GPIO.get_platform_gpio() myGPIO.setup(12,GPIO.IN) myGPIO.setup(16,GPIO.IN) lcd = ADA_LCD() lcd.clear() SPI_PORT = 0 SPI_DEVICE = 0 SPEED = 16000000 DC = 10 RST = 14
Slideshow.ipynb
MinnowBoard/fishbowl-notebooks
mit
The following functions collect all the images in the specified directory and place them into a list. It will filter out all the non-image files in the directory. It will fail if no images are found.
imageList = [] rawList = os.listdir("/notebooks") for i in range(0,len(rawList)): if (rawList[i].lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))==True): imageList.append("/notebooks" + "/" + rawList[i]) if len(imageList)==0: print "No images found!" exit(1) count = 0 print imageList
Slideshow.ipynb
MinnowBoard/fishbowl-notebooks
mit
Now we'll initialize the TFT LCD display and clear it.
disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT,SPI_DEVICE,SPEED)) disp.begin()
Slideshow.ipynb
MinnowBoard/fishbowl-notebooks
mit
This long infinite loop will work like so: <b>Clear the char LCD, write name of new image</b> <b>Wait for a button press</b> <b>Try to open an image</b> <b>Display the image on the TFT LCD</b> --If we fail to open the file, print an error message to the LCD display-- ----If we failed, open up the next file in the list. If we're at the end, restart at the beginning ----
while True: lcd.clear() time.sleep(0.25) message = " Image " + str(count+1) + " of " + str(len(imageList)) + "\n" + imageList[count][len(sys.argv[1]):] lcd.message(message) lcd.scroll() try: image = Image.open(imageList[count]) except(IOError): lcd.clear() time.sleep(0.25) message = " ERR: " + str(count+1) + " of " + str(len(imageList)) + "\n" + imageList[count][len(sys.argv[1]):] lcd.scroll() lcd.message(message) if(count == len(imageList)-1): image = Image.open(imageList[0]) else: image = Image.open(imageList[count+1]) image = image.rotate(90).resize((240, 320)) disp.display(image) try: while True: if (myGPIO.input(12) != 1 and count != 0): count = count - 1 break if (myGPIO.input(16) != 1 and count != len(imageList)-1): count = count + 1 break except (KeyboardInterrupt): lcd.clear() lcd.message("Terminated") print exit(0)
Slideshow.ipynb
MinnowBoard/fishbowl-notebooks
mit
Initial concepts An object is a container of data (attributes) and code (methods) A class is a template for creating objects Reuse is provided by: reusing the same class to create many objects "inheriting" data and code from other classes
# Definiting a Car class class Car(object): pass car = Car()
Spring2019/06a_Objects/Building Software With Objects.ipynb
UWSEDS/LectureNotes
bsd-2-clause
Attributes
from IPython.display import Image Image(filename='ClassAttributes.png')
Spring2019/06a_Objects/Building Software With Objects.ipynb
UWSEDS/LectureNotes
bsd-2-clause