markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
2 - Load the Dataset Now, load the dataset you'll be working on. The following code will load a "flower" 2-class dataset into variables X and Y. | X, Y = load_planar_dataset() | _____no_output_____ | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue. | # Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); | _____no_output_____ | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
You have: - a numpy-array (matrix) X that contains your features (x1, x2) - a numpy-array (vector) Y that contains your labels (red:0, blue:1).First, get a better sense of what your data is like. Exercise 1 How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`? **H... | # (≈ 3 lines of code)
# shape_X = ...
# shape_Y = ...
# training set size
# m = ...
# YOUR CODE STARTS HERE
shape_X = X.shape
shape_Y = Y.shape
m = Y.shape[1]
# YOUR CODE ENDS HERE
print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m))... | The shape of X is: (2, 400)
The shape of Y is: (1, 400)
I have m = 400 training examples!
2
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
**Expected Output**: shape of X (2, 400) shape of Y (1, 400) m 400 3 - Simple Logistic RegressionBefore building a full neural network, let's check how logistic regression performs on this problem. You can use sklearn's built-in functions for this. Run the code below ... | # Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T); | _____no_output_____ | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
You can now plot the decision boundary of these models! Run the code below. | # Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
print(X.shape)
# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/f... | (2, 400)
Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
**Expected Output**: Accuracy 47% **Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! 4 - Neural Network modelLogistic regression didn't work well on the flower dataset. Next, you're going... | # GRADED FUNCTION: layer_sizes
def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size o... | (2, 3)
The size of the input layer is: n_x = 5
The size of the hidden layer is: n_h = 4
The size of the output layer is: n_y = 2
(2, 3)
(2, 3)
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```The size of the input layer is: n_x = 5The size of the hidden layer is: n_h = 4The size of the output layer is: n_y = 2``` 4.2 - Initialize the model's parameters Exercise 3 - initialize_parametersImplement the function `initialize_parameters()`.**Instructions**:- Make sure your parameters' s... | # 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:
params -- python dictionary containing your parameters:
W1 -- wei... | W1 = [[-0.00416758 -0.00056267]
[-0.02136196 0.01640271]
[-0.01793436 -0.00841747]
[ 0.00502881 -0.01245288]]
b1 = [[0.]
[0.]
[0.]
[0.]]
W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]
b2 = [[0.]]
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
**Expected output**```W1 = [[-0.00416758 -0.00056267] [-0.02136196 0.01640271] [-0.01793436 -0.00841747] [ 0.00502881 -0.01245288]]b1 = [[0.] [0.] [0.] [0.]]W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]b2 = [[0.]]``` 4.3 - The Loop Exercise 4 - forward_propagationImplement `forward_propagation()` using th... | # GRADED FUNCTION:forward_propagation
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- python dictionary containing your parameters (output of initialization function)
Returns:
A2 -- The sigmoid output of the second activation
cache -... | A2 = [[0.21292656 0.21274673 0.21295976]]
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```A2 = [[0.21292656 0.21274673 0.21295976]]``` 4.4 - Compute the CostNow that you've computed $A^{[2]}$ (in the Python variable "`A2`"), which contains $a^{[2](i)}$ for all examples, you can compute the cost function as follows:$$J = - \frac{1}{m} \sum\limits_{i = 1}^{m} \large{(} \small y^{(i)}\... | # GRADED FUNCTION: compute_cost
def compute_cost(A2, Y):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
Returns:
cost -... | cost = 0.6930587610394646
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***`cost = 0.6930587610394646` 4.5 - Implement BackpropagationUsing the cache computed during forward propagation, you can now implement backward propagation. Exercise 6 - backward_propagationImplement the function `backward_propagation()`.**Instructions**:Backpropagation is usually the hardest (mos... | # GRADED FUNCTION: backward_propagation
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
... | dW1 = [[ 0.00301023 -0.00747267]
[ 0.00257968 -0.00641288]
[-0.00156892 0.003893 ]
[-0.00652037 0.01618243]]
db1 = [[ 0.00176201]
[ 0.00150995]
[-0.00091736]
[-0.00381422]]
dW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]]
db2 = [[-0.16655712]]
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```dW1 = [[ 0.00301023 -0.00747267] [ 0.00257968 -0.00641288] [-0.00156892 0.003893 ] [-0.00652037 0.01618243]]db1 = [[ 0.00176201] [ 0.00150995] [-0.00091736] [-0.00381422]]dW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]]db2 = [[-0.16655712]]``` 4.6 - Update Parameters Exercise 7 - u... | # GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradie... | W1 = [[-0.00643025 0.01936718]
[-0.02410458 0.03978052]
[-0.01653973 -0.02096177]
[ 0.01046864 -0.05990141]]
b1 = [[-1.02420756e-06]
[ 1.27373948e-05]
[ 8.32996807e-07]
[-3.20136836e-06]]
W2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]
b2 = [[0.00010457]]
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```W1 = [[-0.00643025 0.01936718] [-0.02410458 0.03978052] [-0.01653973 -0.02096177] [ 0.01046864 -0.05990141]]b1 = [[-1.02420756e-06] [ 1.27373948e-05] [ 8.32996807e-07] [-3.20136836e-06]]W2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]b2 = [[0.00010457]]``` 4.7 - IntegrationIntegrate y... | # GRADED FUNCTION: nn_model
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loo... | (1, 3)
(1, 3)
Cost after iteration 0: 0.692739
Cost after iteration 1000: 0.000218
Cost after iteration 2000: 0.000107
Cost after iteration 3000: 0.000071
Cost after iteration 4000: 0.000053
Cost after iteration 5000: 0.000042
Cost after iteration 6000: 0.000035
Cost after iteration 7000: 0.000030
Cost after iteration ... | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```Cost after iteration 0: 0.692739Cost after iteration 1000: 0.000218Cost after iteration 2000: 0.000107...Cost after iteration 8000: 0.000026Cost after iteration 9000: 0.000023W1 = [[-0.65848169 1.21866811] [-0.76204273 1.39377573] [ 0.5792005 -1.10397703] [ 0.76773391 -1.41477129]]b1 = [[ 0.2... | # GRADED FUNCTION: predict
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of o... | Predictions: [[ True False True]]
[92m All tests passed.
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
***Expected output***```Predictions: [[ True False True]]``` 5.2 - Test the Model on the Planar DatasetIt's time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units! | # Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4))
# Print accuracy
predictions = p... | Accuracy: 90%
| MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
**Expected Output**: Accuracy 90% Accuracy is really high compared to Logistic Regression. The model has learned the patterns of the flower's petals! Unlike logistic regression, neural networks are able to learn even highly non-linear decision boundaries. Congrats on finishing this Programming Assignmen... | # This may take about 2 minutes to run
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(... | (1, 400)
(1, 400)
Accuracy for 1 hidden units: 67.5 %
(1, 400)
(1, 400)
Accuracy for 2 hidden units: 67.25 %
(1, 400)
(1, 400)
Accuracy for 3 hidden units: 90.75 %
(1, 400)
(1, 400)
Accuracy for 4 hidden units: 90.5 %
(1, 400)
(1, 400)
Accuracy for 5 hidden units: 91.25 %
(1, 400)
(1, 400)
Accuracy for 20 hidden units:... | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
**Interpretation**:- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. - The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.-... | # Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()
datasets = {"noisy_circles": noisy_circles,
"noisy_moons": noisy_moons,
"blobs": blobs,
"gaussian_quantiles": gaussian_quantiles}
### START CODE HERE ### (choose your dataset)
dat... | _____no_output_____ | MIT | Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb | sounok1234/Deeplearning_Projects |
Preprocess the image | # resize the image
basewidth = 100
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img = np.array(img)[:,:,:3]
print(img.shape)
plt.imshow(img)
img = img.reshape(-1,3)
img.shape | _____no_output_____ | MIT | loc_clust_stripe_segmentation.ipynb | YuTian8328/flow-based-clustering |
Perform the segmentation task via Kmeans | kmeans = KMeans(n_clusters=2).fit(img)
plt.imshow(kmeans.labels_.reshape(29,100)) | _____no_output_____ | MIT | loc_clust_stripe_segmentation.ipynb | YuTian8328/flow-based-clustering |
Perform the task via our algorithm | # generate graph from image
img = img.reshape(-1,3)/255
n_nodes=img.shape[0]
print("number of nodes:",n_nodes )
B,weight=get_B_and_weight_vec(n_nodes,0.2,1)
# plt.hist(weight,bins=30) #distribution of similarity measure
def run_seg(n_nodes,seeds,threshold, K=30, alpha=0.1, lambda_nLasso=0.1):
B, weight_vec = get_... | _____no_output_____ | MIT | loc_clust_stripe_segmentation.ipynb | YuTian8328/flow-based-clustering |
Perform the segmentation task via spectral clustering | from sklearn.cluster import SpectralClustering
s=SpectralClustering(2).fit(img)
plt.imshow(s.labels_.reshape(29,100))
# Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph
#... | Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1 | MIT | loc_clust_stripe_segmentation.ipynb | YuTian8328/flow-based-clustering |
Solution Graded Exercise 1: Leaky-integrate-and-fire model first name: Evelast name: Rahbesciper: 235549date: 21.03.2018*Your teammate*first name of your teammate: Antoinelast name of your teammate: Alleonsciper of your teammate: 223333Note: You are allowed to discuss the concepts with your class mates. You are not al... | %matplotlib inline
import brian2 as b2
import matplotlib.pyplot as plt
import numpy as np
from neurodynex.leaky_integrate_and_fire import LIF
from neurodynex.tools import input_factory, plot_tools
LIF.getting_started()
LIF.print_default_parameters() | nr of spikes: 0
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.1 Exercise: minimal current 2.1.1. Question: minimal current (calculation) [2 points] | from neurodynex.leaky_integrate_and_fire import LIF
print("resting potential: {}".format(LIF.V_REST))
i_min = (LIF.FIRING_THRESHOLD-LIF.V_REST)/LIF.MEMBRANE_RESISTANCE
print("minimal current i_min: {}".format(i_min)) | resting potential: -0.07
minimal current i_min: 2e-09
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
The minimal current is :$i_{min} = \frac{\theta-u_{rest}}{R} = \frac{-50-(-70) [mV]}{10 [Mohm]} = 2 [nA]$$\theta$ is the firing threshold$u_{rest}$ is the resting potential$R$ is the membrane resistance 2.1.2. Question: minimal current (simulation) [2 points] | # create a step current with amplitude= i_min
step_current = input_factory.get_step_current(
t_start=5, t_end=100, unit_time=b2.ms,
amplitude= i_min) # set i_min to your value
# run the LIF model.
# Note: As we do not specify any model parameters, the simulation runs with the default values
(state_monitor,spi... | nr of spikes: 0
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.2. Exercise: f-I Curve 2.2.1. Question: f-I Curve and refractoryness 1 - Sketch or plot the curve with some program. You don't have to include it here, it is just for your understanding and will not be graded.2 - What is the maximum rate at which this neuron can fire? [3 points] | # create a step current with amplitude i_max
i_max = 125 * b2.namp
step_current = input_factory.get_step_current(
t_start=5, t_end=100, unit_time=b2.ms,
amplitude=i_max)
# run the LIF model and set the absolute refractory period to 3ms
(state_monitor,spike_monitor) = LIF.simulate_LIF_neuron(input_current=step_... | nr of spikes: 32
T : 0.00296875
firing frequency : 336.842105263
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
The maximum rate at which this neuron can fire is $f = 336.84 [Hz]$. 3 - Inject currents of different amplitudes (from 0nA to 100nA) into a LIF neuron. For each current, run the simulation for 500ms and determine the firing frequency in Hz. Then plot the f-I curve. [4 points] | import numpy as np
import matplotlib.pyplot as plt
firing_frequency = []
# create a step current with amplitude i from 0 to 100 nA
for i in range(0,100,1) :
step_current = input_factory.get_step_current(
t_start=5, t_end=100, unit_time=b2.ms,
amplitude=i * b2.namp) # stock amplitude i from 0 to 1... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.3. Exercise: “Experimentally” estimate the parameters of a LIF neuron 2.3.1. Question: “Read” the LIF parameters out of the vm plot [6 points] My estimates for the parameters :\begin{itemize}\item Resting potential : $u_{rest} = -66 [mV]$.\item Reset potential : $u_{reset} = -63 [mV]$ is the membrane potential betwe... | # get a random parameter. provide a random seed to have a reproducible experiment
random_parameters = LIF.get_random_param_set(random_seed=432)
# define your test current
test_current = input_factory.get_step_current(
t_start=5, t_end=100, unit_time=b2.ms, amplitude= 10 * b2.namp)
# probe the neuron. pass the tes... | Resting potential: -0.066
Reset voltage: -0.063
Firing threshold: -0.038
Membrane resistance: 13000000.0
Membrane time-scale: 0.013
Absolute refractory period: 0.005
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.4. Exercise: Sinusoidal input current and subthreshold response 2.4.1. Question [5 points] | # note the higher resolution when discretizing the sine wave: we specify unit_time=0.1 * b2.ms
sinusoidal_current = input_factory.get_sinusoidal_current(200, 1000, unit_time=0.1 * b2.ms,
amplitude= 2.5 * b2.namp, frequency=250*b2.Hz,
... | nr of spikes: 0
Amplitude of the membrane voltage : 0.001985117111761442 V
Phase shift : -1.5707963267948966
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
The results are : $ A = 2 [mV]$ (computationnally and visually) and $phase = -\pi/2$ (computationnally and visually). 2.4.2. Question [5 points] | # For input frequencies between 10Hz and 1kHz plot the resulting amplitude of subthreshold oscillations of the
# membrane potential vs. input frequency.
amplitude = []
for i in range(15) :
sinusoidal_current = input_factory.get_sinusoidal_current(200, 1000, unit_time=0.1 * b2.ms,
... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.4.3. Question [5 points] | # For input frequencies between 10Hz and 1kHz
# plot the resulting phase shift of subthreshold oscillations of the membrane potential vs. input frequency.
phase = []
for f in [10,50,100,250,500,750,1000] :
sinusoidal_current = input_factory.get_sinusoidal_current(200, 1000, unit_time=0.1 * b2.ms,
... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2.4.4. Question [3 points] It is a \textbf{Low-Pass} filter because it amplifies low frequencies and attenuates high frequencies. 2.5 Leaky integrate-and-fire neuron with noisy inputThis exercise is not available online. All information is given here.So far you have explored the leaky integrate-and-fire model with s... | def get_noisy_step_current(t_start, t_end, unit_time, amplitude, sigma, append_zero=True):
"""Creates a step current with added noise. If t_start == t_end, then a single
entry in the values array is set to amplitude.
Args:
t_start (int): start of the step
t_end (int): end of the step
... | nr of spikes: 3
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2 - How does the neuron behave? Discuss your result. Your answer should be max 3 lines long. The current behaves randomly increasing or decreasing at each time step (like in a Markov process). The membrane voltage reacts to this input current by following the increasing or decreasing pattern. When the current is large ... | from neurodynex.tools import spike_tools, plot_tools
# time unit. e.g.
time_unit = 1.*b2.ms
time_step = time_unit
def test_effect_of_noise(amplitude, sigma, bins = np.linspace(0,1,50)):
# Create a noisy step current
noisy_step_current = get_noisy_step_current(t_start=50, t_end=5000, unit_time = time_ste... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2 - Discuss yout results (ISI histograms) for the four regimes regimes. For help and inspiration, as well as for verification of your results, have a look at the book chapter 8.3 (http://neuronaldynamics.epfl.ch/online/Ch8.S3.html). Your answer should be max 5 lines long. [5 points] \begin{itemize}\item The first regim... | import math
def get_noisy_sinusoidal_current(t_start, t_end, unit_time,
amplitude, frequency, direct_current, sigma, phase_offset=0.,
append_zero=True):
"""Creates a noisy sinusoidal current. If t_start == t_end, then ALL entries are 0.
Args:
t_sta... | nr of spikes: 2
| MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
In the noiseles case, the voltage reaches the firing threshold but does not generate any spike. In the noisy case we observe some spikes when the firing threshold is exceeded around the maxima of the sinusoid. 2.5.4 Stochastic resonance (Bonus, not graded)Contrary to what one may expect, some amount of noise under cer... | amplitude = 1.*b2.nA
frequency = 20*b2.Hz
time_unit = 1.*b2.ms
time_step = .1*b2.ms
direct_current = 1. * b2.nA
sampling_frequency = .01/time_step
noise_amplitude = 2.
n_inits = 5
# run simulation and calculate power spectrum
def _run_sim(amplitude, noise_amplitude):
noisy_sinusoidal_current = get_noisy_sinusoidal... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
2 - We now apply different noise levels to investigate the optimal noise level of stochastic resonance. The quantity to optimize is the signal-to-noise ratio (SNR). Here, the SNR is defined as the intensity of the power spectrum at the driving frequency (the peak from above), divided by the value of the background nois... | def get_snr(amplitude, noise_amplitude, n_inits):
spectra = []
snr = 0.
for i in range(0,n_inits):
# run model with noisy sinusoidal
freq_signal, spectrum, mfr = ???
spectra.append(spectrum[0])
# Average over trials to get power spectrum
spectrum = ???
if mfr != 0... | _____no_output_____ | MIT | project1/.ipynb_checkpoints/Ex2_Eve_Rahbe_235549-checkpoint.ipynb | antoine-alleon/Biological_Modelling_Neural_Network_python_exercises |
Azure ML Training Pipeline for COVID-CXRThis notebook defines an Azure machine learning pipeline for a single training run and submits the pipeline as an experiment to be run on an Azure virtual machine. | # Import statements
import azureml.core
from azureml.core import Experiment
from azureml.core import Workspace, Datastore
from azureml.data.data_reference import DataReference
from azureml.pipeline.core import PipelineData
from azureml.pipeline.core import Pipeline
from azureml.pipeline.steps import PythonScriptStep, E... | _____no_output_____ | MIT | azure/train_pipeline.ipynb | fashourr/covid-cxr |
Register the workspace and configure its Python environment. | # Get reference to the workspace
ws = Workspace.from_config("./ws_config.json")
# Set workspace's environment
env = Environment.from_pip_requirements(name = "covid-cxr_env", file_path = "./../requirements.txt")
env.register(workspace=ws)
runconfig = RunConfiguration(conda_dependencies=env.python.conda_dependencies)
pr... | _____no_output_____ | MIT | azure/train_pipeline.ipynb | fashourr/covid-cxr |
Create references to persistent and intermediate dataCreate DataReference objects that point to our raw data on the blob. Configure a PipelineData object to point to preprocessed images stored on the blob. | # Get the blob datastore associated with this workspace
blob_store = Datastore(ws, name='covid_cxr_ds')
# Create data references to folders on the blob
raw_data_dr = DataReference(
datastore=blob_store,
data_reference_name="raw_data",
path_on_datastore="data/")
mila_data_dr = DataReference(
datastore=b... | _____no_output_____ | MIT | azure/train_pipeline.ipynb | fashourr/covid-cxr |
Compute TargetSpecify and configure the compute target for this workspace. If a compute cluster by the name we specified does not exist, create a new compute cluster. | CT_NAME = "nd12s-clust-hp" # Name of our compute cluster
VM_SIZE = "STANDARD_ND12S" # Specify the Azure VM for execution of our pipeline
#CT_NAME = "d2-cluster" # Name of our compute cluster
#VM_SIZE = "STANDARD_D2" # Specify the Azure VM for execution of our pipeline
# Set up the compute tar... | _____no_output_____ | MIT | azure/train_pipeline.ipynb | fashourr/covid-cxr |
Define pipeline and submit experiment.Define the steps of an Azure machine learning pipeline. Create an Azure Experiment that will run our pipeline. Submit the experiment to the execution environment. | # Define preprocessing step the ML pipeline
step1 = PythonScriptStep(name="preprocess_step",
script_name="azure/preprocess_step/preprocess_step.py",
arguments=["--miladatadir", mila_data_dr, "--fig1datadir", fig1_data_dr,
"--rsnadata... | _____no_output_____ | MIT | azure/train_pipeline.ipynb | fashourr/covid-cxr |
SIT742: Modern Data Science **(Week 01: Programming Python)**---- Materials in this module include resources collected from various open-source online repositories.- You are free to use, change and distribute this package.- If you found any issue/bug for this document, please submit an issue at [tulip-lab/sit742](http... | ipython notebook %don't run this in notebook, run it on command line to activate the server | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
You can see the message in the terminal windows as follows:This will open a new browser window(or a new tab in your browser window). In the browser, there is an **dashboard** page which shows you all the folders and files under **sit742** folder 1.2 A tour of iPython notebook Create a new ipython notebook ... | text = "Hello World"
print(text) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
After this, press **CTRL + ENTER**, and execute the cell. The result will be shown after the cell. After a cell is executed , the notebook is switched to the **Commmand** mode. In this mode, you can manipulte the notebook and its commponent. Alternatively, you can use **ESC** key to switch from **Edit** mode to **... | text = "Good morning World!" | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Afterwards, press **CTRL + ENTER**, and the new output is displayed. As you can see, you are switching bewteen two modes, **Command** and **Edit**, when editing a notebook. We will in later section look into these two operation modes of closely. Now practise switching between the two modes until you are comfort... | ## Heading 2
Normal text here!
### Heading 3
ordered list here
0. Fruits
0. Banana
0. Grapes
0. Veggies
0. Tomato
0. Broccoli
Unordered list here
- Fruits
- Banana
- Grapes
- Veggies
- Tomato
- Broccoli | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Now execute the cell by press **CTRL+ ENTER**. You notebook should look like this: Here is what the formated Markdown cell looks like: Exercise:Click this cell, and practise writing markdown language here.... 1.3 IPython notebook interfaceNow you have created your first notebook, let us have a close look at th... | sum? | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
The other improtant thing to know is how to interrupt a compuation. This can be done through the menu **Kernel->Interrupt** or **Kernel->Restart**, depending on what works on the situation. We will have chance to try this in later session. Notebook cell typesThere are basically three types of cells in a IPython noteb... | print('Hello, World!') | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
We can also use a variable to store the string value, and use the variable in the**print()** function. | # Assign a string to a variable
text = 'Hello, World!'
print(text) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
A *variable* is basically a name that represents (or refers to) some value. We use **=**to assign a value to a variable before we use it. Variable names are given by a programerin a way that the program is easy to understanding. Variable names are *case sensitive*.It can consist of letters, digits and underscores. Howe... | text = 'Hello, World!'
# with print() function, content is displayed without quotation mark
print(text) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
With variables, we can also display its value without **print()** function. Note thatyou can not display a variable without **print()** function in Python script(i.e. in a **.py** file). This method only works under interactive mode (i.e. in the notebook). | # without print() function, quotation mark is displayed together with content
text | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Back to representation of string, there will be issues if you need to include a quotationmark in the text. | text = ’What’ s your name ’ | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Since strings in double quotes **"** work exactly the same way as string in single quotes.By mixing the two types, it is easy to include quaotation mark itself in the text. | text = "What' s your name?"
print(text) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Alternertively, you can use: | text = '"What is the problem?", he asked.'
print(text) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
You can specify multi-line strings using triple quotes (**"""** or **'''**). In this way, singlequotes and double quotes can be used freely in the text.Here is one example: | multiline = '''This is a test for multiline. This is the first line.
This is the second line.
I asked, "What's your name?"'''
print(multiline) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Notice the difference when the variable is displayed without **print()** function in this case. | multiline = '''This is a test for multiline. This is the first line.
This is the second line.
I asked, "What's your name?"'''
multiline | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Another way of include the special characters, such as single quotes is with help ofescape sequences **\\**. For example, you can specify the single quote using **\\' ** as follows. | string = 'What\'s your name?'
print(string) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
There are many more other escape sequences (See Section 2.4.1 in [Python3.0 official document](https://docs.python.org/3.1/reference/lexical_analysis.html)). But I am going to mention the most useful two examples here. First, use escape sequences to indicate the backslash itself e.g. **\\\\** | path = 'c:\\windows\\temp'
print(path) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Second, used escape sequences to specify a two-line string. Apart from using a triple-quotedstring as shown previously, you can use **\n** to indicate the start of a new line. | multiline = 'This is a test for multiline. This is the first line.\nThis is the second line.'
print(multiline) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
To manipulate strings, the following two operators are most useful: * **+** is use to concatenatetwo strings or string variables; * ***** is used for concatenating several copies of the samestring. | print('Hello, ' + 'World' * 3) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Below is another example of string concatenation based on variables that store strings. | name = 'World'
greeting = 'Hello'
print(greeting + ', ' + name + '!') | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Using variables, change part of the string text is very easy. | name
greeting
# Change part of the text is easy
greeting = 'Good morning'
print(greeting + ', ' + name + '!') | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
2.2 Number There are two types of numbers that are used most frequently: integers and floats. As weexpect, the standard mathematic operation can be applied to these two types. Pleasetry the following expressions. Note that **\*\*** is exponent operator, which indicatesexponentation exponential(power) caluclation. | 2 + 3
3 * 5
#3 to the power of 4
3 ** 4 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Among the number operations, we need to look at division closely. In Python 3.0, classic division is performed using **/**. | 15 / 5
14 / 5 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
*//* is used to perform floor division. It truncates the fraction and rounds it to the next smallest whole number toward the left on the number line. | 14 // 5
# Negatives move left on number line. The result is -3 instead of -2
-14 // 5 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Modulus operator **%** can be used to obtain remaider. Pay attention when negative number is involved. | 14 % 5
# Hint: −14 // 5 equal to −3
# (-3) * 5 + ? = -14
-14 % 5 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
*Operator precedence* is a rule that affects how an expression is evaluated. As we learned in high school, the multiplication is done first than the addition. e.g. **2 + 3 * 4**. This means multiplication operator has higher precedence than the addition operator.For your reference, a precedence table from the python re... | 2 + 3 * 4
(2 + 3) * 4
2 + 3 ** 2
(2 + 3) ** 2
-(4+3)+2 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Similary as string, variables can be used to store a number so that it is easy to manipulate them. | x = 3
y = 2
x + 2
sum = x + y
sum
x * y | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
One common expression is to run a math operation on a variable and then assign the result of the operation back to the variable. Therefore, there is a shortcut for such a expression. | x = 2
x = x * 3
x | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
This is equivalant to: | x = 2
# Note there is no space between '*' and '+'
x *= 3
x | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
2.3 Data conversion and comparison So far, we have seen three types of data: interger, float, and string. With various data type, Python can define the operations possible on them and the storage method for each of them. In the later pracs, we will further introduce more data types, such as tuple, list and dictionary... | type('Hello, world!)')
input_Value = '45.6'
type(input_Value)
weight = float(input_Value)
weight
type(weight) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Note the system will report error message when the conversion function is not compatible with the data. | input_Value = 'David'
weight = float(input_Value) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Comparison between two values can help make decision in a program. The result of the comparison is either **True** or **False**. They are the two values of *Boolean* type. | 5 > 10
type(5 > 10)
# Double equal sign is also used for comparison
10.0 == 10 | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Check the following examples on comparison of two strings. | 'cat' < 'dog'
# All uppercases are before low cases.
'cat' < 'Dog'
'apple' < 'apricot' | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
There are three logical operators, *not*, *and* and *or*, which can be applied to the boolean values. | # Both condition #1 and condition #2 are True?
3 < 4 and 7 < 8
# Either condition 1 or condition 2 are True?
3 < 4 or 7 > 8
# Both conditional #1 and conditional #2 are False?
not ((3 > 4) or (7 > 8)) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
2. 4. Input and output All programing languages provide features to interact with user. Python provide *input()* function to get input. It waits for the user to type some input and press return. We can add some information for the user by putting a message inside the function's brackets. It must be a string or a stri... | nInput = input('Enter you number here:\n') | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
However, be aware that the input received from the user are treated as a string, eventhough a user entered a number. The following **print()** function invokes an error message. | print(nInput + 3) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
The input need to be converted to an integer before the match operation can be performed as follows: | print(int(nInput) + 3) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
After user's input are accepted, the messages need to be displayed to the user accordingly. String concatenation is one way to display messages which incorporate variable values. | name = 'David'
print('Hello, ' + name) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Another way of achieving this is using **print()** funciton with *string formatting*. We need to use the *string formatting operator*, the percent(**%**) sign. | name = 'David'
print('Hello, %s' % name) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Here is another example with two variables: | name = 'David'
age = 23
print('%s is %d years old.' % (name, age)) | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
Notice that the two variables, **name**, **age**, that specify the values are included at the end of the statement, and enclosed with a bracket. With the quotation mark, **%s** and **%d** are used to specify formating for string and integer respectively. The following table shows a selected set of symbols which can be... | # With %f, the format is right justification by default.
# As a result, white spaces are added to the left of the number
# 10.4 means minimal width 10 with 4 decinal points
print('Output a float number: %10.4f' % (3.5))
# plus sign after % means to show positive sign
# Zero after plus sign means using leading zero to ... | _____no_output_____ | MIT | Jupyter/SIT742P01A-Python.ipynb | jilliant/sit742 |
General Equilibrium This notebook illustrates **how to solve GE equilibrium models**. The example is a simple one-asset model without nominal rigidities.The notebook shows how to:1. Solve for the **stationary equilibrium**.2. Solve for (non-linear) **transition paths** using a relaxtion algorithm.3. Solve for **transi... | LOAD = False # load stationary equilibrium
DO_VARY_SIGMA_E = True # effect of uncertainty on stationary equilibrium
DO_TP_RELAX = True # do transition path with relaxtion | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Setup | %load_ext autoreload
%autoreload 2
import time
import numpy as np
import numba as nb
from scipy import optimize
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
from consav.misc import elapsed
from GEModel import GE... | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Choose number of threads in numba | import numba as nb
nb.set_num_threads(8) | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Model | model = GEModelClass('baseline',load=LOAD)
print(model) | Modelclass: GEModelClass
Name: baseline
namespaces: ['sol', 'sim', 'par']
other_attrs: []
savefolder: saved
not_floats: ['Ne', 'Na', 'max_iter_solve', 'max_iter_simulate', 'path_T']
sol:
a = ndarray with shape = (7, 500) [dtype: float64]
m = ndarray with shape = (7, 500) [dtype: float64]
c = ndarray with shape = (... | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
For easy access | par = model.par
sim = model.sim
sol = model.sol | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Productivity states:** | for e,pr_e in zip(par.e_grid,par.e_ergodic):
print(f'Pr[e = {e:7.4f}] = {pr_e:.4f}')
assert np.isclose(np.sum(par.e_grid*par.e_ergodic),1.0) | Pr[e = 0.3599] = 0.0156
Pr[e = 0.4936] = 0.0938
Pr[e = 0.6769] = 0.2344
Pr[e = 0.9282] = 0.3125
Pr[e = 1.2729] = 0.2344
Pr[e = 1.7456] = 0.0937
Pr[e = 2.3939] = 0.0156
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Find Stationary Equilibrium **Step 1:** Find demand and supply of capital for a grid of interest rates. | if not LOAD:
t0 = time.time()
par = model.par
# a. interest rate trial values
Nr = 20
r_vec = np.linspace(0.005,1.0/par.beta-1-0.002,Nr) # 1+r > beta not possible
# b. allocate
Ks = np.zeros(Nr)
Kd = np.zeros(Nr)
# c. loop
r_min = r_vec[0]
r_max = r_vec[Nr-1]
... | grid search done in 10.8 secs
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 2:** Plot supply and demand. | if not LOAD:
par = model.par
fig = plt.figure(figsize=(6,4))
ax = fig.add_subplot(1,1,1)
ax.plot(r_vec,Ks,label='supply of capital')
ax.plot(r_vec,Kd,label='demand for capital')
ax.axvline(r_min,lw=0.5,ls='--',color='black')
ax.axvline(r_max,lw=0.5,ls='--',color='black')
ax.lege... | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 3:** Solve root-finding problem. | def obj(r,model):
model.solve_household_ss(r=r)
model.simulate_household_ss()
return np.sum(model.sim.D*model.sol.a)-model.firm_demand(r,model.par.Z)
if not LOAD:
t0 = time.time()
opt = optimize.root_scalar(obj,bracket=[r_min,r_max],method='bisect',args=(model,))
model.par.r_ss =... | search done in 7.1 secs
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 4:** Check market clearing conditions. | model.steady_state() | household problem solved in 0.1 secs [652 iterations]
household problem simulated in 0.1 secs [747 iterations]
r: 0.0127
w: 1.0160
Y: 1.1415
K/Y: 2.9186
capital market clearing: -0.00000000
goods market clearing: -0.00000755
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Timings | %timeit model.solve_household_ss(r=par.r_ss)
%timeit model.simulate_household_ss() | 66.2 ms ± 1.42 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Income uncertainty and the equilibrium interest rate The equlibrium interest rate decreases when income uncertainty is increased. | if DO_VARY_SIGMA_E:
par = model.par
# a. seetings
sigma_e_vec = [0.20]
# b. find equilibrium rates
model_ = model.copy()
for sigma_e in sigma_e_vec:
# i. set new parameter
model_.par.sigma_e = sigma_e
model_.create_grids()
# ii. solve
prin... | sigma_e = 0.2000 -> r_ss = 0.0029
household problem solved in 0.1 secs [430 iterations]
household problem simulated in 0.0 secs [427 iterations]
r: 0.0029
w: 1.0546
Y: 1.1849
K/Y: 3.9462
capital market clearing: -0.00000000
goods market clearing: -0.00000587
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Test matrix formulation **Step 1:** Construct $\boldsymbol{Q}_{ss}$ | # a. allocate Q
Q = np.zeros((par.Ne*par.Na,par.Ne*par.Na))
# b. fill
for i_e in range(par.Ne):
# get view of current block
q = Q[i_e*par.Na:(i_e+1)*par.Na,i_e*par.Na:(i_e+1)*par.Na]
for i_a in range(par.Na):
# i. optimal choice
a_opt = sol.a[i_e,i_a]
# i... | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 2:** Construct $\tilde{\Pi}^e=\Pi^e \otimes \boldsymbol{I}_{\_{a}\times\_{a}}$ | Pit = np.kron(par.e_trans,np.identity(par.Na)) | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 3:** Test $\overrightarrow{D}_{t+1}=\tilde{\Pi}^{e\prime}\boldsymbol{Q}_{ss}^{\prime}\overrightarrow{D}_{t}$ | D = np.zeros(sim.D.shape)
D[:,0] = par.e_ergodic
# a. standard
D_plus = np.zeros(D.shape)
simulate_forwards(D,sol.i,sol.w,par.e_trans.T.copy(),D_plus)
# b. matrix product
D_plus_alt = ((Pit.T@Q.T)@D.ravel()).reshape((par.Ne,par.Na))
# c. test equality
assert np.allclose(D_plus,D_plus_alt) | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Find transition path **MIT-shock:** Transtion path for arbitrary exogenous path of $Z_t$ starting from the stationary equilibrium, i.e. $D_{-1} = D_{ss}$ and in particular $K_{-1} = K_{ss}$. **Step 1:** Construct $\{Z_t\}_{t=0}^{T-1}$ where $Z_t = (1-\rho_Z)Z_{ss} + \rho_Z Z_t$ and $Z_0 = (1+\sigma_Z) Z_{ss}$ | path_Z = model.get_path_Z() | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Step 2:** Apply relaxation algorithm. | if DO_TP_RELAX:
t0 = time.time()
# a. allocate
path_r = np.repeat(model.par.r_ss,par.path_T) # use steady state as initial guess
path_r_ = np.zeros(par.path_T)
path_w = np.zeros(par.path_T)
# b. setting
nu = 0.90 # relaxation parameter
max_iter = 5000 # maximum number of iteration... | 0: 0.00038764
10: 0.00013139
20: 0.00004581
30: 0.00001597
40: 0.00000557
50: 0.00000194
60: 0.00000068
70: 0.00000024
80: 0.00000008
90: 0.00000003
100: 0.00000001
transtion path found in 23.7 secs
| MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Plot transition-paths:** | if DO_TP_RELAX:
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(2,2,1)
ax.plot(np.arange(par.path_T),path_Z,'-o',ms=2)
ax.set_title('technology, $Z_t$');
ax = fig.add_subplot(2,2,2)
ax.plot(np.arange(par.path_T),sim.path_K,'-o',ms=2)
ax.set_title('capital, $k_t$');
ax = fig... | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Remember:** | if DO_TP_RELAX:
path_Z_relax = path_Z
path_K_relax = sim.path_K
path_r_relax = path_r
path_w_relax = path_w
| _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Find impulse-responses using sequence-space method **Paper:** Auclert, A., Bardóczy, B., Rognlie, M., and Straub, L. (2020). *Using the Sequence-Space Jacobian to Solve and Estimate Heterogeneous-Agent Models*. **Original code:** [shade-econ](https://github.com/shade-econ/sequence-jacobian/sequence-space-jacobian)**Th... | def jac(model,price,dprice=1e-4,do_print=True):
t0_all = time.time()
if do_print: print(f'price is {price}')
par = model.par
sol = model.sol
sim = model.sim
# a. step 1: solve backwards
t0 = time.time()
path_r = np.repeat(par.r_ss,par.path_T)
path_w = np.repeat(p... | price is r
solved backwards in 0.2 secs
derivatives calculated in 2.0 secs
expecation factors calculated in 0.8 secs
f calculated in 0.1 secs
J calculated in 0.0 secs
full Jacobian calculated in 3.1 secs
price is w
solved backwards in 0.1 secs
derivatives calculated in 0.2 secs
expecation factors calculated in 0.1 sec... | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
**Inspect Jacobians:** | fig = plt.figure(figsize=(12,8))
T_fig = 200
# curlyK_r
ax = fig.add_subplot(2,2,1)
for s in [0,25,50,75,100]:
ax.plot(np.arange(T_fig),sol.jac_curlyK_r[s,:T_fig],'-o',ms=2,label=f'$s={s}$')
ax.legend(frameon=True)
ax.set_title(r'$\mathcal{J}^{\mathcal{K},r}$')
ax.set_xlim([0,T_fig])
# curlyK_w
ax = fig.add_... | _____no_output_____ | MIT | 00. DynamicProgramming/05. General Equilibrium.ipynb | JMSundram/ConsumptionSavingNotebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.