markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Quiz Question: Which model (1, 2 or 3) has lowest RSS on TRAINING Data? Is this what you expected?
Now compute the RSS on on TEST data for each of the three models. | # Compute the RSS on TESTING data for each of the three models and record the values:
rss_model_1 = get_residual_sum_of_squares(model_1, test_data, test_data['price'])
rss_model_2 = get_residual_sum_of_squares(model_2, test_data, test_data['price'])
rss_model_3 = get_residual_sum_of_squares(model_3, test_data, test_dat... | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Load house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located. | sales = graphlab.SFrame('kc_house_data.gl/') | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Split data into training and testing
We use seed=0 so that everyone running this notebook gets the same results. In practice, you may set a random seed (or let GraphLab Create pick a random seed for you). | train_data,test_data = sales.random_split(.8,seed=0) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Useful SFrame summary functions
In order to make use of the closed form soltion as well as take advantage of graphlab's built in functions we will review some important ones. In particular:
* Computing the sum of an SArray
* Computing the arithmetic average (mean) of an SArray
* multiplying SArrays by constants
* multi... | # Let's compute the mean of the House Prices in King County in 2 different ways.
prices = sales['price'] # extract the price column of the sales SFrame -- this is now an SArray
# recall that the arithmetic average (the mean) is the sum of the prices divided by the total number of houses:
sum_prices = prices.sum()
num_... | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
As we see we get the same answer both ways | # if we want to multiply every price by 0.5 it's a simple as:
half_prices = 0.5*prices
# Let's compute the sum of squares of price. We can multiply two SArrays of the same length elementwise also with *
prices_squared = prices*prices
sum_prices_squared = prices_squared.sum() # price_squared is an SArray of the squares ... | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Aside: The python notation x.xxe+yy means x.xx * 10^(yy). e.g 100 = 10^2 = 1*10^2 = 1e2
Build a generic simple linear regression function
Armed with these SArray functions we can use the closed form solution found from lecture to compute the slope and intercept for a simple linear regression on observations stored as ... | def simple_linear_regression(input_feature, output):
Xi = input_feature
Yi = output
N = len(Xi)
# compute the mean of input_feature and output
Ymean = Yi.mean()
Xmean = Xi.mean()
# compute the product of the output and the input_feature and its mean
SumYiXi = (Yi * Xi).sum()
Yi... | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
We can test that our function works by passing it something where we know the answer. In particular we can generate a feature and then put the output exactly on a line: output = 1 + 1*input_feature then we know both our slope and intercept should be 1 | test_feature = graphlab.SArray(range(5))
test_output = graphlab.SArray(1 + 1*test_feature)
(test_intercept, test_slope) = simple_linear_regression(test_feature, test_output)
print "Intercept: " + str(test_intercept)
print "Slope: " + str(test_slope) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Now that we know it works let's build a regression model for predicting price based on sqft_living. Rembember that we train on train_data! | sqft_intercept, sqft_slope = simple_linear_regression(train_data['sqft_living'], train_data['price'])
print "Intercept: " + str(sqft_intercept)
print "Slope: " + str(sqft_slope) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Predicting Values
Now that we have the model parameters: intercept & slope we can make predictions. Using SArrays it's easy to multiply an SArray by a constant and add a constant value. Complete the following function to return the predicted output given the input_feature, slope and intercept: | def get_regression_predictions(input_feature, intercept, slope):
# calculate the predicted values:
predicted_values = intercept + (slope * input_feature)
return predicted_values | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Now that we can calculate a prediction given the slop and intercept let's make a prediction. Use (or alter) the following to find out the estimated price for a house with 2650 squarefeet according to the squarefeet model we estiamted above.
Quiz Question: Using your Slope and Intercept from (4), What is the predicted p... | my_house_sqft = 2650
estimated_price = get_regression_predictions(my_house_sqft, sqft_intercept, sqft_slope)
print "The estimated price for a house with %d squarefeet is $%.2f" % (my_house_sqft, estimated_price) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Residual Sum of Squares
Now that we have a model and can make predictions let's evaluate our model using Residual Sum of Squares (RSS). Recall that RSS is the sum of the squares of the residuals and the residuals is just a fancy word for the difference between the predicted output and the true output.
Complete the fol... | def get_residual_sum_of_squares(input_feature, output, intercept, slope):
# First get the predictions
predicted_values = intercept + (slope * input_feature)
# then compute the residuals (since we are squaring it doesn't matter which order you subtract)
residuals = output - predicted_values
# square ... | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Let's test our get_residual_sum_of_squares function by applying it to the test model where the data lie exactly on a line. Since they lie exactly on a line the residual sum of squares should be zero! | print get_residual_sum_of_squares(test_feature, test_output, test_intercept, test_slope) # should be 0.0 | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Now use your function to calculate the RSS on training data from the squarefeet model calculated above.
Quiz Question: According to this function and the slope and intercept from the squarefeet model What is the RSS for the simple linear regression using squarefeet to predict prices on TRAINING data? | rss_prices_on_sqft = get_residual_sum_of_squares(train_data['sqft_living'], train_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on Square Feet is : ' + str(rss_prices_on_sqft) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Predict the squarefeet given price
What if we want to predict the squarefoot given the price? Since we have an equation y = a + b*x we can solve the function for x. So that if we have the intercept (a) and the slope (b) and the price (y) we can solve for the estimated squarefeet (x).
Comlplete the following function to... | def inverse_regression_predictions(output, intercept, slope):
# solve output = intercept + slope*input_feature for input_feature. Use this equation to compute the inverse predictions:
estimated_feature = (output - intercept)/slope
return estimated_feature | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Now that we have a function to compute the squarefeet given the price from our simple regression model let's see how big we might expect a house that coses $800,000 to be.
Quiz Question: According to this function and the regression slope and intercept from (3) what is the estimated square-feet for a house costing $800... | my_house_price = 800000
estimated_squarefeet = inverse_regression_predictions(my_house_price, sqft_intercept, sqft_slope)
print "The estimated squarefeet for a house worth $%.2f is %d" % (my_house_price, estimated_squarefeet) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
New Model: estimate prices from bedrooms
We have made one model for predicting house prices using squarefeet, but there are many other features in the sales SFrame.
Use your simple linear regression function to estimate the regression parameters from predicting Prices based on number of bedrooms. Use the training data... | # Estimate the slope and intercept for predicting 'price' based on 'bedrooms'
sqft_intercept, sqft_slope = simple_linear_regression(train_data['bedrooms'], train_data['price'])
print "Intercept: " + str(sqft_intercept)
print "Slope: " + str(sqft_slope) | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
Test your Linear Regression Algorithm
Now we have two models for predicting the price of a house. How do we know which one is better? Calculate the RSS on the TEST data (remember this data wasn't involved in learning the model). Compute the RSS from predicting prices using bedrooms and from predicting prices using squa... | # Compute RSS when using bedrooms on TEST data:
sqft_intercept, sqft_slope = simple_linear_regression(train_data['bedrooms'], train_data['price'])
rss_prices_on_bedrooms = get_residual_sum_of_squares(test_data['bedrooms'], test_data['price'], sqft_intercept, sqft_slope)
print 'The RSS of predicting Prices based on Bedr... | machine_learning/2_regression/assignment/week1/week-1-simple-regression-assignment-exercise.ipynb | tuanavu/coursera-university-of-washington | mit |
To see what columns exist in that dataset and filter by, call the 'describe' method on a dataset from above: | nasdaq.describe('cx_hits') | examples/TickVault_NasdaqCx_Example1.ipynb | TickSmith/tickvault-python-api | mit |
To access the bid and ask prices for TD quotes when the ask and bid sizes were greater than 10, we will query the HiTS dataset (and print its length to make sure we got results): | result = nasdaq.query_hits(source="CHIX", tickers="TD",
fields="ts,askprice,bidprice", start_time=20150302093000, end_time=20150302160000,
predicates="ask_size > 10 and bid_size > 10 and line_type like Q",
limit=1000000)
str(len(result)) | examples/TickVault_NasdaqCx_Example1.ipynb | TickSmith/tickvault-python-api | mit |
Let's convert the result to a pandas DataFrame for analytics: | df = nasdaq.as_dataframe(result)
df.info() | examples/TickVault_NasdaqCx_Example1.ipynb | TickSmith/tickvault-python-api | mit |
Now to visualise the result: | %matplotlib inline
df.plot() | examples/TickVault_NasdaqCx_Example1.ipynb | TickSmith/tickvault-python-api | mit |
3. Affine Decomposition | @ExactParametrizedFunctions()
class NavierStokes(NavierStokesProblem):
# Default initialization of members
def __init__(self, V, **kwargs):
# Call the standard initialization
NavierStokesProblem.__init__(self, V, **kwargs)
# ... and also store FEniCS data structures for assembly
... | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4. Main program
4.1. Read the mesh for this problem
The mesh was generated by the data/generate_mesh.ipynb notebook. | mesh = Mesh("data/backward_facing_step.xml")
subdomains = MeshFunction("size_t", mesh, "data/backward_facing_step_physical_region.xml")
boundaries = MeshFunction("size_t", mesh, "data/backward_facing_step_facet_region.xml") | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.2. Create Finite Element Space (Taylor-Hood P2-P1) | element_u = VectorElement("Lagrange", mesh.ufl_cell(), 2)
element_p = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
element = MixedElement(element_u, element_p)
V = FunctionSpace(mesh, element, components=[["u", "s"], "p"]) | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.3. Allocate an object of the NavierStokes class | problem = NavierStokes(V, subdomains=subdomains, boundaries=boundaries)
mu_range = [(1.0, 80.0)]
problem.set_mu_range(mu_range) | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.4. Prepare reduction with a POD-Galerkin method | reduction_method = PODGalerkin(problem)
reduction_method.set_Nmax(10) | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.5. Perform the offline phase | lifting_mu = (1.0,)
problem.set_mu(lifting_mu)
reduction_method.initialize_training_set(100, sampling=EquispacedDistribution())
reduced_problem = reduction_method.offline() | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.6. Perform an online solve | online_mu = (80.0,)
reduced_problem.set_mu(online_mu)
reduced_solution = reduced_problem.solve()
plot(reduced_solution, reduced_problem=reduced_problem, component="u")
plot(reduced_solution, reduced_problem=reduced_problem, component="p") | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.7. Perform an error analysis | reduction_method.initialize_testing_set(16, sampling=EquispacedDistribution())
reduction_method.error_analysis() | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.8. Perform a speedup analysis | reduction_method.speedup_analysis() | tutorials/17_navier_stokes/tutorial_navier_stokes_1_exact.ipynb | mathLab/RBniCS | lgpl-3.0 |
Figure: The two Theis curves caused by delayed yield
We see that the blue curve is equal to the red one but shifted exactly a factor $S_y/S_e = 100$ to the right, i.e. it is delayed by a factor $S_y/S_e$.
Therefore, in an unconfined aquifer with some vertical resistance, we expect the drawdown to initially follow the r... | import csv
import wells
W = wells.W # Theis
Wh = wells.Wh # Hantush
# Global info and prefrences for this project
proj = "Pumping test at St. Pardon de Conques (1965)"
folder = './ptestDelayed'
p_names = 'ptst02', 'ptst10', 'ptst30'
l_names = 'semilog02_late', 'semilog10_late', 'semilog30_late', 'semilog10_ear... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Next we define a class piezometer, that allows us to store information pertaining to individual piezometers, so that we can easily plot them, use their data together with their meta data. Defining such a class prevents clutter. It's always to good idea to define a class or a function when this prevents duplicating code... | class Piezometer:
"""Piezometer definition"""
clrs ='brgkmcy'
styles = ['-',';','--','-.']
markers = ['o','s','^','v','p','+','x','.']
c_cnt = -1
l_cnt = -1
m_cnt = -1
def __init__(self, name="", t=np.array([]), s=np.array([]),
dim_t='s', dim_s='m', c... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
The function invK0 defined below is the inverse of the K0 bessel function. It takes the value of K0(z) and computes z. To do this, Newton Raphson iterations are used. Look up the Newton Raphson method on the internet (Wikipedia), if you don't know it. It's a basic numerical method. | def invK0(K0, tol=1e-6, verbose=False):
"Return x if K0(x) is given (Newton Raphson)"
x = tol
for i in range(100):
f = K0 - k0(x)
facc = k1(x)
x = x - f/facc
if verbose:
print("{:3d} {:10.3g} {:10.3g}".format(i, x, f/facc))
if np.abs(f/facc) < tol:
... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
The next function reads in the data for all piezometers and returns a list of piezometer objects, that is, objects of the class defined above. | def get_data(folder, names, linestyle=None, marker=None):
"Reads in the data, returns them as a list of class Piezometer"
piezoms = []
for name in names:
p = Piezometer(name=name)
fName = folder + '/' + name + '.csv'
with open(fName) as csvfile:
datareader = csv.reade... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Now read the data, returning the piezometers in a list, called "piezoms".
After that show the lines on a semilog graph, firrst as they are read and then together with the best linear approximation. | # reads piezometers
piezoms = get_data(folder, p_names, linestyle='', marker='o')
# get straight lines drawn through piezometer data
piezlines = get_data(folder, l_names, linestyle='-', marker='')
# Show the data
# Double log scale
ax1 = plt.figure().add_subplot(111)
ax1.set(**pltset0)
ax1.grid(True)
for p in pi... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Intepretation of the pumping test
The data on double log scales should reveal a picture of the delayed type curves. The first part of the lines should mimic Theis, the mediate part should tend to a horizontal line as predicts the Hantush' type curves and the last part should also mimic the later part of a Theis curve. ... | # compute it all
def all(author, proj, t0, s, ds, sig, D=8.24, Q=53., r=10.):
sph = 3600.
t0 = t0/sph # [h]
kD = Q / (4 * np.pi) * np.log(10) / ds
Sy = 2.25 * kD * t0 / r**2
Se = Sy / sig
besK0 = 2 * np.pi * kD * s / Q
Lam = r / invK0(besK0)
beta = (r/Lam)**2 # (r/lambda)*... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
The essential difference between the results of Neuman (using the semilog method) and the indipendently derived figures, is the steady state drawdown, i.e. the Hantush case, that would pertain to the situation in which the water table would be fixed by continuous additional supply of water. That figure is difficult to ... | #def plotResult(author, proj, Q, r, Lam, c, kD, Sy, Se, t, plotset):
def plotResult(author, proj, Q, r, D, kr, kz, c, Sy, Se, t, plotset):
kD = kr * D
Lam = np.sqrt(kD * c)
ue = r**2 *Se /(4 * kD * t)
uy = r**2 *Sy /(4 * kD * t)
sh = Q/ (4 * np.pi * kD) * Wh(ue, r/Lam)
se = Q/ (4 * n... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
In conclusion, the curves analysed here deviate little from the measurements. We had to approximate the steady-state drawdown without delayed yield, to obtain a value for $ r/\lambda $. The value chosen was 0.22 m, whereas the value that follows from the results of Neuman would be .28 m, corresponding to the horizontal... | modules = '/Users/Theo/GRWMODELS/Python_projects/mfpy/modules/'
import sys
if not modules in sys.path:
sys.path.insert(0, modules)
import mfgrid as grid
import fdm_t
# author, r, Q, D, kr, kz, c, Sy, Se
t = np.logspace(-1, 6, 71)
ax3 = plt.figure().add_subplot(111)
ax4 = plt.figure().add_subplot(111)
def n... | exercises_notebooks/DelayedYield.ipynb | Olsthoorn/TransientGroundwaterFlow | gpl-3.0 |
Pendulum
This notebook solves the Spider-Man problem from spiderman.ipynb, demonstrating a different development process for physical simulations.
In pendulum_sympy, we derive the equations of motion for a rigid pendulum without drag, yielding:
$ \ddot{x} = \frac{x}{x^{2} + y^{2}} \left(g y - vx^{2} - vy^{2}\right) $
$... | condition = Condition(g = 9.8,
m = 75,
area = 1,
rho = 1.2,
v_term = 60,
duration = 30,
length0 = 100,
angle = (270 - 45),
k = 20) | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Now here's a version of make_system that takes a Condition object as a parameter.
make_system uses the given value of v_term to compute the drag coefficient C_d. | def make_system(condition):
"""Makes a System object for the given conditions.
condition: Condition with height, g, m, diameter,
rho, v_term, and duration
returns: System with init, g, m, rho, C_d, area, and ts
"""
unpack(condition)
theta = np.deg2rad(angle)
... | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Let's make a System | system = make_system(condition)
system
system.init | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
To write the slope function, we can get the expressions for ax and ay directly from SymPy and plug them in. | def slope_func(state, t, system):
"""Computes derivatives of the state variables.
state: State (x, y, x velocity, y velocity)
t: time
system: System object with length0, m, k
returns: sequence (vx, vy, ax, ay)
"""
x, y, vx, vy = state
unpack(system)
ax = x*(g*y - vx**2 - v... | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
And then run the simulation. | %time run_odeint(system, slope_func) | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Visualizing the results
We can extract the x and y components as Series objects. | xs = system.results.x
ys = system.results.y | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
The simplest way to visualize the results is to plot x and y as functions of time. | newfig()
plot(xs, label='x')
plot(ys, label='y')
decorate(xlabel='Time (s)',
ylabel='Position (m)') | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
We can plot the velocities the same way. | vxs = system.results.vx
vys = system.results.vy
newfig()
plot(vxs, label='vx')
plot(vys, label='vy')
decorate(xlabel='Time (s)',
ylabel='Velocity (m/s)') | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Another way to visualize the results is to plot y versus x. The result is the trajectory through the plane of motion. | newfig()
plot(xs, ys, label='trajectory')
decorate(xlabel='x position (m)',
ylabel='y position (m)') | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
We can also animate the trajectory. If there's an error in the simulation, we can sometimes spot it by looking at animations. | newfig()
decorate(xlabel='x position (m)',
ylabel='y position (m)',
xlim=[-100, 100],
ylim=[-200, -50],
legend=False)
for x, y in zip(xs, ys):
plot(x, y, 'bo', update=True)
sleep(0.01) | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Here's a function that encapsulates that code and runs the animation in (approximately) real time. | def animate2d(xs, ys, speedup=1):
"""Animate the results of a projectile simulation.
xs: x position as a function of time
ys: y position as a function of time
speedup: how much to divide `dt` by
"""
# get the time intervals between elements
ts = xs.index
dts = np.diff(ts)
d... | notebooks/pendulum2.ipynb | AllenDowney/ModSimPy | mit |
Problem 1
Write a function that returns a list of numbers, such that $x_i=i^2$, for $1\leq i \leq n$. Make sure it handles the case where $n<1$ by raising a ValueError. | def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
{% if solution %}
if n < 1:
raise ValueError("n must be greater than or equal to 1")
return [i ** 2 for i in xrange(1, n + 1)]
{% else %}
# YOUR COD... | examples/create_assignment/Assignment Template.ipynb | jhamrick/original-nbgrader | mit |
Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] for $n=10$. Check that it does: | squares(10)
"""Check that squares returns the correct output for several inputs"""
from nbgrader.tests import assert_equal
assert_equal(squares(1), [1])
assert_equal(squares(2), [1, 4])
assert_equal(squares(10), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100])
assert_equal(squares(11), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 12... | examples/create_assignment/Assignment Template.ipynb | jhamrick/original-nbgrader | mit |
Problem 2
Part A
Using your squares function, write a function that computes the sum of the squares of the numbers from 1 to $n$. Your function should call the squares function -- it should NOT reimplement its functionality. | def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
{% if solution %}
return sum(squares(n))
{% else %}
# YOUR CODE HERE
raise NotImplementedError
{% endif %} | examples/create_assignment/Assignment Template.ipynb | jhamrick/original-nbgrader | mit |
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get: | sum_of_squares(10)
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert_equal(sum_of_squares(1), 1)
assert_equal(sum_of_squares(2), 5)
assert_equal(sum_of_squares(10), 385)
assert_equal(sum_of_squares(11), 506)
"""Check that sum_of_squares relies on squares."""
orig_squares = squares
... | examples/create_assignment/Assignment Template.ipynb | jhamrick/original-nbgrader | mit |
Part B
Using LaTeX math notation, write out the equation that is implemented by your sum_of_squares function.
{% if solution %}
$\sum_{i=1}^n i^2$
{% else %}
YOUR ANSWER HERE
{% endif %}
Part C
Create a plot of the sum of squares for $n=1$ to $n=15$. Make sure to appropriately label the $x$-axis and $y$-axis, and to gi... | fig, ax = plt.subplots() # do not delete this line!
{% if solution %}
x = range(1, 16)
y = [sum_of_squares(x[i]) for i in xrange(len(x))]
ax.plot(x, y)
ax.set_title("Sum of squares from 1 to $n$")
ax.set_xlabel("$n$")
ax.set_ylabel("sum")
ax.set_xlim([1, 15])
{% else %}
# YOUR CODE HERE
raise NotImplementedError
{% end... | examples/create_assignment/Assignment Template.ipynb | jhamrick/original-nbgrader | mit |
Extracting Data of Southeast states of the United states from 1992 - 2016.
The following query will extract data from the mongoDB instance and project only selected attributes such as structure number, yearBuilt, deck, year, superstructure, owner, countryCode, structure type, type of wearing surface, and subtructure. | def getData(state):
pipeline = [{"$match":{"$and":[{"year":{"$gt":1991, "$lt":2017}},{"stateCode":state}]}},
{"$project":{"_id":0,
"structureNumber":1,
"yearBuilt":1,
"yearReconstructed":1,
"deck":1, ## R... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southeast+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
The following script will select all the bridges in the Southeast United States, filter missing and not required data. The script also provides information of how much of the data is being filtered. | states = ['54','51','21','47','37','45','13','01','28','02','22','12']
# Mapping state code to state abbreviation
stateNameDict = {'25':'MA',
'04':'AZ',
'08':'CO',
'38':'ND',
'09':'CT',
'19':'IA',
'26':'MI',
... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southeast+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
In following figures, shows the cumulative distribution function of the probability of reconstruction over the bridges' lifespan, of bridges in the Southeast United States, as the bridges grow older the probability of reconstruction increases. | plt.figure(figsize=(12,8))
plt.title("CDF Probability of Reconstruction vs Age")
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
linestyles =[':','-.','--','-',':','-.','--','-',':','-.','--','-']
for num, state in enumerate(df_cumsum_p... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southeast+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
A key observation in this investigation of several state reveals a constant number of bridges are reconstructed every year, this could be an effect of fixed budget allocated for reconstruction by the state. This also highlights the fact that not all bridges that might require reconstruction are reconstructed.
To Unders... | plt.figure(figsize = (16,12))
plt.xlabel('Age')
plt.ylabel('Mean')
# Initialize the figure
plt.style.use('seaborn-darkgrid')
# create a color palette
palette = [
'blue', 'blue', 'green', 'magenta', 'cyan', 'brown', 'grey', 'red', 'silver', 'purple', 'gold', 'black','olive'
]
# multiple line plot
num = 1
linesty... | Bridge Life-Cycle Models/CDF+Probability+Reconstruction+vs+Age+of+Bridges+in+the+Southeast+United+States.ipynb | kaleoyster/nbi-data-science | gpl-2.0 |
Pandas es una librería orientada a objetos y los objetos más importantes que incluye son las Series y los DataFrames.
Series
Una serie es una colección de valores con un índice asociado. El índice puede ser numérico, nominal, fecha y hora, etc. y permite referenciar los datos de la serie por su índice.
Los siguientes s... | # Crear una seríe indicando la producción por mes
produccion = pd.Series( [120,130,110,150,170,180,170,160,190,175,160,141],
index=['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dec'] )
print(produccion)
# Crear una serie a partir de un diccionario
dict = { 'a':6.4, 'b':7.... | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Atributos y Métodos de las Series
Los siguientes son los atributos más importantes | # Número de elementos
pesos.size
# Forma (número de filas, columnas). En el caso de las series solo son filas
pesos.shape
# Tipo de datos que contiene la serie
pesos.dtype
# Los indices de la serie
pesos.index
# Los valores contenidos en la serie
pesos.values
## Acceso a los elementos de la serie | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Los elementos de una serie se acceden de forma similar a los de una lista. Se pueden usar los índices de la serie, o la posición de los elementos, por ejemplo: | pesos['a']
# o usando el metodo .get
pesos.get('a')
pesos[0]
pesos['b':'e']
pesos[1:5]
pesos[:'c']
pesos[:3]
pesos['d':]
pesos[3:] | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
También se puede seleccionar un subconjunto de índices o posiciones particular | pesos[ ['b','e','c'] ]
pesos[ [1,4,2] ] | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Indexado lógico
La indexación lógica permite obtener los elementos de la serie que cumplen con una condición lógica | pesos[ pesos>7 ] | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Se puede comprobar si un determinado indice está presente en la serie | 'a' in pesos
'h' in pesos
'Sep' in produccion
# Asignar valor a un indice
pesos.at['a'] = 5.0
pesos[0]
# Esta vacia la serie
pesos.empty
# Crear una serie vacia
volumenes = pd.Series()
volumenes.empty | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Eliminar elementos de una Series
Se pueden eliminar elementos por medio del método .drop e indicando los índices a eliminar | pesos.drop(['e','c']) | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
De particular interes son casos en los que la serie contiene elementos nulos (NaN). Todos los elementos nulos se pueden eliminar con el método .dropna | # Hacer una copia de la Series
pesos2 = pesos.copy()
# Hacer nulos algunos de sus elementos
pesos2.at['b'] = None
pesos2
pesos2.dropna() | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Métodos para comprobar una condición lógica sobre todos los elementos de una Series | # Comprobar si todos/algunos elementos de la serie cumplen una condición lógica
(pesos>5).all()
(pesos<5).any()
# Indice correspondiente al mayor/menor valor de la serie
pesos.argmax()
pesos.argmin()
# Convertir a matriz de numpy
x = pesos.as_matrix()
print(x)
print(type(x))
# Estadísticas descriptivas de la serie... | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Operadores aritméticos
Todas las operaciones aritméticas entre series se hacen alineando los indices de las series. Las operaciones se pueden realizar utilizando los métodos .add .sub .mul .div .pow .dot .abs .mod o los correspondientes operadores sobrecargados. Indices no presentes se asumen NaN (Not a Number) | # Crear una nueva serie
medidas = pd.Series({ 'b':6.1, 'c':8.2, 'd':7.3, 'e':5.4, 'f':6.5, 'h':3.2 })
print("pesos\n", pesos)
print("\nmedidas\n",medidas)
pesos.add(medidas)
pesos+medidas
pesos-medidas
pesos*medidas
pesos/medidas | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Operadores relacionales
Se cuenta asi mismo con los métodos relacionales estándar .lt .le .gt .ge .eq .ne o sus correspondientes operadores sobrecargados < <= > >= == !=. Solo son aplicables a series de igual longitud (no es oblogatorio que coincidan los índices). | medidas.at['a']=1.
pesos.size, medidas.size
pesos<medidas
pesos.eq(medidas)
pesos!=medidas
pesos.ge(medidas)
# Comprobar si alguno de los elementos es nulo
pesos.isnull() | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
También se cuenta con las operaciones estádisticas comunes: .count .sum .min .max .mean .var .std .median .mode .cov .corr .autocorr .sem | pesos.count(), pesos.sum(), pesos.mean(), pesos.median() | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Se puede ordernar la serie por valores o por indices, en orden creciente o decreciente | pesos.sort_values()
pesos.sort_index(ascending=False) | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
Operaciones de entrada/salida | # Salvar la serie en un archivo
pesos.to_csv('pesos.csv')
# Leer la serie de un archivo
copia = pd.read_csv('pesos.csv', squeeze=True, index_col=0, header=None)
copia
# Graficar la serie
import matplotlib.pyplot as plt
pesos.plot()
plt.show()
# Obtener su histograma
pesos.hist()
plt.show() | pandas/PandasSeries.ipynb | jmlon/PythonTutorials | gpl-3.0 |
In the beginning we need to instantiate two objects in the main file to run the program -
from src.environment import Environment
from src.runner import Runner
the Environment and the Runner class. The code for those classes are stored in the folder src and the name of the classes are Environment and Runner (not s... | # %load configs/agents/hf/hf.xml
<agent identifier="HF">
<parameter type="stock_variables" name="GB" value="40"></parameter>
<parameter type="stock_variables" name="CB" value="20"></parameter>
<parameter type="stock_variables" name="Cash" value="10"></parameter>
<parameter type="stock_variables" name="does_repo" valu... | examples/firesales_SA/.ipynb_checkpoints/Python code Toy model-checkpoint.ipynb | cogeorg/black_rhino | gpl-3.0 |
Those type " " names later become dictionaries for the instantiated agent object. So the hedge fund has
a dictionary (a data structure that saves stuff) with the name stock_variable = {Cash: 20, GB: 40, CB: 20, does_repo = 'yes'} When I write the results to csv, I iterate over those variables.
You can define addition... | # %load configs/environment/environment_config.xml
<environment identifier='toy_test'>
<!-- simulation parameters -->
<parameter type='static' name='num_sweeps' value='10'></parameter>
<parameter type='static' name='num_simulations' value='1'></parameter>
<parameter type='static' name='cbank_directory' value='con... | examples/firesales_SA/.ipynb_checkpoints/Python code Toy model-checkpoint.ipynb | cogeorg/black_rhino | gpl-3.0 |
Here you can change the initital interest rates and prices for the marketable assets and also the shocks. It's possible to assign them to other variables and change them later in the updater. It's also possible to not read them in at all (just delete the lines) and define those in the updater script, but in the current... | # -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# class Updater
# -------------------------------------------------------------------------
import numpy as np
class Updater():
#
#
# METHODS
#
def get_identifier(self):
return self.ident... | examples/firesales_SA/.ipynb_checkpoints/Python code Toy model-checkpoint.ipynb | cogeorg/black_rhino | gpl-3.0 |
Now let's set up REBOUNDx and add radiation_forces. We also have to set the speed of light in the units we want to use. | rebx = reboundx.Extras(sim)
rf = rebx.load_force("radiation_forces")
rebx.add_force(rf)
rf.params["c"] = 3.e8 | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
By default, the radiation_forces effect assumes the particle at index 0 is the source of the radiation. If you'd like to use a different one, or it's possible that the radiation source might move to a different index (e.g. with a custom merger routine), you can add a radiation_source flag to the appropriate particle l... | ps["Sun"].params["radiation_source"] = 1 | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
Here we show how to add two dust grains to the simulation in different ways. Let's first initialize their orbits. In both cases we use the orbital elements of Saturn's irregular satellite Phoebe, which the dust grains will inherit upon release (Tamayo et al. 2011). Since the dust grains don't interact with one anoth... | a = 1.3e10 # in meters
e = 0.16
inc = 175*np.pi/180.
Omega = 0. # longitude of node
omega = 0. # argument of pericenter
f = 0. # true anomaly
# Add two dust grains with the same orbit
sim.add(primary=ps["Saturn"], a=a, e=e, inc=inc, Omega=Omega, omega=omega, f=f, hash="p1")
sim.add(primary=ps["Saturn"], a=a, e=e, inc=... | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
Now we add the grains' physical properties. In order for particles to feel radiation forces, we have to set their beta parameter. $\beta$ is tha ratio of the radiation force to the gravitational force from the star (Burns et al. 1979). One can either set it directly: | ps["p1"].params["beta"] = 0.01 | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
or we can calculate it from more fundamental parameters. REBOUNDx has a convenience function that takes the gravitional constant, speed of light, radiation source's mass and luminosity, and then the grain's physical radius, bulk density, and radiation pressure coefficient Q_pr (Burns et al. 1979, equals 1 in the limit... | grain_radius = 1.e-5 # grain radius in m
density = 1000. # kg/m^3 = 1g/cc
Q_pr = 1.
luminosity = 3.85e26 # Watts
ps["p2"].params["beta"] = rebx.rad_calc_beta(sim.G, rf.params["c"], ps[0].m, luminosity, grain_radius, density, Q_pr)
print("Particle 2's beta parameter = {0}".format(ps["p2"].params["beta"])) | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
Now let's run for 100 years (about 3 Saturn orbits), and look at how the eccentricity varies over a Saturn year: | yr = 365*24*3600 # s
Noutput = 1000
times = np.linspace(0,100.*yr, Noutput)
e1, e2 = np.zeros(Noutput), np.zeros(Noutput)
sim.move_to_com() # move to center of mass frame first
for i, time in enumerate(times):
sim.integrate(time)
e1[i] = ps["p1"].calculate_orbit(primary=ps["Saturn"]).e
e2[i] = ps["p2"].ca... | ipython_examples/Radiation_Forces_Circumplanetary_Dust.ipynb | hannorein/reboundx | gpl-3.0 |
Getting the Pre-Trained Models and Data | DATA_DIR = ('http://github.com/hardmaru/sketch-rnn-datasets/'
'raw/master/aaron_sheep/')
MODELS_ROOT_DIR = '/tmp/sketch_rnn/models'
DATA_DIR
PRETRAINED_MODELS_URL
download_pretrained_models(
models_root_dir=MODELS_ROOT_DIR,
pretrained_models_url=PRETRAINED_MODELS_URL) | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
We look at the layer normalized model trained on the aaron_sheep dataset for now. | MODEL_DIR = MODELS_ROOT_DIR + '/aaron_sheep/layer_norm'
(train_set,
valid_set,
test_set,
hps_model,
eval_hps_model,
sample_hps_model) = load_env(DATA_DIR, MODEL_DIR)
class SketchPath(Path):
def __init__(self, data, factor=.2, *args, **kwargs):
vertices = np.cumsum(data[::, :-1], ax... | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
The real fun begins
Everything up to here has more or less been copied straight from the previous notebook. Now we load the pre-trained SketchRNN model and use it to begin our exploration of the test dataset. | # construct the sketch-rnn model here:
reset_graph()
model = Model(hps_model)
eval_model = Model(eval_hps_model, reuse=True)
sample_model = Model(sample_hps_model, reuse=True)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
# loads the weights from checkpoint into our model
load_checkpoint(... | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
The helper functions for encoding a sketch to some latent code $z$ and then decoding it back to a sketch were provided in the original notebook. I just made some minor syntactic changes and removed the behaviour of plotting as a side-effect. | def encode(input_strokes):
strokes = to_big_strokes(input_strokes).tolist()
strokes.insert(0, [0, 0, 1, 0, 0])
seq_len = [len(input_strokes)]
z = sess.run(eval_model.batch_z,
feed_dict={
eval_model.input_data: [strokes],
eval_model.sequence_lengt... | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
Now we get a random sample from the test dataset | sketch = test_set.random_sample()
fig, ax = plt.subplots(figsize=(3, 3),
subplot_kw=dict(xticks=[],
yticks=[],
frame_on=False))
draw(sketch, ax=ax)
plt.show() | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
We project it into the 128-dimensional latent space using the pre-trained encoder | z = encode(sketch)
z.shape | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
Now we can reconstruct the original sketch from the learned latent representation using the pre-trained decoder, with temperature $\tau=0.8$. The temperature parameter controls the level of randomness in the samples generated by the model, which becomes deterministic as $\tau \to 0$, and produces samples that are the m... | sketch_reconstructed = decode(z, temperature=.6)
sketch_reconstructed.shape
fig, ax = plt.subplots(figsize=(3, 3),
subplot_kw=dict(xticks=[],
yticks=[],
frame_on=False))
draw(sketch_reconstructed, ax=ax)
plt.show() | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
Variance in the Reconstruction
The grid of drawings below consists of samples of the reconstructed drawings at various settings of the temperature parameter. The first column is the original drawing, and each of the remaining columns are 5 samples of the reconstructed drawing with $\tau$ increasing from 0.1 to 0.9. | fig, ax_arr = plt.subplots(nrows=5,
ncols=10,
figsize=(8, 4),
subplot_kw=dict(xticks=[],
yticks=[],
frame_on=False))
fig.tight_layout()
for row_num, a... | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
At the lowest setting of the temperature at $\tau=0.1$, we see the samples consistently share a similar appearance - they all look like vertical strokes emanating from a fluffy cloud. However, they are also consistently dissimilar to the original sketch. In this sense, the samples from the models seems to exhibit high ... | fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(6, 3),
subplot_kw=dict(xticks=[],
yticks=[]))
fig.tight_layout()
x_pad, y_pad = 10, 10
x_pad //= 2
y_pad //= 2
(x_min_1,
x_max_1,
y_min_1,
y_max_1) = get_bounds(data=sketch... | exploring-the-google-quickdraw-dataset-with-sketchrnn-part-2.ipynb | ltiao/notebooks | mit |
This creates a new array of points that are the values of $\sin(x_i)$ at each point $x_i$: | f = np.sin(x)
f
plt.plot(x, f, marker='o')
plt.xlabel('x')
plt.ylabel('f(x)'); | days/day11/Interpolation.ipynb | bjshaw/phys202-2015-work | mit |
Build 2d arrays to use in computing the function on the grid points: | X, Y = np.meshgrid(x, y)
Z = wave2d(X, Y)
X | days/day11/Interpolation.ipynb | bjshaw/phys202-2015-work | mit |
Define the placeholders and variables for the CNN model: | x = tf.placeholder(tf.float32, [None, 24 * 24])
y = tf.placeholder(tf.float32, [None, len(names)])
W1 = tf.Variable(tf.random_normal([5, 5, 1, 64]))
b1 = tf.Variable(tf.random_normal([64]))
W2 = tf.Variable(tf.random_normal([5, 5, 64, 64]))
b2 = tf.Variable(tf.random_normal([64]))
W3 = tf.Variable(tf.random_normal([6*6... | ch09_cnn/Concept03_cnn.ipynb | BinRoot/TensorFlow-Book | mit |
Define helper functions for the convolution and maxpool layers: | def conv_layer(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
conv_with_b = tf.nn.bias_add(conv, b)
conv_out = tf.nn.relu(conv_with_b)
return conv_out
def maxpool_layer(conv, k=2):
return tf.nn.max_pool(conv, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') | ch09_cnn/Concept03_cnn.ipynb | BinRoot/TensorFlow-Book | mit |
The CNN model is defined all within the following method: | def model():
x_reshaped = tf.reshape(x, shape=[-1, 24, 24, 1])
conv_out1 = conv_layer(x_reshaped, W1, b1)
maxpool_out1 = maxpool_layer(conv_out1)
norm1 = tf.nn.lrn(maxpool_out1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)
conv_out2 = conv_layer(norm1, W2, b2)
norm2 = tf.nn.lrn(conv_out2, 4, bias... | ch09_cnn/Concept03_cnn.ipynb | BinRoot/TensorFlow-Book | mit |
Here's the cost function to train the classifier. | model_op = model()
cost = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=model_op, labels=y)
)
train_op = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(model_op, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) | ch09_cnn/Concept03_cnn.ipynb | BinRoot/TensorFlow-Book | mit |
Let's train the classifier on our data: | with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
onehot_labels = tf.one_hot(labels, len(names), on_value=1., off_value=0., axis=-1)
onehot_vals = sess.run(onehot_labels)
batch_size = len(data) // 200
print('batch size', batch_size)
for j in range(0, 1000):
avg_accur... | ch09_cnn/Concept03_cnn.ipynb | BinRoot/TensorFlow-Book | mit |
You would like a classifier to separate the blue dots from the red dots.
1 - Neural Network model
You will use a 3-layer neural network (already implemented for you). Here are the initialization methods you will experiment with:
- Zeros initialization -- setting initialization = "zeros" in the input argument.
- Random... | def model(X, Y, learning_rate = 0.01, num_iterations = 15000, print_cost = True, initialization = "he"):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (2, number of examples)
Y -- true "label" vector (containing 0 ... | deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb | diegocavalca/Studies | cc0-1.0 |
2 - Zero initialization
There are two types of parameters to initialize in a neural network:
- the weight matrices $(W^{[1]}, W^{[2]}, W^{[3]}, ..., W^{[L-1]}, W^{[L]})$
- the bias vectors $(b^{[1]}, b^{[2]}, b^{[3]}, ..., b^{[L-1]}, b^{[L]})$
Exercise: Implement the following function to initialize all parameters to z... | # GRADED FUNCTION: initialize_parameters_zeros
def initialize_parameters_zeros(layers_dims):
"""
Arguments:
layer_dims -- python array (list) containing the size of each layer.
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td>
**W1**
</td>
<td>
[[ 0. 0. 0.]
[ 0. 0. 0.]]
</td>
</tr>
<tr>
<td>
**b1**
</td>
<td>
[[ 0.]
[ 0.]]
</td>
</tr>
<tr>
<td>
**W2**
</td>
<td>
[[ 0. 0.]]
</td>
</tr>
<tr>... | parameters = model(train_X, train_Y, initialization = "zeros")
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | deep-learnining-specialization/2. improving deep neural networks/week1/Initialization.ipynb | diegocavalca/Studies | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.