markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We can also compute the characteristic function of the velocity distribution: | char_move = fft(move)
plt.plot(xs, abs(char_move)); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
You might notice that the narrower (more certain) the distribution is in the space domain, the wider (less certain) it is in the frequency domain. As it turns out, the product of the two standard deviations is constant.
We can see that more clearly by plotting the distribution side-by-side in the space and frequency d... | def plot_dist_and_char(dist):
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(7, 4))
ax1.plot(xs, dist)
ax1.set_xlabel('space domain')
char = fft(dist)
ax2.plot(xs, np.roll(abs(char), 180))
ax2.set_xlabel('frequency domain') | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
The following function plots Gaussian distributions with given parameters. | def plot_gaussian_dist_and_char(mu=180, sigma=3):
dist = gaussian(xs, mu, sigma)
plot_dist_and_char(dist) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Here's a simple example: | plot_gaussian_dist_and_char(mu=180, sigma=3) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Now we can make sliders to control mu and sigma. | from IPython.html.widgets import interact, fixed
from IPython.html import widgets
slider1 = widgets.IntSliderWidget(min=0, max=360, value=180)
slider2 = widgets.FloatSliderWidget(min=0, max=100, value=3)
interact(plot_gaussian_dist_and_char, mu=slider1, sigma=slider2); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
As you increase sigma, the distribution gets wider in the space domain and narrower in the frequency domain.
As you vary mu, the location changes in the space domain, and the phase changes in the frequency domain, but the magnitudes are unchanged.
But enough of that; I still haven't explained why characteristic functio... | char_new_pos = char_pos * char_move
plt.plot(xs, abs(char_new_pos)); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
If we compute the inverse FFT of the characteristic function, we get the PMF of the new position: | from numpy.fft import ifft
new_pos = ifft(char_new_pos).real
plt.plot(xs, new_pos); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
We can check the mean and standard deviation of the result: | def mean_std_dist(xs, dist):
xbar = mean_dist(xs, dist)
s = std_dist(xs, dist, xbar)
return xbar, s | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Yup, that's what we expected (forgiving some floating-point errors): | mean_std_dist(xs, new_pos) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
We can encapsulate this process in a function that computes the convolution of two distributions: | def fft_convolve(dist1, dist2):
prod = fft(dist1) * fft(dist2)
dist = ifft(prod).real
return dist | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Since FFT is $N \log N$, and elementwise multiplication is linear, the whole function is $N \log N$, which is better than the $N^2$ algorithm we started with.
The results from the function are the same: | new_pos = fft_convolve(pos, move)
mean_std_dist(xs, new_pos) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
The update step
Now suppose that after the move we measure the position of the rotating part with a noisy instrument. If the measurement is 197 and the standard deviation of measurement error is 4, the following distribution shows the likelihood of the observed measurement for each possible, actual, position of the pa... | likelihood = gaussian(xs, mu=197, sigma=4)
plt.plot(xs, new_pos); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Now we can take our belief about the position of the part and update it using the observed measurement. By Bayes's theorem, we compute the product of the prior distribution and the likelihood, then renormalize to get the posterior distribution: | new_pos = new_pos * likelihood
normalize(new_pos)
plt.plot(xs, new_pos); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
The prior mean was 195 and the measurement was 197, so the posterior mean is in between, at 196.2 (closer to the measurement because the measurement error is 4 and the standard deviation of the prior is 5).
The posterior standard deviation is 3.1, so the measurement decreased our uncertainty about the location. | mean_std_dist(xs, new_pos) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
We can encapsulate the prediction step in a function: | def predict(xs, pos, move):
new_pos = fft_convolve(pos, move)
return new_pos | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
And likewise the update function: | def update(xs, pos, likelihood):
new_pos = pos * likelihood
normalize(new_pos)
return new_pos | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
The following function takes a prior distribution, velocity, and a measurement, and performs one predict-update step.
(The uncertainty of the velocity and measurement are hard-coded in this function, but could be parameters.) | def predict_update(xs, pos1, velocity, measure):
# predict
move = gaussian(xs, velocity, 3)
pos2 = predict(xs, pos1, move)
#update
likelihood = gaussian(xs, measure, 4)
pos3 = update(xs, pos2, likelihood)
#plot
plt.plot(xs, pos1, label='pos1')
plt.plot(xs, pos2, label='pos2... | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
In the figure below, pos1 is the initial belief about the position, pos2 is the belief after the predict step, and pos3 is the posterior belief after the measurement.
The taller the distribution, the narrower it is, indicating more certainty about position. In general, the predict step makes us less certain, and the u... | pos1 = gaussian(xs, 180, 4)
pos3 = predict_update(xs, pos1, velocity=15, measure=197) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
So far I've been using Gaussian distributions for everything, but in that case we could skip all the computation and get the results analytically.
The implementation I showed generalizes to arbitrary distribitions. For example, suppose our initial beliefs are multimodal, for example, if we can't tell whether the part ... | pos1 = (gaussian(xs, 0, 4) + gaussian(xs, 90, 4) +
gaussian(xs, 180, 4) + gaussian(xs, 270, 4))
normalize(pos1)
plt.plot(xs, pos1); | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Now we can do the same predict-update step: | pos3 = predict_update(xs, pos1, velocity=15, measure=151) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
After the predict step, our belief is still multimodal.
Then I chose a measurement, 151, that's halfway between two modes. The result is bimodal (with the other two modes practically eliminated).
If we perform one more step: | pos5 = predict_update(xs, pos3, velocity=15, measure=185) | convolution.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Loading the data | def loadMovieLens(path='./data/movielens'):
#Get movie titles
movies={}
rev_movies={}
for idx,line in enumerate(open(path+'/u.item')):
idx,title=line.split('|')[0:2]
movies[idx]=title
rev_movies[title]=idx
# Load data
prefs={}
for line in open(path+'/u.data'):
... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Splitting data between train/test
We avoid to let unseen data form the train set in the test set.
We also try to minimise the dataset reduction by splitting on each user. | def getRawArray(data):
d = []
for u in data.keys():
for i in data[u].keys():
d.append([u,i,data[u][i]])
return np.array(d)
# splitting while avoiding to reduce the dataset too much
def split_train_test(data,percent_test):
test={}
train={}
movie={}
for u in data.keys():
... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
split used for convenience on the average by movie baseline | percent_test = 0.2
train,test = split_train_test(data,percent_test)
m_train,m_test = split_train_test_by_movies(data,percent_test) | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
cleaning
18 movies have no ratings at all | def deleteUnseenInTest(train,test):
for k in test.keys():
try:
train[k]
except KeyError:
test.pop(k,None)
def deleteUnknowData(triplet_test, trainUsers, trainItems) :
to_Del = []
for i,t in enumerate(triplet_test):
if not t[0] in trainUsers:
to_De... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Matrix used for fast evaluation | def getRawArray(data):
rawArray = []
for u in data.keys():
for i in data[u].keys():
rawArray.append([u,i,data[u][i]])
return rawArray
def getDataByUsers(rawArray) :
usr = {}
for t in rawArray:
if not t[0] in usr.keys():
usr[t[0]] = {}
usr[t[0]][t[1]] ... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Content example | arrayTest[:10,:10] | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Baseline: mean by user | class baselineMeanUser:
def __init__(self):
self.users={}
def fit(self,train):
for user in train.keys():
note=0.0
for movie in train[user].keys():
note+=train[user][movie]
note=note/len(train[user])
self.users[user]=note
... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Raw matrix are used for convenience and clarity.
Structure like scipy sparse matrix or python dictionnaries may be used for speedup.
Complete dataset | rawMatrix = np.zeros((943,1682))
for u in data:
for m in data[u]:
rawMatrix[int(u)-1][int(movies[m])-1] = data[u][m]
print(np.shape(rawMatrix))
rawMatrix[:5,:5] | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Train and test dataset | rawMatrixTrain = np.zeros((len(data.keys()),1682))
for u in train:
for m in train[u]:
rawMatrixTrain[int(u)-1][int(movies[m])-1] = train[u][m]
rawMatrixTest = np.zeros((len(data.keys()),1682))
for u in test:
for m in test[u]:
rawMatrixTest[int(u)-1][int(movies[m])-1] = test[u][m] | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Non-negative Matrix Factorization
Fast implementation using numpy's matrix processing. | def nmf(X, latent_features, max_iter=100, eps = 1e-5,printevery=100):
print "NMF with %d latent features, %d iterations."%(latent_features, max_iter)
# mask used to ignore null element (coded by zero)
mask = np.sign(X)
# randomly initialized matrix
rows, columns = X.shape
A = np.random.rand(r... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
We see that it quickly get better than the baseline.
However, we see below that it overfit after that: | %%time
A,Y = nmf(rawMatrixTrain,50,eps = 1e-5,max_iter=500,printevery=100)
resMatrix = A.dot(Y) | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
This is due to the high sparsity of the matrix.
We can of course reduce the features matrix size to avoid overfitting, but that will limit further improvments: | %%time
A,Y = nmf(rawMatrixTrain,1,eps = 1e-5,max_iter=100,printevery=20)
resMatrix = A.dot(Y) | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Despite good results in few seconds on this dataset, this can only get us so far.
We then have to add regularization to the cost function.
Evaluation | ## This class is used to make predictions
class evalMF:
def __init__(self,resMatrix,dicU,dicI):
self.resMatrix=resMatrix
self.dicU = dicU
self.dicI = dicI
def fit(self):
pass
def predict(self,user,movie):
return self.resMatrix[int(user)-1][int(self.dicI[movie... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Let's look at some predictions | print data["1"]["Akira (1988)"]
print mf.predict("1","Akira (1988)")
print data["1"]["I.Q. (1994)"]
print mf.predict("1","I.Q. (1994)") | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
We usualy see an important difference between users, so we need to take the bias into account. | user="1"
summ=0
for i in data[user]:
summ+=(float(data[user][i]) - mf.predict(user,i))**2
summ/len(data[user])
user="3"
summ=0
for i in data[user]:
summ+=(float(data[user][i]) - mf.predict(user,i))**2
summ/len(data[user]) | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
We have not been very successful with incorporating the bias and L1 into that implementation...
We build a simpler model below, and then add the regularization and bias. | class mf():
def __init__(self, k, eps=1e-3, nIter=2000, lambd=0.5):
self.k = k
self.lambd = lambd
self.eps = eps
self.nIter = nIter
def fit(self, trainUsers, trainItems, rawArray):
print "MF with %d latent features, %d iterations."%(self.k, self.nIter)
printever... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
thanks to Professeur Chen | class tSNE():
def __init__(self,perp, nIter, lr, moment, dim=2):
self.perp = perp # entre 5 et 50
self.nIter = nIter
self.lr = lr
self.moment = moment
self.dim = dim
def fit(self,data):
nEx = np.shape(data)[0]
# Matrice des distances de ||xi - xj||² #
... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
For reference, let's compare it with sklearn's TSNE | from sklearn.manifold import TSNE
mod = TSNE(random_state=1337)
%%time
X = mod.fit_transform(X_ini)
palette = np.array(sns.color_palette("hls", 10))
# We create a scatter plot.
f = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
sc = ax.scatter(X[:,0], X[:,1], lw=0, s=40,
c=palette[cols.... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
It produce similar results, albeit faster, as expected. | rawMatrix = np.zeros((943,1682))
for u in data:
for m in data[u]:
rawMatrix[int(u)-1][int(movies[m])-1] = data[u][m] | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Predict unknown data and fill the others with the right number | %%time
rawMatrix = np.zeros((943,1682))
for u in data:
for m in movies.keys():
try:
rawMatrix[int(u)-1][int(movies[m])-1] = model.predict([[u,m]])
except KeyError:
rawMatrix[int(u)-1][int(movies[m])-1] = 3
for u in data:
for m in data[u]:
rawMatrix[int(u)-1][int(m... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
0.0164939277392222 percent of unseen data | model.predict([["1","101 Dalmatians (1996)"]])
rawMatrix = np.zeros((943,1682))
for u in data:
for m in data[u]:
rawMatrix[int(u)-1][int(movies[m])-1] = data[u][m]
mod = TSNE(random_state=1337)
%%time
X = mod.fit_transform(rawMatrix) | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Produced visualisation | palette = np.array(sns.color_palette("hls", 4))
f = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
sc = ax.scatter(X[:,0], X[:,1], lw=0, s=40)
plt.xlim(-25, 25)
plt.ylim(-25, 25)
ax.axis('off')
ax.axis('tight')
plt.show() | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
But its not very informative...
Let's add some colors by ratings | me = rawMatrix.mean(1)
X_ini = np.vstack([rawMatrix[np.where(np.logical_and(me>i, me<=j))]
for i,j in [(0,2),(2,3),(3,4),(4,5)]])
cols = np.hstack( [ np.round( me[ np.where(np.logical_and(me>i, me<=j)) ] )
for i,j in [(0,2),(2,3),(3,4),(4,5)] ] )
%%time
X = mod.fit_transform(X_ini)
pale... | FDMS/TME5/TME4_5_FiltrageCollaboratif_tsne.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
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 --... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected output:
<table style="width:80%">
<tr>
<td> **W1** </td>
<td> [[ 0.01624345 -0.00611756]
[-0.00528172 -0.01072969]] </td>
</tr>
<tr>
<td> **b1**</td>
<td>[[ 0.]
[ 0.]]</td>
</tr>
<tr>
<td>**W2**</td>
<td> [[ 0.00865408 -0.02301539]]</td>
</tr>
<tr>
<td> **b2** <... | # 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":
... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected output:
<table style="width:35%">
<tr>
<td> **Z** </td>
<td> [[ 3.1980455 7.85763489]] </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... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected output:
<table style="width:35%">
<tr>
<td> **With sigmoid: A ** </td>
<td > [[ 0.96076066 0.99961336]]</td>
</tr>
<tr>
<td> **With ReLU: A ** </td>
<td > [[ 3.1980455 7.85763489]]</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()
... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
<table style="width:40%">
<tr>
<td> **AL** </td>
<td > [[ 0.0844367 0.92356858]]</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... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
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 ... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected Output:
<table style="width:90%">
<tr>
<td> **dA_prev** </td>
<td > [[ 2.38272385 5.85438014]
[ 6.31969219 15.52755701]
[ -3.97876302 -9.77586689]] </td>
</tr>
<tr>
<td> **dW** </td>
<td > [[ 2.77870358 -0.05500058 -5.13144969]] </td>
</tr>
<tr>
<t... | # 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)... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected output with sigmoid:
<table style="width:100%">
<tr>
<td > dA_prev </td>
<td >[[ 0.08982777 0.00226265]
[ 0.23824996 0.00600122]
[-0.14999783 -0.00377826]] </td>
</tr>
<tr>
<td > dW </td>
<td > [[-0.06001514 -0.09687383 -0.10598695]] </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... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
Expected Output
<table style="width:60%">
<tr>
<td > dW1 </td>
<td > [[-0.09686122 -0.04840482 -0.11864308]] </td>
</tr>
<tr>
<td > db1 </td>
<td > -0.262594998379 </td>
</tr>
<tr>
<td > dA1 </td>
<td > [[-0.71011462 -0.22925516]
[-0.17330152 -0.05594909... | # 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
... | Neural Networks And Deep Learning/Deep Neural Network - Application.ipynb | anukarsh1/deep-learning-coursera | mit |
For alpha-shaped currents we have: | A = sp.Matrix([[-1/tau_s,0,0],[1,-1/tau_s,0],[0,1/C,-1/tau_m]]) | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Non-singular case ($\tau_m\neq \tau_s$)
The propagator is: | PA = sp.simplify(sp.exp(A*h))
PA | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Note that the entry in the third line and the second column $A_{32}$ would also appear in the propagator matrix in case of an exponentially shaped current
Singular case ($\tau_m = \tau_s$)
We have | As = sp.Matrix([[-1/tau_m,0,0],[1,-1/tau_m,0],[0,1/C,-1/tau_m]])
As | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
The propagator is | PAs = sp.simplify(sp.exp(As*h))
PAs | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Numeric stability of propagator elements
For the lines $\tau_s\rightarrow\tau_m$ the entry $PA_{32}$ becomes numerically unstable, since denominator and enumerator go to zero.
$1.$ We show that $PAs_{32}$ is the limit of $PA_{32}(\tau_s)$ for $\tau_s\rightarrow\tau_m$.: | PA_32 = PA.row(2).col(1)[0]
sp.limit(PA_32, tau_s, tau_m) | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
$2.$ The Taylor-series up to the second order of the function $PA_{32}(\tau_s)$ is: | PA_32_series = PA_32.series(x=tau_s,x0=tau_m,n=2)
PA_32_series | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Therefore we have
$T(PA_{32}(\tau_s,\tau_m))=PAs_{32}+PA_{32}^{lin}+O(2)$ where $PA_{32}^{lin}=h^2(-\tau_m + \tau_s)*exp(-h/\tau_m)/(2C\tau_m^2)$
$3.$ We define
$dev:=|PA_{32}-PAs_{32}|$
We also define $PA_{32}^{real}$ which is the correct value of P32 without misscalculation (instability).
In the following we assume ... | import nest
import numpy as np
import pylab as pl | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Neuron, simulation and plotting parameters | taum = 10.
C_m = 250.
# array of distances between tau_m and tau_ex
epsilon_array = np.hstack(([0.],10.**(np.arange(-6.,1.,1.))))[::-1]
dt = 0.1
fig = pl.figure(1)
NUM_COLORS = len(epsilon_array)
cmap = pl.get_cmap('gist_ncar')
maxVs = [] | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Loop through epsilon array | for i,epsilon in enumerate(epsilon_array):
nest.ResetKernel() # reset simulation kernel
nest.SetKernelStatus({'resolution':dt})
# Current based alpha neuron
neuron = nest.Create('iaf_psc_alpha')
nest.SetStatus(neuron,{'C_m':C_m,'tau_m':taum,'t_ref':0.,'V_reset':-70.,'V_th':1e32,
... | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Show maximum values of voltage traces | fig = pl.figure(2)
pl.semilogx(epsilon_array,maxVs,color='red',label='maxV')
#show singular solution as horizontal line
pl.semilogx(epsilon_array,np.ones(len(epsilon_array))*maxVs[-1],color='black',label='singular')
pl.xlabel('epsilon')
pl.ylabel('max(voltage V) (mV)')
pl.legend()
pl.show() | doc/model_details/IAF_neurons_singularity.ipynb | alberto-antonietti/nest-simulator | gpl-2.0 |
Let's check if those points are within the polygon | # Check if p1 is within the polygon using the within function
p1_within = p1.within(poly)
# Check if p2 is within the polygon
p2_within = p2.within(poly)
# Print the results
print("Is p1 within the polygon?: ", p1_within)
print("Is p2 within the polygon?: ", p2_within) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Okey, so we can see that the first point seems to be inside that polygon and the other one doesn't.
In fact, the first point is close to the center of the polygon as we can see: | print(p1)
print(poly.centroid) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
It is also possible to do PIP other way around, i.e. to check if polygon contains a point: | # Does polygon contain point 1
print("Does polygon contain p1?: ", poly.contains(p1))
# What about the other point?
print("Does polygon contain p2?: ", poly.contains(p2)) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Thus, both ways has the same results.
Which one should you use then? Well, it depends:
if you have many points and just one polygon and you try to find out which one of them is inside the polygon:
you need to iterate over the points and check one at a time if it is within() the polygon specified
if you have man... | from shapely.geometry import LineString, MultiLineString
# Create two lines
line_a = LineString([(0, 0), (1, 1)])
line_b = LineString([(1, 1), (0, 2)]) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Let's see if they intersect | line_a.intersects(line_b) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Do they also touch each other? | line_a.touches(line_b) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Indeed, they do and we can see this by plotting the features together | # Create a MultiLineString
multi_line = MultiLineString([line_a, line_b])
multi_line | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Thus, the line_b continues from the same node ( (1,1) ) where line_a ends.
However, if the lines overlap fully, they don't touch, as we can see: | # Check if line_a touches itself
print("Touches?: ", line_a.touches(line_a))
# However, it does intersect
print("Intersects?: ", line_a.intersects(line_a)) | source/codes/Lesson3-point-in-polygon.ipynb | Automating-GIS-processes/2017 | mit |
Load in the stopwords file. These are common words which we wish to exclude when performing comparisons (a, an, the, etc). Every word is separated by a new line. | stopWordsFile = "en.txt"
with open(stopWordsFile) as f:
stoplist = [x.strip('\n') for x in f.readlines()] | doc/Jaccard Index matching example.ipynb | bkuczenski/lca-tools-datafiles | gpl-3.0 |
Load in the data from the catalog | # http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
# need this to deal with unicode errors
def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.iteritems()}
elif isinsta... | doc/Jaccard Index matching example.ipynb | bkuczenski/lca-tools-datafiles | gpl-3.0 |
.. _tut_artifacts_reject:
Rejecting bad data (channels and segments) | import numpy as np
import mne
from mne.datasets import sample
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = mne.io.read_raw_fif(raw_fname) | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
.. _marking_bad_channels:
Marking bad channels
Sometimes some MEG or EEG channels are not functioning properly
for various reasons. These channels should be excluded from
analysis by marking them bad as. This is done by setting the 'bads'
in the measurement info of a data container object (e.g. Raw, Epochs,
Evoked). Th... | raw.info['bads'] = ['MEG 2443'] | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Why setting a channel bad?: If a channel does not show
a signal at all (flat) it is important to exclude it from the
analysis. If a channel as a noise level significantly higher than the
other channels it should be marked as bad. Presence of bad channels
can have terribe consequences on down stream analysis. For a flat... | # Reading data with a bad channel marked as bad:
fname = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname, condition='Left Auditory',
baseline=(None, 0))
# restrict the evoked to EEG and MEG channels
evoked.pick_types(meg=True, eeg=True, exclude=[])
# plot with... | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Let's now interpolate the bad channels (displayed in red above) | evoked.interpolate_bads(reset_bads=False) | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Let's plot the cleaned data | evoked.plot(exclude=[]) | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
.. note::
Interpolation is a linear operation that can be performed also on
Raw and Epochs objects.
For more details on interpolation see the page :ref:channel_interpolation.
.. _marking_bad_segments:
Marking bad raw segments with annotations
MNE provides an :class:mne.Annotations class that can be used to mark... | eog_events = mne.preprocessing.find_eog_events(raw)
n_blinks = len(eog_events)
# Center to cover the whole blink with full duration of 0.5s:
onset = eog_events[:, 0] / raw.info['sfreq'] - 0.25
duration = np.repeat(0.5, n_blinks)
raw.annotations = mne.Annotations(onset, duration, ['bad blink'] * n_blinks)
raw.plot(event... | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
As the data is epoched, all the epochs overlapping with segments whose
description starts with 'bad' are rejected by default. To turn rejection off,
use keyword argument reject_by_annotation=False when constructing
:class:mne.Epochs. When working with neuromag data, the first_samp
offset of raw acquisition is also take... | reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
.. note::
The rejection values can be highly data dependent. You should be careful
when adjusting these values. Make sure not too many epochs are rejected
and look into the cause of the rejections. Maybe it's just a matter
of marking a single channel as bad and you'll be able to save a lot
of data.
We th... | events = mne.find_events(raw, stim_channel='STI 014')
event_id = {"auditory/left": 1}
tmin = -0.2 # start of each epoch (200ms before the trigger)
tmax = 0.5 # end of each epoch (500ms after the trigger)
baseline = (None, 0) # means from the first instant to t = 0
picks_meg = mne.pick_types(raw.info, meg=True, eeg=F... | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
We then drop/reject the bad epochs | epochs.drop_bad() | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
And plot the so-called drop log that details the reason for which some
epochs have been dropped. | print(epochs.drop_log[40:45]) # only a subset
epochs.plot_drop_log() | 0.12/_downloads/plot_artifacts_correction_rejection.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Data | url = "https://raw.githubusercontent.com/fehiepsi/rethinking-numpyro/master/data/UCBadmit.csv"
UCBadmit = pd.read_csv(url, sep=";")
d = UCBadmit
display(d)
print(d.to_latex(index=False))
dat_list = dict(
admit=d.admit.values,
applications=d.applications.values,
gid=(d["applicant.gender"] != "male").astype... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Model 1 | dat_list = dict(
admit=d.admit.values,
applications=d.applications.values,
gid=(d["applicant.gender"] != "male").astype(int).values,
)
def model(gid, applications, admit=None):
a = numpyro.sample("a", dist.Normal(0, 1.5).expand([2]))
logit_p = a[gid]
numpyro.sample("admit", dist.Binomial(appli... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Posterior predictive check | def ppc(mcmc_run, model_args):
post = mcmc_run.get_samples()
pred = Predictive(mcmc_run.sampler.model, post)(random.PRNGKey(2), **model_args)
admit_pred = pred["admit"]
admit_rate = admit_pred / d.applications.values
plt.errorbar(
range(1, 13),
jnp.mean(admit_rate, 0),
jnp.st... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Model 2 (departmental-specific offset) | dat_list["dept_id"] = jnp.repeat(jnp.arange(6), 2)
def model(gid, dept_id, applications, admit=None):
a = numpyro.sample("a", dist.Normal(0, 1.5).expand([2]))
delta = numpyro.sample("delta", dist.Normal(0, 1.5).expand([6]))
logit_p = a[gid] + delta[dept_id]
numpyro.sample("admit", dist.Binomial(applic... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Poisson regression
We now show we can emulate binomial regresison using 2 poisson regressions,
following sec 11.3.3 of rethinking. We use a simplified model that just predicts outcomes, and has no features (just an offset term). | # binomial model of overall admission probability
def model(applications, admit):
a = numpyro.sample("a", dist.Normal(0, 1.5))
logit_p = a
numpyro.sample("admit", dist.Binomial(applications, logits=logit_p), obs=admit)
"""
m_binom = AutoLaplaceApproximation(model)
svi = SVI(
model,
m_binom,
op... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Beta-binomial regression
Sec 12.1.1 of rethinking.
Code from snippet 12.2 of Du Phan's site | d = UCBadmit
d["gid"] = (d["applicant.gender"] != "male").astype(int)
dat = dict(A=d.admit.values, N=d.applications.values, gid=d.gid.values)
def model(gid, N, A=None):
a = numpyro.sample("a", dist.Normal(0, 1.5).expand([2]))
phi = numpyro.sample("phi", dist.Exponential(1))
theta = numpyro.deterministic("... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Mixed effects model with joint prior
This code is from https://numpyro.readthedocs.io/en/latest/examples/ucbadmit.html. | from numpyro.examples.datasets import UCBADMIT, load_dataset
def glmm(dept, male, applications, admit=None):
v_mu = numpyro.sample("v_mu", dist.Normal(0, jnp.array([4.0, 1.0])))
sigma = numpyro.sample("sigma", dist.HalfNormal(jnp.ones(2)))
L_Rho = numpyro.sample("L_Rho", dist.LKJCholesky(2, concentration... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
PGMs | # p344
dag = CausalGraphicalModel(nodes=["G", "D", "A"], edges=[("G", "D"), ("G", "A"), ("D", "A")])
out = dag.draw()
display(out)
out.render(filename="admissions_dag", format="pdf")
# p345
dag = CausalGraphicalModel(nodes=["G", "D", "A"], edges=[("G", "D"), ("G", "A"), ("D", "A")], latent_edges=[("D", "A")])
out = da... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Causal inference with the latent DAG
This is based on sec 6.3 (collider bias) of the Rethinking book.
Code is from Du Phan, code snippet 6.25. We change the names to match our current example: P (parents) -> D (department), C (child) -> A (admit).
Linear regression version | N = 200 # number of samples
b_GP = 1 # direct effect of G on P
b_GC = 0 # direct effect of G on C
b_PC = 1 # direct effect of P on C
b_U = 2 # direct effect of U on P and C
with numpyro.handlers.seed(rng_seed=1):
U = 2 * numpyro.sample("U", dist.Bernoulli(0.5).expand([N])) - 1
G = numpyro.sample("G", dist... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Logistic regression version
We modify the scenario to match the UC Berkeley admissions scenario (with binary data) in sec 11.1.4. | N = 200 # number of samples
b_GP = 1 # direct effect of G on P
b_GC = 0 # direct effect of G on C
b_PC = 1 # direct effect of P on C
b_U = 2 # direct effect of U on P and C
with numpyro.handlers.seed(rng_seed=1):
# U = 2 * numpyro.sample("U", dist.Bernoulli(0.5).expand([N])) - 1
U = numpyro.sample("U", di... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Counterfactual plot
Similar to p140 | # p(C | do(G), do(P))
Pfixed = 0
df0 = make_samples(G=0, P=Pfixed, nsamples=200)
display(df0.head())
Cbar0 = df0["C"].values.mean()
df1 = make_samples(G=1, P=Pfixed, nsamples=200)
display(df1.head())
Cbar1 = df1["C"].values.mean()
print([Cbar0, Cbar1])
sim_dat = dict(G=jnp.array([0, 1]), P=jnp.array(Pfixed))
post =... | notebooks/misc/logreg_ucb_admissions_numpyro.ipynb | probml/pyprobml | mit |
Are we underfitting?
Our validation accuracy so far has generally been higher than our training accuracy. That leads to two obvious questions:
How is this possible?
Is this desirable?
The answer to (1) is that this is happening because of dropout. Dropout refers to a layer that randomly deletes (i.e. sets to zero) ea... | model = vgg_ft(2) | Overfitting.ipynb | sysid/nbs | mit |
...and load our fine-tuned weights. | model.load_weights(model_path+'finetune3.h5') | Overfitting.ipynb | sysid/nbs | mit |
We're going to be training a number of iterations without dropout, so it would be best for us to pre-calculate the input to the fully connected layers - i.e. the Flatten() layer. We'll start by finding this layer in our model, and creating a new model that contains just the layers up to and including this layer: | layers = model.layers
last_conv_idx = [index for index,layer in enumerate(layers)
if type(layer) is Convolution2D][-1]
last_conv_idx
layers[last_conv_idx]
conv_layers = layers[:last_conv_idx+1]
conv_model = Sequential(conv_layers)
# Dense layers - also known as fully connected or 'FC' layers
f... | Overfitting.ipynb | sysid/nbs | mit |
Now we can use the exact same approach to creating features as we used when we created the linear model from the imagenet predictions in the last lesson - it's only the model that has changed. As you're seeing, there's a fairly small number of "recipes" that can get us a long way! | batches = get_batches(path+'train', shuffle=False, batch_size=batch_size)
val_batches = get_batches(path+'valid', shuffle=False, batch_size=batch_size)
val_classes = val_batches.classes
trn_classes = batches.classes
val_labels = onehot(val_classes)
trn_labels = onehot(trn_classes)
val_features = conv_model.predict_ge... | Overfitting.ipynb | sysid/nbs | mit |
For our new fully connected model, we'll create it using the exact same architecture as the last layers of VGG 16, so that we can conveniently copy pre-trained weights over from that model. However, we'll set the dropout layer's p values to zero, so as to effectively remove dropout. | # Copy the weights from the pre-trained model.
# NB: Since we're removing dropout, we want to half the weights
def proc_wgts(layer): return [o/2 for o in layer.get_weights()]
# Such a finely tuned model needs to be updated very slowly!
opt = RMSprop(lr=0.00001, rho=0.7)
def get_fc_model():
model = Sequential([
... | Overfitting.ipynb | sysid/nbs | mit |
And fit the model in the usual way: | fc_model.fit(trn_features, trn_labels, nb_epoch=8,
batch_size=batch_size, validation_data=(val_features, val_labels))
fc_model.save_weights(model_path+'no_dropout.h5')
fc_model.load_weights(model_path+'no_dropout.h5') | Overfitting.ipynb | sysid/nbs | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.