markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
In matplotlib, the line style and color can be set with a third argument to plot. Examples of this argument:
dashed red: r--
blue circles: bo
dotted black: k.
Write a plot_sine2(a, b, style) function that has a third style argument that allows you to set the line style of the plot. The style should default to a blue ... | # YOUR CODE HERE
raise NotImplementedError()
plot_sine2(4.0, -1.0, 'r--') | assignments/assignment05/InteractEx02.ipynb | sthuggins/phys202-2015-work | mit |
Use interact to create a UI for plot_sine2.
Use a slider for a and b as above.
Use a drop down menu for selecting the line style between a dotted blue line line, black circles and red triangles. | # YOUR CODE HERE
raise NotImplementedError()
assert True # leave this for grading the plot_sine2 exercise | assignments/assignment05/InteractEx02.ipynb | sthuggins/phys202-2015-work | mit |
Federal funds rate with switching intercept
The first example models the federal funds rate as noise around a constant intercept, but where the intercept changes during different regimes. The model is simply:
$$r_t = \mu_{S_t} + \varepsilon_t \qquad \varepsilon_t \sim N(0, \sigma^2)$$
where $S_t \in {0, 1}$, and the re... | # Get the federal funds rate data
from statsmodels.tsa.regime_switching.tests.test_markov_regression import fedfunds
dta_fedfunds = pd.Series(fedfunds, index=pd.date_range('1954-07-01', '2010-10-01', freq='QS'))
# Plot the data
dta_fedfunds.plot(title='Federal funds rate', figsize=(12,3))
# Fit the model
# (a switchi... | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
From the summary output, the mean federal funds rate in the first regime (the "low regime") is estimated to be $3.7$ whereas in the "high regime" it is $9.6$. Below we plot the smoothed probabilities of being in the high regime. The model suggests that the 1980's was a time-period in which a high federal funds rate exi... | res_fedfunds.smoothed_marginal_probabilities[1].plot(
title='Probability of being in the high regime', figsize=(12,3)); | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
From the estimated transition matrix we can calculate the expected duration of a low regime versus a high regime. | print(res_fedfunds.expected_durations) | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
A low regime is expected to persist for about fourteen years, whereas the high regime is expected to persist for only about five years.
Federal funds rate with switching intercept and lagged dependent variable
The second example augments the previous model to include the lagged value of the federal funds rate.
$$r_t = ... | # Fit the model
mod_fedfunds2 = sm.tsa.MarkovRegression(
dta_fedfunds.iloc[1:], k_regimes=2, exog=dta_fedfunds.iloc[:-1])
res_fedfunds2 = mod_fedfunds2.fit()
res_fedfunds2.summary() | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
There are several things to notice from the summary output:
The information criteria have decreased substantially, indicating that this model has a better fit than the previous model.
The interpretation of the regimes, in terms of the intercept, have switched. Now the first regime has the higher intercept and the seco... | res_fedfunds2.smoothed_marginal_probabilities[0].plot(
title='Probability of being in the high regime', figsize=(12,3)); | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
Finally, the expected durations of each regime have decreased quite a bit. | print(res_fedfunds2.expected_durations) | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
Taylor rule with 2 or 3 regimes
We now include two additional exogenous variables - a measure of the output gap and a measure of inflation - to estimate a switching Taylor-type rule with both 2 and 3 regimes to see which fits the data better.
Because the models can be often difficult to estimate, for the 3-regime model... | # Get the additional data
from statsmodels.tsa.regime_switching.tests.test_markov_regression import ogap, inf
dta_ogap = pd.Series(ogap, index=pd.date_range('1954-07-01', '2010-10-01', freq='QS'))
dta_inf = pd.Series(inf, index=pd.date_range('1954-07-01', '2010-10-01', freq='QS'))
exog = pd.concat((dta_fedfunds.shift(... | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
Due to lower information criteria, we might prefer the 3-state model, with an interpretation of low-, medium-, and high-interest rate regimes. The smoothed probabilities of each regime are plotted below. | fig, axes = plt.subplots(3, figsize=(10,7))
ax = axes[0]
ax.plot(res_fedfunds4.smoothed_marginal_probabilities[0])
ax.set(title='Smoothed probability of a low-interest rate regime')
ax = axes[1]
ax.plot(res_fedfunds4.smoothed_marginal_probabilities[1])
ax.set(title='Smoothed probability of a medium-interest rate regi... | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
Switching variances
We can also accomodate switching variances. In particular, we consider the model
$$
y_t = \mu_{S_t} + y_{t-1} \beta_{S_t} + \varepsilon_t \quad \varepsilon_t \sim N(0, \sigma_{S_t}^2)
$$
We use maximum likelihood to estimate the parameters of this model: $p_{00}, p_{10}, \mu_0, \mu_1, \beta_0, \beta... | # Get the federal funds rate data
from statsmodels.tsa.regime_switching.tests.test_markov_regression import areturns
dta_areturns = pd.Series(areturns, index=pd.date_range('2004-05-04', '2014-5-03', freq='W'))
# Plot the data
dta_areturns.plot(title='Absolute returns, S&P500', figsize=(12,3))
# Fit the model
mod_aret... | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
The first regime is a low-variance regime and the second regime is a high-variance regime. Below we plot the probabilities of being in the low-variance regime. Between 2008 and 2012 there does not appear to be a clear indication of one regime guiding the economy. | res_areturns.smoothed_marginal_probabilities[0].plot(
title='Probability of being in a low-variance regime', figsize=(12,3)); | examples/notebooks/markov_regression.ipynb | josef-pkt/statsmodels | bsd-3-clause |
2 - Outline of the Assignment
To build your neural network, you will be implementing several "helper functions". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions tha... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
parameters -- python dictionary containing your parameters:
W1 --... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected output:
<table style="width:80%">
<tr>
<td> **W1** </td>
<td> [[ 0.01624345 -0.00611756 -0.00528172]
[-0.01072969 0.00865408 -0.02301539]] </td>
</tr>
<tr>
<td> **b1**</td>
<td>[[ 0.]
[ 0.]]</td>
</tr>
<tr>
<td>**W2**</td>
<td> [[ 0.01744812 -0.00761207]]</td>
</tr>
... | # GRADED FUNCTION: initialize_parameters_deep
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected output:
<table style="width:80%">
<tr>
<td> **W1** </td>
<td>[[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]
[-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]
[-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]
[-0.00404677 -0.0054536 -0.01546477 0.00982367 -... | # GRADED FUNCTION: linear_forward
def linear_forward(A, W, b):
"""
Implement the linear part of a layer's forward propagation.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current la... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected output:
<table style="width:35%">
<tr>
<td> **Z** </td>
<td> [[ 3.26295337 -1.23429987]] </td>
</tr>
</table>
4.2 - Linear-Activation Forward
In this notebook, you will use two activation functions:
Sigmoid: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you w... | # GRADED FUNCTION: linear_activation_forward
def linear_activation_forward(A_prev, W, b, activation):
"""
Implement the forward propagation for the LINEAR->ACTIVATION layer
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weigh... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected output:
<table style="width:35%">
<tr>
<td> **With sigmoid: A ** </td>
<td > [[ 0.96890023 0.11013289]]</td>
</tr>
<tr>
<td> **With ReLU: A ** </td>
<td > [[ 3.43896131 0. ]]</td>
</tr>
</table>
Note: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a s... | # GRADED FUNCTION: L_model_forward
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
<table style="width:40%">
<tr>
<td> **AL** </td>
<td > [[ 0.17007265 0.2524272 ]]</td>
</tr>
<tr>
<td> **Length of caches list ** </td>
<td > 2</td>
</tr>
</table>
Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predict... | # GRADED FUNCTION: compute_cost
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), sh... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>**cost** </td>
<td> 0.41493159961539694</td>
</tr>
</table>
6 - Backward propagation module
Just like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss funct... | # GRADED FUNCTION: linear_backward
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from ... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected Output:
<table style="width:90%">
<tr>
<td> **dA_prev** </td>
<td > [[ 0.51822968 -0.19517421]
[-0.40506361 0.15255393]
[ 2.37496825 -0.89445391]] </td>
</tr>
<tr>
<td> **dW** </td>
<td > [[-0.10076895 1.40685096 1.64992505]] </td>
</tr>
<tr>
<td> **d... | # GRADED FUNCTION: linear_activation_backward
def linear_activation_backward(dA, cache, activation):
"""
Implement the backward propagation for the LINEAR->ACTIVATION layer.
Arguments:
dA -- post-activation gradient for current layer l
cache -- tuple of values (linear_cache, activation_cache)... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected output with sigmoid:
<table style="width:100%">
<tr>
<td > dA_prev </td>
<td >[[ 0.11017994 0.01105339]
[ 0.09466817 0.00949723]
[-0.05743092 -0.00576154]] </td>
</tr>
<tr>
<td > dW </td>
<td > [[ 0.10266786 0.09778551 -0.01968084]] </td>
</tr>
<tr>
... | # GRADED FUNCTION: L_model_backward
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (contain... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
Expected Output
<table style="width:60%">
<tr>
<td > dW1 </td>
<td > [[ 0.41010002 0.07807203 0.13798444 0.10502167]
[ 0. 0. 0. 0. ]
[ 0.05283652 0.01005865 0.01777766 0.0135308 ]] </td>
</tr>
<tr>
<td > db1 </td>
<td > [[-0.22007063]... | # GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
... | Building your Deep Neural Network - Step by Step/Building+your+Deep+Neural+Network+-+Step+by+Step+v4.ipynb | GuillaumeDec/machine-learning | gpl-3.0 |
mlxtend - Multilayer Perceptron Examples
Sections
Classify Iris
Classify handwritten digits from MNIST
<br>
<br>
Classify Iris
Load 2 features from Iris (petal length and petal width) for visualization purposes. | from mlxtend.data import iris_data
X, y = iris_data()
X = X[:, 2:] | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Train neural network for 3 output flower classes ('Setosa', 'Versicolor', 'Virginica'), regular gradient decent (minibatches=1), 30 hidden units, and no regularization. | from mlxtend.classifier import NeuralNetMLP
import numpy as np
nn1 = NeuralNetMLP(n_output=3,
n_features=X.shape[1],
n_hidden=30,
l2=0.0,
l1=0.0,
epochs=5000,
eta=0.001,
alpha=0.00,
minibatches=1,
shuffle=True,
random_sta... | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Now, check if the gradient descent converged after 5000 epochs, and choose smaller learning rate (eta) otherwise. | import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(range(len(nn1.cost_)), nn1.cost_)
plt.ylim([0, 300])
plt.ylabel('Cost')
plt.xlabel('Epochs')
plt.grid()
plt.show() | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Standardize features for smoother and faster convergence. | X_std = np.copy(X)
for i in range(2):
X_std[:,i] = (X[:,i] - X[:,i].mean()) / X[:,i].std()
nn2 = NeuralNetMLP(n_output=3,
n_features=X_std.shape[1],
n_hidden=30,
l2=0.0,
l1=0.0,
epochs=1000,
eta=0.05,
alpha=0.1,
minibatches=1,
... | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Visualize the decision regions. | from mlxtend.evaluate import plot_decision_regions
plot_decision_regions(X, y, clf=nn1)
plt.xlabel('petal length [cm]')
plt.ylabel('petal width [cm]')
plt.show() | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
<br>
<br>
Classify handwritten digits from MNIST
Load a 5000-sample subset of the MNIST dataset. | from mlxtend.data import mnist_data
X, y = mnist_data() | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Visualize a sample from the MNIST dataset. | def plot_digit(X, y, idx):
img = X[idx].reshape(28,28)
plt.imshow(img, cmap='Greys', interpolation='nearest')
plt.title('true label: %d' % y[idx])
plt.show()
plot_digit(X, y, 4) | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Initialize the neural network to recognize the 10 different digits (0-10) using 300 epochs and minibatch learning. | nn = NeuralNetMLP(n_output=10, n_features=X.shape[1],
n_hidden=100,
l2=0.0,
l1=0.0,
epochs=300,
eta=0.0005,
alpha=0.0,
minibatches=50,
random_state=1) | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Learn the features while printing the progress to get an idea about how long it may take. | nn.fit(X, y, print_progress=True)
y_pred = nn.predict(X)
acc = np.sum(y == y_pred, axis=0) / X.shape[0]
print('Accuracy: %.2f%%' % (acc * 100)) | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Check for convergence. | plt.plot(range(len(nn.cost_)), nn.cost_)
plt.ylim([0, 500])
plt.ylabel('Cost')
plt.xlabel('Mini-batches * Epochs')
plt.show()
plt.plot(range(len(nn.cost_)//50), nn.cost_[::50], color='red')
plt.ylim([0, 500])
plt.ylabel('Cost')
plt.xlabel('Epochs')
plt.show() | docs/examples/classifier_nn_mlp.ipynb | YoungKwonJo/mlxtend | bsd-3-clause |
Exercícios para a próxima aula
Fazer uma função que amplie/reduza a imagem utilizando interpolação no domínio da frequência,
conforme discutido em aula. Comparar os resultados com o scipy.misc.imresize, tanto de qualidade do
espectro como de tempo de execução.
Os alunos com RA ímpar devem fazer as ampliações... | def imresize(f, size):
'''
Resize an image
Parameters
----------
f: input image
size: integer, float or tuple
- integer: percentage of current size
- float: fraction of current size
- tuple: new dimensions
Returns
-------
output image r... | deliver/Aula_10_Wavelets.ipynb | robertoalotufo/ia898 | mit |
Modificar a função pconv para executar no domínio da frequência, caso o número de
elementos não zeros da menor imagem, é maior que um certo valor, digamos 15.
Nome da função: pconvfft | def pconvfft(f,h):
'''
Periodical convolution.
This is an efficient implementation of the periodical convolution.
This implementation should be comutative, i.e., pconvfft(f,h)==pconvfft(h,f).
This implementation should be fast. If the number of pixels used in the
convolution is larger than 15, ... | deliver/Aula_10_Wavelets.ipynb | robertoalotufo/ia898 | mit |
Transforma Discreta de Wavelets
Iremos utilizar um notebook que foi um resultado de projeto de anos
anteriores.
DWT | /home/lotufo/ia898/dev/wavelets.ipynb | deliver/Aula_10_Wavelets.ipynb | robertoalotufo/ia898 | mit |
"Post-NOV0215" verification testing using the MAR0516O products
These are nominal flight-like products created using the existing MAR0516 loads.
One expected difference is that Matlab uses the OFLS CHARACTERISTICS file
CHARACTERIS_07JUL16 to back out the OFLS ODB_SI_ALIGN transform.
MAR0516 was planned using CHARACTERI... | PRODUCTS = 'MAR0516O'
TEST_DIR = '/proj/sot/ska/ops/SFE'
FLIGHT_DIR = '/data/mpcrit1/mplogs/2016' # Must match PRODUCTS
# SI_ALIGN from Matlab code
SI_ALIGN = chandra_aca.ODB_SI_ALIGN
SI_ALIGN
def print_dq(q1, q2):
"""
Print the difference between two quaternions in a nice formatted way.
"""
dq = q1... | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
Check internal consistency of dynamical_offsets table
This checks that applying the sum of target and ACA offsets along with the nominal SI_ALIGN to the target attitude produces the ACA attitude.
All the ACIS observations have a similar offset due to the CHARACTERISTICS mismatch noted earlier, while the HRC observation... | for obs in dat:
check_obs(obs) | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
Check dynamical offsets ACA attitude matches TEST maneuver summary
It is assumed that the maneuver summary matches the load product attitudes. | filename = glob.glob(os.path.join(TEST_DIR, PRODUCTS, 'ofls', 'mps', 'mm*.sum'))[0]
print('Reading', filename)
mm = parse_cm.maneuver.read_maneuver_summary(filename, structured=True)
mm = {m['final']['id']: m for m in mm} # Turn into a dict
for obs in dat:
check_obs_vs_manvr(obs, mm[obs['obsid'] * 100]) | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
Check dynamical offsets ACA attitude matches FLIGHT maneuver summary to ~10 arcsec
It is assumed that the maneuver summary matches the load product attitudes.
There are three discrepancies below: obsids 18725, 18790, and 18800. All of these are DDT observations that are configured in the OR list to use Cycle 18 aimpoi... | os.path.join(FLIGHT_DIR, PRODUCTS[:-1], 'ofls', 'mps', 'mm*.sum')
filename = glob.glob(os.path.join(FLIGHT_DIR, PRODUCTS[:-1], 'ofls', 'mps', 'mm*.sum'))[0]
print('Reading', filename)
mm = parse_cm.maneuver.read_maneuver_summary(filename, structured=True)
mm = {m['final']['id']: m for m in mm} # Turn into a dict
for... | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
Check that predicted CHIPX / CHIPY matches expectation to within 10 arcsec.
Use the test ACA attitude and observed SIM DY/DZ (alignment from fids).
Generate a "fake" observation with adjusted RA_NOM, DEC_NOM, ROLL_NOM ("HRMA attitude").
Adjustment based on the delta between TEST and FLIGHT pointing attitudes.
Use the ... | ciaoenv = Ska.Shell.getenv('source /soft/ciao/bin/ciao.sh')
ciaorun = functools.partial(Ska.Shell.bash, env=ciaoenv)
dmcoords_cmd = ['dmcoords', 'none',
'asolfile=none',
'detector="{detector}"',
'fpsys="{fpsys}"',
'opt=cel',
'ra={ra_targ}'... | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
For pre-NOV1615 products with an empty zero-offsets aimpoint table
Check that TEST (JUL0415M) and FLIGHT attitudes from maneuver summary match to within 0.1 arcsec.
JUL0415M was constructed with an OR-list zero-offset aimpoint table which exists but has
no row entries. This has the effect of telling SAUSAGE to run thr... | PRODUCTS = 'JUL0415M'
FLIGHT_DIR = '/data/mpcrit1/mplogs/2015' # Must match PRODUCTS
# Get FLIGHT maneuver summary
filename = glob.glob(os.path.join(FLIGHT_DIR, PRODUCTS[:-1], 'ofls', 'mps', 'mm*.sum'))[0]
print('Reading', filename)
mmf = parse_cm.maneuver.read_maneuver_summary(filename, structured=True)
mmf = {m['fi... | testing/dynam_offsets/verify_dynamic_offsets.ipynb | sot/aimpoint_mon | bsd-2-clause |
b) Load dataset
Download customer account data from Wiley's website, RetailMart.xlsx | # find path to your RetailMart.xlsx
dataset = pd.read_excel(open('C:/Users/craigrshenton/Desktop/Dropbox/excel_data_sci/ch06/RetailMart.xlsx','rb'), sheetname=0)
dataset = dataset.drop('Unnamed: 17', 1) # drop empty col
dataset.rename(columns={'PREGNANT':'Pregnant'}, inplace=True)
dataset.rename(columns={'Home/Apt/ PO ... | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
The 'Pregnant' column can only take on one of two (in this case) possabilities. Here 1 = pregnant, and 0 = not pregnant
2. Summarize Data
a) Descriptive statistics | # shape
print(dataset.shape)
# types
print(dataset.dtypes)
# head
dataset.head()
# feature distribution
print(dataset.groupby('Implied_Gender').size())
# target distribution
print(dataset.groupby('Pregnant').size())
# correlation
r = dataset.corr(method='pearson')
id_matrix = np.identity(r.shape[0]) # create ident... | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
We can see no features with significant correlation coefficents (i.e., $r$ values > 0.7)
3. Prepare Data
a) Data Transforms
We need to 'dummify' (i.e., separate out) the catagorical variables: implied gender and residency | # dummify gender variable
dummy_gender = pd.get_dummies(dataset['Implied_Gender'], prefix='Gender')
print(dummy_gender.head())
# dummify residency variable
dummy_resident = pd.get_dummies(dataset['Residency'], prefix='Resident')
print(dummy_resident.head())
# Drop catagorical variables
dataset = dataset.drop('Implied... | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
4. Evaluate Algorithms
a) Split-out validation dataset | # Split-out validation dataset
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y,
test_size=validation_size, random_state=seed) | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
b) Spot Check Algorithms | # Spot-Check Algorithms
models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC()))
# evaluate each model i... | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
c) Select The Best Model | # Compare Algorithms
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(names)
plt.show() | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
5. Make predictions on validation dataset
Linear Discriminant Analysis is just about the most accurate model. Now test the accuracy of the model on the validation dataset. | lda = LinearDiscriminantAnalysis()
lda.fit(X_train, Y_train)
predictions = lda.predict(X_validation)
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))
print(classification_report(Y_validation, predictions))
# predict probability of survival
y_pred_prob = lda.predict_pr... | notebooks/data_smart_project_1.ipynb | craigrshenton/home | mit |
A very simple "image" | X = np.zeros((9, 9))
X[::2, 1::2] = 1
X[1::2, ::2] = 1
plt.imshow(X, cmap=plt.cm.gray, interpolation="nearest")
camera = data.camera()
print(type(camera))
plt.imshow(camera, cmap=plt.cm.gray)
print(camera.shape)
print(camera.dtype) | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Histogram Equalization
Q: What is the histogram of an image? | print(camera.min(), camera.max())
from scipy.stats import uniform
bins = np.linspace(0, 256, 20)
hist = np.histogram(camera.ravel(), bins, normed=True)[0]
bins = 0.5*(bins[1:] + bins[:-1])
plt.plot(bins, hist, label="original")
estimate = uniform.pdf(bins)
plt.plot(bins, estimate, label="uniform estimate") | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Q: What is wrong with the figure above?
Q: What does it mean to improve the contrast of an image? | from skimage import exposure
camera_eq = exposure.equalize_hist(camera)
print(camera_eq.min(), camera_eq.max())
bins = np.linspace(0, 1, 20)
hist = np.histogram(camera_eq.ravel(), bins, normed=True)[0]
bins = 0.5*(bins[1:] + bins[:-1])
plt.plot(bins, hist, label="Original")
estimate_uni = uniform.pdf(bins)
plt.plot(b... | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Exercise: Image filtering by thresholding
Convert the background in the following image to zero-valued pixels | coins = data.coins()
plt.imshow(coins, cmap=plt.cm.gray)
plt.xticks([])
plt.yticks([])
plt.grid() | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Hint: Use histogram to pick the right threshold | # enter code here | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Q: What was the problem with this approach of thresholding?
Adaptive Thresholding | from skimage import filters
threshold = filters.threshold_otsu(coins)
coins_low = coins.copy()
coins_low[coins_low < threshold] = 0
plt.imshow(coins_low, cmap=plt.cm.gray)
plt.xticks([])
plt.yticks([])
plt.grid()
bins = np.linspace(0, 256, 50)
hist = np.histogram(coins.ravel(), bins, normed=True)[0]
bins = 0.5*(bins[1... | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Independent labeling of objects
Segmentation with boolean masks | plt.imshow(coins_low > 0, cmap=plt.cm.gray)
plt.grid() | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Filling in smaller regions | from skimage.morphology import closing, square
bw = closing(coins_low > 0, square(3))
plt.imshow(bw, cmap=plt.cm.gray)
plt.grid()
from skimage.segmentation import clear_border
from skimage.color import label2rgb
from skimage.measure import label
# remove artifacts connected to image border
cleared = clear_border(bw)
... | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Exercise: Color each independent region in the following image
Note: Image is entireyly only black and white. It has already been thresholded and binaried | n = 20
l = 256
im = np.zeros((l, l))
points = l * np.random.random((2, n ** 2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = filters.gaussian_filter(im, sigma=l / (4. * n))
blobs = im > im.mean()
plt.imshow(blobs, cmap=plt.cm.gray)
plt.xticks([])
plt.yticks([])
# enter code here | notebooks/day1/04_intro_scikit_image.ipynb | jaidevd/inmantec_fdp | mit |
Data set | # To plot the unction we use a uniform grid
X = np.arange(-1, 1, 0.05)
Y = np.arange(-1, 1, 0.05)
n_samples = len(X) * len(Y)
points = np.zeros((n_samples, 2))
i=0
for x in X:
for y in Y:
points[i][0] = x
points[i][1] = y
i=i+1
labels = (np.sin(5 * points[:,0] * (3 * points[:,1] + 1.)) + 1.... | doc/sphinx/notebooks/dCGPANNs_for_function_approximation.ipynb | darioizzo/d-CGP | gpl-3.0 |
Encoding and training a FFNN using dCGP
There are many ways the same FFNN could be encoded into a CGP chromosome. The utility encode_ffnn selects one for you returning the expression. | # We define a 2 input 1 output dCGPANN with sigmoid nonlinearities
dcgpann = dcgpy.encode_ffnn(2,1,[50,20],["sig", "sig", "sig"], 5)
std = 1.5
# Weight/biases initialization is made using a normal distribution
dcgpann.randomise_weights(mean = 0., std = std)
dcgpann.randomise_biases(mean = 0., std = std)
# We show the... | doc/sphinx/notebooks/dCGPANNs_for_function_approximation.ipynb | darioizzo/d-CGP | gpl-3.0 |
Same training is done using Keras (Tensor Flow backend) | import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras import optimizers
# We define Stochastic Gradient Descent as an optimizer
sgd = optimizers.SGD(lr=0.3)
# We define weight initializetion
initializerw = keras.initializers.RandomNormal(mean=0.0, stddev=std, seed=Non... | doc/sphinx/notebooks/dCGPANNs_for_function_approximation.ipynb | darioizzo/d-CGP | gpl-3.0 |
Repeating ten times the same comparison | epochs = 5000
for i in range(10):
# dCGP
dcgpann = dcgpy.encode_ffnn(2,1,[50,20],["sig", "sig", "sig"], 5)
dcgpann.randomise_weights(mean = 0., std = std)
dcgpann.randomise_biases(mean = 0., std = std)
res = []
for i in tqdm(range(epochs)):
lr = lr0 #* np.exp(-0.0001 * i)
loss = ... | doc/sphinx/notebooks/dCGPANNs_for_function_approximation.ipynb | darioizzo/d-CGP | gpl-3.0 |
Expected output:
test: Hello World
<font color='blue'>
What you need to remember:
- Run your cells using SHIFT+ENTER (or "Run cell")
- Write code in the designated areas using Python 3 only
- Do not modify the code outside of the designated areas
1 - Building basic functions with numpy
Numpy is the main package for sci... | # GRADED FUNCTION: basic_sigmoid
import math
def basic_sigmoid(x):
"""
Compute sigmoid of x.
Arguments:
x -- A scalar
Return:
s -- sigmoid(x)
"""
### START CODE HERE ### (≈ 1 line of code)
s = 1/(1+math.exp(-x))
### END CODE HERE ###
return s
basic_sigmoid(3) | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table style = "width:40%">
<tr>
<td>** basic_sigmoid(3) **</td>
<td>0.9525741268224334 </td>
</tr>
</table>
Actually, we rarely use the "math" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. Th... | ### One reason why we use "numpy" instead of "math" in Deep Learning ###
x = [1, 2, 3]
basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector. | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
In fact, if $ x = (x_1, x_2, ..., x_n)$ is a row vector then $np.exp(x)$ will apply the exponential function to every element of x. The output will thus be: $np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})$ | import numpy as np
# example of np.exp
x = np.array([1, 2, 3])
print(np.exp(x)) # result is (exp(1), exp(2), exp(3)) | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Furthermore, if x is a vector, then a Python operation such as $s = x + 3$ or $s = \frac{1}{x}$ will output s as a vector of the same size as x. | # example of vector operation
x = np.array([1, 2, 3])
print (x + 3) | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Any time you need more info on a numpy function, we encourage you to look at the official documentation.
You can also create a new cell in the notebook and write np.exp? (for example) to get quick access to the documentation.
Exercise: Implement the sigmoid function using numpy.
Instructions: x could now be either a ... | # GRADED FUNCTION: sigmoid
import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size
Return:
s -- sigmoid(x)
"""
### START C... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table>
<tr>
<td> **sigmoid([1,2,3])**</td>
<td> array([ 0.73105858, 0.88079708, 0.95257413]) </td>
</tr>
</table>
1.2 - Sigmoid gradient
As you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first ... | # GRADED FUNCTION: sigmoid_derivative
def sigmoid_derivative(x):
"""
Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.
You can store the output of the sigmoid function into variables and then use it to calculate the gradient.
Arguments:... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table>
<tr>
<td> **sigmoid_derivative([1,2,3])**</td>
<td> [ 0.19661193 0.10499359 0.04517666] </td>
</tr>
</table>
1.3 - Reshaping arrays
Two common numpy functions used in deep learning are np.shape and np.reshape().
- X.shape is used to get the shape (dimension) of a... | # GRADED FUNCTION: image2vector
def image2vector(image):
"""
Argument:
image -- a numpy array of shape (length, height, depth)
Returns:
v -- a vector of shape (length*height*depth, 1)
"""
### START CODE HERE ### (≈ 1 line of code)
v = image.reshape((image.shape[0]*image.shape[1... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table style="width:100%">
<tr>
<td> **image2vector(image)** </td>
<td> [[ 0.67826139]
[ 0.29380381]
[ 0.90714982]
[ 0.52835647]
[ 0.4215251 ]
[ 0.45017551]
[ 0.92814219]
[ 0.96677647]
[ 0.85304703]
[ 0.52351845]
[ 0.19981397]
[ 0.27417313]
[ 0.60659855]
[ 0.00533165]... | # GRADED FUNCTION: normalizeRows
def normalizeRows(x):
"""
Implement a function that normalizes each row of the matrix x (to have unit length).
Argument:
x -- A numpy matrix of shape (n, m)
Returns:
x -- The normalized (by row) numpy matrix. You are allowed to modify x.
"""
... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table style="width:60%">
<tr>
<td> **normalizeRows(x)** </td>
<td> [[ 0. 0.6 0.8 ]
[ 0.13736056 0.82416338 0.54944226]]</td>
</tr>
</table>
Note:
In normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment... | # GRADED FUNCTION: softmax
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (n, m).
Argument:
x -- A numpy matrix of shape (n,m)
Returns:
s -- A numpy matrix equal to the softmax of x, of shape (n,m)
... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table style="width:60%">
<tr>
<td> **softmax(x)** </td>
<td> [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04
1.21052389e-04]
[ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04
8.01252314e-04]]</td>
</tr>
</table>
Note:
- If ... | import time
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###
tic = time.process_time()
dot = 0
for i in range(len(x1)):
dot+= x1[i]*x2[i]
toc = time.process_time()
print ("dot = " + str(dot) + "\n ----- Comp... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger.
Note that np.dot() performs a matrix-matrix or matrix-vector multiplication. This is different from np.multiply() and the * operator (which is equi... | # GRADED FUNCTION: L1
def L1(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L1 loss function defined above
"""
### START CODE HERE ### (≈ 1 line of code)
loss = np.sum(np.abs(yhat-y... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Expected Output:
<table style="width:20%">
<tr>
<td> **L1** </td>
<td> 1.1 </td>
</tr>
</table>
Exercise: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if $x = [x_1, x_2,... | # GRADED FUNCTION: L2
def L2(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L2 loss function defined above
"""
### START CODE HERE ### (≈ 1 line of code)
loss = np.sum(np.dot(y-yhat... | Intro_to_Neural_Networks/Python+Basics+With+Numpy+v3.ipynb | radu941208/DeepLearning | mit |
Test environment setup
For more details on this please check out examples/utils/testenv_example.ipynb.
devlib requires the ANDROID_HOME environment variable configured to point to your local installation of the Android SDK. If you have not this variable configured in the shell used to start the notebook server, you nee... | # Setup target configuration
my_conf = {
# Target platform and board
"platform" : 'android',
"board" : 'hikey960',
# Device serial ID
# Not required if there is only one device connected to your computer
"device" : "0123456789ABCDEF",
# Android home
# Not requ... | ipynb/examples/android/workloads/Android_Viewer.ipynb | bjackman/lisa | apache-2.0 |
Workload definition
The Viewer workload will simply read an URI and let Android pick the best application to view the item designated by that URI. That item could be a web page, a photo, a pdf, etc. For instance, if given an URL to a Google Maps location, the Google Maps application will be opened at that location. If ... | class GmapsViewer(ViewerWorkload):
def pre_interact(self):
self.script = TargetScript(te, "gmaps_swiper.sh")
# Define commands to execute during experiment
for i in range(2):
System.hswipe(self.script, 40, 60, 100, False)
self.script.append('sleep 1')
... | ipynb/examples/android/workloads/Android_Viewer.ipynb | bjackman/lisa | apache-2.0 |
Workload execution | results = experiment()
# Load traces in memory (can take several minutes)
platform_file = os.path.join(te.res_dir, 'platform.json')
with open(platform_file, 'r') as fh:
platform = json.load(fh)
trace_file = os.path.join(te.res_dir, 'trace.dat')
trace = Trace(platform, trace_file, events=my_conf['ftrace']['events... | ipynb/examples/android/workloads/Android_Viewer.ipynb | bjackman/lisa | apache-2.0 |
Traces visualisation | !kernelshark {trace_file} 2>/dev/null | ipynb/examples/android/workloads/Android_Viewer.ipynb | bjackman/lisa | apache-2.0 |
The Data
For this exercise (and the next one) will will be using the classic MNIST dataset. Like the digits data you had used earlier, these are pictures of numbers. The big difference is the pictures are bigger (28x28 pixels rather than 8x8) and we will be looking at a much larger data set: 60,000 training images and ... | # Load Mnist data
# the data, split between train and test sets
num_classes = 10 # we have 10 digits to classify
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_tra... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Building the model
We're now ready to build our first neural network model. We'll begin with the easiest model imaginable given the data. A network where eeach one of the 784 pixels in the input data is connected to each of the 10 output classes.
This network essentially just has a single layer (it is both the first a... | model = Sequential() | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
The variable model will contain all the information on the model, and as we add layers and perform calculations, it will all be stored insidle this variable.
Step II: Adding a (input) layer
In general adding a layer to a mode is achieved by the model.add(layer_definition) command. Where the layer_definition is specific... | model.add(Dense(num_classes, activation='softmax', input_shape=(784,)))
| bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Note the input_shape=(784,) here. 784 is the size of out input images. The (784,) means we can have an unspecified number of input images coming into the network.
Normally, we would keep adding more layers (see examples later). But in this case we only have one layer. So we can see what our model looks like by invoking... | model.summary() | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Whenever you build a model be sure to look at the summary. The number of trainable parameters gives you a sense of model complexity. Models with fewer parameters are likely to be easier to train, and likely to generalize better for the same performance.
Step III: Compile the model
This step describes how keras will upd... | model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy']) | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Step IV: Train the model
We're now ready to perform the training. A couple more decisions need to be made:
1. How long to train: This is measured in "epochs", each epoch representing the whole training data going through the algorithm. You want to give the optimizer long enough so it can get to a good solution, but you... | batch_size = 128
epochs = 20
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1)
| bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Step V: Test the model
The real test of a model is how well it does on the training data (a severly overfit model could get 100% accuracy on training data, but fail miserably on new data). So the real score we care about is the performance on un-seen data. We do this by evaluating performance on the test data we held o... | score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
fig = plt.figure()
trainCurve=plt.plot(history.history['acc'],label='Training')
testCurve=plt.axhline(y=score[1],color='k',label='Testing')
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('ep... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Interpreting the results
Since we used an incredibly simple network, it is easy to look under the covers and see what is going on. For each class (i.e. digit=1 to 9) this simple network essentially has a filter-matrix the same size as the image, which it "multiplies" an input image against. The digit for which the filt... | denseLayer=model.layers[0]
weights=denseLayer.get_weights()
topWeights=weights[0]
fig = plt.figure(figsize=(15, 15))
meanTop=np.mean(topWeights,axis=1)
for num in range(topWeights.shape[1]):
mat=topWeights[:,num]-meanTop
mat=(mat.reshape(28,28))
ax = fig.add_subplot(3,4,num+1)
plt.imshow(mat,cmap=plt.cm... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Questions:
Compare the results of these weights to the mean digit images at the beginning of this notebook:
1. Can you explain the form of these curves? Why does the first one have a white spot (low value) at the center while the second has a high value there?
2. What do you think the limitations of this approach are? ... |
# Model initialization unchanged
model = Sequential()
# Input layer is similar, but because it doesn't connect to the final layer we are free
# to choose number of outputs (here 512) and we use 'relu' activation instead of softmax. It also
model.add(Dense(512, activation='relu', input_shape=(784,)))
# New intermediat... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Note the dramatic increase in the number of parameters achieved with this network. When you train this network, you'll see that this increase in number of parameters really slows things down, but leads to an increase in performance: | batch_size = 128
epochs = 20
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
fig = plt.figure()
trainCurve... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
Questions:
What do you think about the agreement between the training and testing curves?
Do you think there is a qualitative difference in what this classifier picks up?
We can get some clues by looking at the input layer as before. Although now there are 512 instead of 10 filters. So we just look at the first 10. | denseLayer=model.layers[0]
weights=denseLayer.get_weights()
topWeights=weights[0]
fig = plt.figure(figsize=(15, 15))
meanTop=np.mean(topWeights,axis=1)
for num in range(10):
mat=topWeights[:,num]-meanTop
mat=(mat.reshape(28,28))
ax = fig.add_subplot(3,4,num+1)
plt.imshow(mat,cmap=plt.cm.binary)
plt.show... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
What is the quaitative difference between these plots and
Overfitting
As you can see with the increase in the number of parameters, there is an increase in the mismatch between training and testing, raising the concern that the model is overfitting on the training data. There are a couple of approaches to combat this.... | model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
# NEW dropout layer dropping 20% of inputs
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
# NEW dropout layer dropping 20% of inputs
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
# Compila... | bicf_nanocourses/courses/ML_1/exercises/Keras_Tutorial.ipynb | bcantarel/bcantarel.github.io | gpl-3.0 |
TF-Keras Text Classification Distributed Single Worker GPUs using Vertex Training with Local Mode Container
<table align="left">
<td>
<a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_an... | PROJECT_ID = "YOUR PROJECT ID"
BUCKET_NAME = "gs://YOUR BUCKET NAME"
REGION = "YOUR REGION"
SERVICE_ACCOUNT = "YOUR SERVICE ACCOUNT"
content_name = "tf-keras-txt-cls-dist-single-worker-gpus-local-mode-cont" | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Local Training with Vertex Local Mode and Auto Packaging | BASE_IMAGE_URI = "us-docker.pkg.dev/vertex-ai/training/tf-gpu.2-5:latest"
SCRIPT_PATH = "trainer/task.py"
OUTPUT_IMAGE_NAME = "gcr.io/{}/{}:latest".format(PROJECT_ID, content_name)
ARGS = "--epochs 5 --batch-size 16 --local-mode"
! gcloud ai custom-jobs local-run \
--executor-image-uri=$BASE_IMAGE_URI \
--script=$... | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Vertex Training using Vertex SDK and Vertex Local Mode Container
Container Built by Vertex Local Mode | custom_container_image_uri = OUTPUT_IMAGE_NAME
! docker push $custom_container_image_uri
! gcloud container images list --repository "gcr.io"/$PROJECT_ID | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Initialize Vertex SDK | ! pip install -r requirements.txt
from google.cloud import aiplatform
aiplatform.init(
project=PROJECT_ID,
staging_bucket=BUCKET_NAME,
location=REGION,
) | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Create a Vertex Tensorboard Instance | tensorboard = aiplatform.Tensorboard.create(
display_name=content_name,
) | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Option: Use a Previously Created Vertex Tensorboard Instance
tensorboard_name = "Your Tensorboard Resource Name or Tensorboard ID"
tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)
Run a Vertex SDK CustomContainerTrainingJob | display_name = content_name
gcs_output_uri_prefix = f"{BUCKET_NAME}/{display_name}"
machine_type = "n1-standard-8"
accelerator_count = 4
accelerator_type = "NVIDIA_TESLA_P100"
args = [
"--epochs",
"100",
"--batch-size",
"128",
"--num-gpus",
f"{accelerator_count}",
]
custom_container_training_... | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Training Output Artifact | ! gsutil ls $gcs_output_uri_prefix | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Clean Up Artifact | ! gsutil rm -rf $gcs_output_uri_prefix | community-content/tf_keras_text_classification_distributed_single_worker_gpus_with_gcloud_local_run_and_vertex_sdk/vertex_training_with_local_mode_container.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Hyperparameter optimization
This notebook was made with the following version of george: | import george
george.__version__ | docs/_static/notebooks/hyper.ipynb | dfm/george | mit |
In this tutorial, we’ll reproduce the analysis for Figure 5.6 in Chapter 5 of Rasmussen & Williams (R&W). The data are measurements of the atmospheric CO2 concentration made at Mauna Loa, Hawaii (Keeling & Whorf 2004). The dataset is said to be available online but I couldn’t seem to download it from the original sourc... | import numpy as np
import matplotlib.pyplot as pl
from statsmodels.datasets import co2
data = co2.load_pandas().data
t = 2000 + (np.array(data.index.to_julian_date()) - 2451545.0) / 365.25
y = np.array(data.co2)
m = np.isfinite(t) & np.isfinite(y) & (t < 1996)
t, y = t[m][::4], y[m][::4]
pl.plot(t, y, ".k")
pl.xlim(t... | docs/_static/notebooks/hyper.ipynb | dfm/george | mit |
In this figure, you can see that there is periodic (or quasi-periodic) signal with a year-long period superimposed on a long term trend. We will follow R&W and model these effects non-parametrically using a complicated covariance function. The covariance function that we’ll use is:
$$k(r) = k_1(r) + k_2(r) + k_3(r) + k... | from george import kernels
k1 = 66**2 * kernels.ExpSquaredKernel(metric=67**2)
k2 = 2.4**2 * kernels.ExpSquaredKernel(90**2) * kernels.ExpSine2Kernel(gamma=2/1.3**2, log_period=0.0)
k3 = 0.66**2 * kernels.RationalQuadraticKernel(log_alpha=np.log(0.78), metric=1.2**2)
k4 = 0.18**2 * kernels.ExpSquaredKernel(1.6**2)
ker... | docs/_static/notebooks/hyper.ipynb | dfm/george | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.