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 |
|---|---|---|---|---|---|
Question 5**5.** Now we would like to find out if the proportion of individuals who completed one of these three programs feel differently than those that did not. Store a dataframe of only the individual's who had **HigherEd** equal to 1 in **ed_1**. Similarly, store a dataframe of only the **HigherEd** equal to 0 v... | ed_1 = df[df['HigherEd'] == 1] # Subset df to only those with HigherEd of 1
ed_0 = df[df['HigherEd'] == 0] # Subset df to only those with HigherEd of 0
print(ed_1['HigherEd'][:5]) #Assure it looks like what you would expect
print(ed_0['HigherEd'][:5]) #Assure it looks like what you would expect
#Check your subset is ... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Question 6**6.** What can you conclude from the above plot? Change the dictionary to mark **True** for the keys of any statements you can conclude, and **False** for any of the statements you cannot conclude. | sol = {'Everyone should get a higher level of formal education': False,
'Regardless of formal education, online courses are the top suggested form of education': True,
'There is less than a 1% difference between suggestions of the two groups for all forms of education': False,
'Those with higher f... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Welcome to first_nbdev> this is my first attempt at the nbdev tutorial This file will become your README and also the index of your documentation. Install `pip install nbdev_first` How to use this module has one function: `say_hello`. It takes a string which is ideally the name of an individual. | say_hello("Joe") | _____no_output_____ | Apache-2.0 | index.ipynb | josephsmann/first_nbdev |
Reading and writing LAS filesThis notebook goes with [the Agile blog post](https://agilescientific.com/blog/2017/10/23/x-lines-of-python-load-curves-from-las) of 23 October.Set up a `conda` environment with: conda create -n welly python=3.6 matplotlib=2.0 scipy pandasYou'll need `welly` in your environment: cond... | import welly
ls ../data/*.LAS | [31m../data/P-129_out.LAS[m[m*
| Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
1. Load the LAS file with `lasio` | import lasio
l = lasio.read('../data/P-129.LAS') # Line 1. | Found nonstandard LAS section: ~Parameter
| Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
That's it! But the object itself doesn't tell us much — it's really just a container: | l | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
2. Look at the WELL section of the header | l.header['Well'] # Line 2. | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
3. Look at the curve data The curves are all present one big NumPy array: | l.data | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
Or we can go after a single curve object: | l.curves.GR # Line 3. | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
And there's a shortcut to its data: | l['GR'] # Line 4. | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
...so it's easy to make a plot against depth: | import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(15,3))
plt.plot(l['DEPT'], l['GR'])
plt.show() | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
4. Inspect the curves as a `pandas` dataframe | l.df().head() # Line 5. | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
5. Load the LAS file with `welly` | from welly import Well
w = Well.from_las('../data/P-129.LAS') # Line 6. | Found nonstandard LAS section: ~Parameter
| Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
`welly` Wells know how to display some basics: | w | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
And the `Well` object also has `lasio`'s access to a pandas DataFrame: | w.df().head() | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
6. Look at `welly`'s Curve objectLike the `Well`, a `Curve` object can report a bit about itself: | gr = w.data['GR'] # Line 7.
gr | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
One important thing about Curves is that each one knows its own depths — they are stored as a property called `basis`. (It's not actually stored, but computed on demand from the start depth, the sample interval (which must be constant for the whole curve) and the number of samples in the object.) | gr.basis | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
7. Plot part of a curveWe'll grab the interval from 300 m to 1000 m and plot it. | gr.to_basis(start=300, stop=1000).plot() # Line 8. | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
8. Smooth a curveCurve objects are, fundamentally, NumPy arrays. But they have some extra tricks. We've already seen `Curve.plot()`. Using the `Curve.smooth()` method, we can easily smooth a curve, eg by 15 m (passing `samples=True` would smooth by 15 samples): | sm = gr.smooth(window_length=15, samples=False) # Line 9.
sm.plot() | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
9. Export a set of curves as a matrixYou can get at all the data through the lasio `l.data` object: | print("Data shape: {}".format(w.las.data.shape))
w.las.data | Data shape: (12718, 25)
| Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
But we might want to do some other things, such as specify which curves you want (optionally using aliases like GR1, GRC, NGC, etc for GR), resample the data, or specify a start and stop depth — `welly` can do all this stuff. This method is also wrapped by `Project.data_as_matrix()` which is nice because it ensures tha... | w.data.keys()
keys=['CALI', 'DT', 'DTS', 'RHOB', 'SP']
w.plot(tracks=['TVD']+keys)
X, basis = w.data_as_matrix(keys=keys, start=275, stop=1850, step=0.5, return_basis=True)
w.data['CALI'].shape | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
So CALI had 12,718 points in it... since we downsampled to 0.5 m and removed the top and tail, we should have substantially fewer points: | X.shape
plt.figure(figsize=(15,3))
plt.plot(X.T[0])
plt.show() | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
10+. BONUS: fix the lat, lonOK, we're definitely going to go over our budget on this one.Did you notice that the location of the well did not get loaded properly? | w.location | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
Let's look at some of the header: LAS format log file from PETREL Project units are specified as depth units ================================================================== ~Version information VERS. 2.0: WRAP. YES: ================================================================== ~WEL... | import re
def transform_ll(text):
"""
Parses malformed lat and lon so they load properly.
"""
def callback(match):
d = match.group(1).strip()
m = match.group(2).strip()
s = match.group(3).strip()
c = match.group(4).strip()
if c.lower() in ('w', 's') and d[0] != '... | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
Make sure that works! | print(transform_ll("""Lat = 45* 12' 34.237" N"""))
remap = {
'LATI': 'LOC', # Use LOC for the parameter LATI.
'LONG': 'UWI', # Use UWI for the parameter LONG.
'LOC': None, # Use nothing for the parameter SECT.
'SECT': None, # Use nothing for the parameter SECT.
'RANG': None, # Use nothing f... | _____no_output_____ | Apache-2.0 | master/Read_and_write_LAS.ipynb | michael-scarn/geocomp-0118 |
DaKanjiRecognizer - Single Kanji CNN : Create dataset SetupImport the needed libraries. | #std lib
import sys
import os
import random
import math
import multiprocessing as mp
import gc
import time
import datetime
from typing import Tuple, List
from shutil import copy
from tqdm import tqdm
import tensorflow as tf
#reading the dataset
from etldr.etl_data_reader import ETLDataReader
from etldr.etl_character_... | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Loading the data The [ETL Character data set](http://etlcdb.db.aist.go.jp/) which I am using is a data set with multiple sub sets (ETL1 - ETL7, ETL8B, ETL8G, ETL9B and ETL9G). After unpacking the data set I renamed all folders and files to have a uniform naming scheme: "ETLX/ETLX_Y". "X" is the number of the subset an... | path = "Z:\data_sets\etlcdb_binary"
reader = ETLDataReader(path) | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Define a convenience function for showing characters and their label. | def show_image(img : np.array, label : str):
plt.figure(figsize=(2.2, 2.2))
plt.title(label=label, font=show_sample_font)
plt.axis("off")
plt.imshow(img.astype(np.float64), cmap="gray") | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Now load all samples which contain Kanji, Hiragana and Katakana. | types = [ETLCharacterGroups.kanji, ETLCharacterGroups.katakana, ETLCharacterGroups.hiragana]
x, y = reader.read_dataset_whole(types, 16)
print(x.shape, y.shape) | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
With the loaded data we can take a look at the class distributions. | unique, counts = np.unique(y, return_counts=True)
balance = dict(zip(unique, counts))
plt.bar(range(0, len(counts)), counts, width=1.0)
plt.show() | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Because the data is quite imbalanced we need more data.First remove samples so that a class has maximum 10all_jis2_charsamples. | del_inds, cnt = [], 0
for _x, _y in zip(x, y):
ind = np.where(unique == _y)
if(counts[ind] > 1000):
del_inds.append(cnt)
counts[ind] -= 1
cnt += 1
x = np.delete(x, del_inds, axis=0)
y = np.delete(y, del_inds)
unique, counts = np.unique(y, return_counts=True)
balance = dict(zip(uniqu... | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Save etlcdb images to disk To use the data later with keras we save them to disk in an appropriate folder structure. The ETL_data_reader package provides a handy function for this. | reader.save_to_file(x, y, r"Z:\data_sets\dakanji_single_kanji_cnn", name=0) | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Create samples for missing JIS-2 KanjiBecause not all JIS 2 characters are in the etlcdb we need to get samples for them. First find the characters which are in JIS2 but not in the data set. | chars_to_gen = {}
# add samples for the already existing classes
for u, c in zip(unique, counts):
if(c < 2000):
chars_to_gen[u] = 2000 - c
with open("jis2_characters.txt", encoding="utf8", mode="r") as f:
all_jis2_chars = f.read().replace(" ", "").replace("\n", "")
all_jis2_chars = list(all_ji... | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Copy samples from DaJapanaeseDataGenerator dataset | da_data_dir = r"Z:\data_sets\da_japanese_data_generator"
with open(os.path.join(da_data_dir, "encoding.txt"), encoding="utf8", mode="r") as f:
d = eval(f.read())
da_data_encoding = {v : k for k, v in d.items()}
single_kanji_data_dir = r"Z:\data_sets\dakanji_single_kanji_cnn"
with open(os.path.join(single_kanj... | _____no_output_____ | MIT | single_kanji_data_gen.ipynb | CaptainDario/DaKanjiRecognizer-ML |
Jupyter notebooksThis is a [Jupyter](http://jupyter.org/) notebook using Python. You can install Jupyter locally to edit and interact with this notebook. Finite difference methods for transient PDE Method of LinesOur method for solving time-dependent problems will be to discretize in space first, resulting in a syste... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn')
def ode_euler(f, u0, tfinal=1, h=0.1):
u = np.array(u0)
t = 0
thist = [t]
uhist = [u0]
while t < tfinal:
h = min(h, tfinal - t)
u += h * f(t, u)
t += h
thist.append(t)
... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Midpoint MethodWhat if instead of evaluating the function at the end of the time step, we evaluated in the middle of the time step using the average of the endpoint values.$$ \tilde u(h) = u(0) + h f\left(\frac h 2, \frac{\tilde u(h) + u(0)}{2} \right) $$For the linear problem, this reduces to$$ \Big(I - \frac h 2 A \... | def ode_midpoint_linear(A, u0, tfinal=1, h=0.1):
u = u0.copy()
t = 0
thist = [t]
uhist = [u0]
I = np.eye(len(u))
while t < tfinal:
h = min(h, tfinal - t)
u = np.linalg.solve(I - .5*h*A, (I + .5*h*A) @ u)
t += h
thist.append(t)
uhist.append(u.copy())
re... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
$\theta$ methodThe above methods are all special cases of the $\theta$ method$$ \tilde u(h) = u(0) + h f\left(\theta h, \theta\tilde u(h) + (1-\theta)u(0) \right) $$which, for linear problems, is solved as$$ (I - h \theta A) u(h) = \Big(I + h (1-\theta) A \Big) u(0) . $$$\theta=0$ is explicit Euler, $\theta=1$ is impl... | for theta in [.2, .5, .8]:
plot_stability(xx, yy, (1 + (1-theta)*zz)/(1 - theta*zz), '$\\theta={:3.1f}$'.format(theta)) | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
We will generalize slightly to allow solution of a linear differential algebraic equation$$ M \dot u = A u + f(t,x) $$where $M$ is (for now) a diagonal matrix that has zero rows at boundary conditions. With this generalization, the $\theta$ method becomes$$ (M - h \theta A) u(h) = \Big(M + h (1-\theta) A \Big) u(0) + ... | def dae_theta_linear(M, A, u0, rhsfunc, bcs=[], tfinal=1, h=0.1, theta=.5):
u = u0.copy()
t = 0
hist = [(t,u0)]
while t < tfinal:
if tfinal - t < 1.01*h:
h = tfinal - t
tnext = tfinal
else:
tnext = t + h
h = min(h, tfinal - t)
rhs = (M ... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Stiff decay to cosine | test = fcos(k=5000)
u0 = np.array([.2])
hist = dae_theta_linear(np.eye(1), -test.k, u0,
lambda t: test.k*np.cos(t),
h=.1, tfinal=6, theta=.5)
hist = np.array(hist)
plt.plot(hist[:,0], hist[:,1], 'o')
tt = np.linspace(0, 6, 200)
plt.plot(tt, test.u(tt,u0)); | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* $\theta=1$ is robust* $\theta=1/2$ gets correct long-term behavior, but has oscillations at early times* $\theta < 1/2$ allows oscillations to grow Definition: $A$-stabilityA method is $A$-stable if the stability region$$ \{ z : |R(z)| \le 1 \} $$contains the entire left half plane $$ \Re[z] \le 0 .$$Th... | %run fdtools.py # define cosspace, vander_chebyshev, and chebeval
def diffusion_cheb(n, left, right):
"""Solve the diffusion PDE on (-1,1) using n elements with rhsfunc(x) forcing.
The left and right boundary conditions are specified as a pair (deriv, func) where
* deriv=0 for Dirichlet u(x_endpoint) = ... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* Sharp central spike is diffused very quickly.* Artifacts with $\theta < 1$. Manufactured solution | class exact_tanh:
def __init__(self, k=1, x0=0):
self.k = k
self.x0 = x0
def u(self, t, x):
return np.tanh(self.k*(x - t - self.x0))
def u_x(self, t, x):
return self.k * np.cosh(self.k*(x - t - self.x0))**(-2)
def u_t(self, t, x):
return -self.u_x(t, x)
def u_... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* Errors are limited by time (not spatial) discretization error. This is a result of using the (spectrally accurate) Chebyshev method in space.* $\theta=1$ is more accurate than $\theta = 1/2$, despite the latter being second order accurate in time. This is analogous to the stiff relaxation to cosine tes... | def maxeig(n):
x, M, A, bcs = diffusion_cheb(n, (0, ex.u), (1, ex.u_x))
lam = np.linalg.eigvals(-A)
return max(lam)
plt.loglog(ns, [maxeig(n) for n in ns], 'o', label='cheb')
for p in range(1,5):
plt.loglog(ns, ns**(p), label='$n^{%d}$'%p)
plt.xlabel('n')
plt.ylabel('$\max \sigma(A)$')
plt.legend(loc='... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Finite difference method | def maxeig_fd(n):
dx = 2/n
A = 1/dx**2 * (2 * np.eye(n+1) - np.eye(n+1, k=1) - np.eye(n+1, k=-1))
return max(np.linalg.eigvals(A))
plt.loglog(2/ns, [maxeig_fd(n) for n in ns], 'o', label='fd')
for p in range(1,4):
plt.loglog(2/ns, 4*(2/ns)**(-p), label='$4 h^{-%d}$'%p)
plt.xlabel('h')
plt.ylabel('$\max... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Question: max explicit Euler time stepExpress the maximum stable time step $\Delta t$ using explicit Euler in terms of the grid spacing $\Delta x$. Hyperbolic (wave) equationsThe simplest hyperbolic equation is linear advection$$ \dot u(t,x) + c u'(t,x) = f(t,x) $$where $c$ is the wave speed and $f$ is a source term. ... | def advection_cheb(n, c, left=(None,None), right=(None,None)):
"""Discretize the advection PDE on (-1,1) using n elements with rhsfunc(x) forcing.
The left boundary conditions are specified as a pair (deriv, func) where
* deriv=0 for Dirichlet u(x_endpoint) = func(x_endpoint)
* deriv=1 for Neumann u... | [ 1.00000000e+00 -8.32667268e-17 -4.85722573e-17 0.00000000e+00
1.00613962e-16]
| BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* $\theta > 1/2$ causes decay in amplitude* $\theta < 1/2$ causes growth -- unstable* An undershoot develops behind the traveling wave and increasing resolution doesn't make it go away* We need an *upwind* boundary condition, otherwise the system is unstable* Only Dirichlet inflow conditions are appropriat... | def advection_fd(n, c, stencil=2, bias=0, left=None, right=None):
x = np.linspace(-1, 1, n+1)
A = np.zeros((n+1,n+1))
for i in range(n+1):
sleft = max(0, i - stencil//2 + bias)
sleft = min(sleft, n+1 - stencil)
A[i,sleft:sleft+stencil] = -c*fdstencil(x[i], x[sleft:sleft+stencil])[1]
... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* Centered methods have an undershoot behind the traveling wave* Upwind biasing of the stencil tends to reduce artifacts, but only `stencil=2` removes undershoots* Downwind biasing is usually unstable* With upwinded `stencil=2`, we can use an explicit integrator, but the time step must satisfy$$ c \Delta t... | x = np.arange(-1, 1+1)
s1 = fdstencil(0, x)[1]
print(s1)
theta = np.linspace(0, np.pi)
phi = np.exp(1j*np.outer(x, theta))
plt.plot(theta, np.sin(theta))
plt.plot(theta, np.abs(s1 @ phi), '.')
plt.plot(theta, theta); | [-0.5 0. 0.5]
| BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Runge-Kutta methodsThe methods we have considered thus far can all be expressed as Runge-Kutta methods, which are expressed in terms of $s$ "stage" equations (possibly coupled) and a completion formula. For the ODE$$ \dot u = f(t, u) $$the Runge-Kutta method is$$\begin{split}Y_i = u(t) + h \sum_j a_{ij} f(t+c_j h, Y_... | def Rstability(A, b, z):
s = len(b)
def R(z):
return 1 + z*b.dot(np.linalg.solve(np.eye(s) - z*A, np.ones(s)))
f = np.vectorize(R)
return f(z)
def rk_butcher_theta(theta):
A = np.array([[theta]])
b = np.array([1])
return A, b
def zmeshgrid(xlen=5, ylen=5):
xx = np.linspace(-xle... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Evidently the endpoint variant of $\theta$ has the same stability function as the original (midpoint) variant that we've been using. These methods are equivalent for linear problems, but different for nonlinear problems. Higher order explicit methods: Heun's and RK4Explicit Euler steps can be combined to create more a... | def rk_butcher_heun():
A = np.array([[0, 0],[1,0]])
b = np.array([.5, .5])
return A, b
A, b = rk_butcher_heun()
plot_rkstability(A, b, label='Heun')
def rk_butcher_4():
A = np.array([[0,0,0,0],[.5,0,0,0],[0,.5,0,0],[0,0,1,0]])
b = np.array([1/6, 1/3, 1/3, 1/6])
return A, b
A, b = rk_butcher_4(... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Finally a method with lots of stability along the imaginary axis. Let's try it on some test problems. | def ode_rkexplicit(f, u0, butcher=None, tfinal=1, h=.1):
if butcher is None:
A, b = rk_butcher_4()
else:
A, b = butcher
c = np.sum(A, axis=1)
s = len(c)
u = u0.copy()
t = 0
hist = [(t,u0)]
while t < tfinal:
if tfinal - t < 1.01*h:
h = tfinal - t
... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Observations* Solutions look pretty good and we didn't need a solve.* We needed to evaluate the right hand side $s$ times per step | def mms_error(h, rk_butcher):
hist = ode_rkexplicit(test.f, u0, rk_butcher(), tfinal=20, h=h)
times = [t for t,u in hist]
u = np.array([u for t,u in hist])
return np.linalg.norm(u - test.u(times, u0), np.inf)
hs = np.logspace(-1.5, .5, 20)
error_heun = [mms_error(h, rk_butcher_heun) for h in hs]
error_... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Work-precision diagrams for comparing methodsSince these methods do not cost the same per step, it is more enlightening to compare them using some measure of cost. For large systems of ODE, such as arise by discretizing a PDE, the cost of time integration is dominated by evaluating the right hand side (discrete spati... | plt.loglog(20*2/hs, error_heun, 'o', label='Heun')
plt.loglog(20*4/hs, error_rk4, 's', label='RK4')
plt.title('Error vs cost')
plt.ylabel('Error')
plt.xlabel('# function evaluations')
plt.legend(loc='upper right');
test = linear(np.array([[0, 1, 0],[-1, 0, 0],[10, 0, -10]]))
print(np.linalg.eigvals(test.A))
u0 = np.arr... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Evidently Heun becomes resolved at lower cost than RK4. Refinement in space and timeWhen solving a transient PDE, we should attempt to balance spatial discretization error with temporal discretization error. If we wish to use the same type of method across a range of accuracies, we need to1. choose spatial and tempor... | def rk_butcher_bs3():
A = np.array([[0, 0, 0, 0],
[1/2, 0, 0, 0],
[0, 3/4, 0, 0],
[2/9, 1/3, 4/9, 0]])
b = np.array([[2/9, 1/3, 4/9, 0],
[7/24, 1/4, 1/3, 1/8]])
return A, b
A, b = rk_butcher_bs3()
plot_rkstability(A, b[0], ... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
While this method has four stages, it has the "first same as last" (FSAL) property meaning that the fourth stage exactly matches the completion formula, thus the first stage of the next time step. This means it can be implemented using only three function evaluations per time step.Higher order methods with embedded er... | # We can import and clean these coefficient tables directly from Wikipedia
import pandas
from fractions import Fraction
dframe = pandas.read_html('https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method')[0]
dframe
# Clean up unicode minus sign, NaN, and convert to float
dfloat = dframe.applymap(lam... | _____no_output_____ | BSD-2-Clause | FDTransient.ipynb | justindeng21/numcomp-class-spring19 |
Valuación de opciones asiáticas - Las opciones que tratamos la clase pasada dependen sólo del valor del precio del subyacente $S_t$, en el instante que se ejerce.- Cambios bruscos en el precio, cambian que la opción esté *in the money* a estar *out the money*.- **Posibilidad de evitar esto** $\longrightarrow$ suscrib... | #importar los paquetes que se van a usar
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import datetime
import matplotlib.pyplot as plt
import scipy.stats as st
import seaborn as sns
%matplotlib inline
#algunas opciones para Pandas
pd.set_option('display.notebook_repr_html', True)
pd.set_op... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpcionesAsiaticas.ipynb | danielch4/SPF-2021-I |
Valuación opciones asiáticas 1. Método sumas de Riemann | #### Sumas de Riemann
# Strike
strike = K
# Tiempo de cierre del contrato
T = 1
# Valuación de la opción
call = pd.DataFrame({'Prima_asiatica':
np.exp(-r*T) * np.fmax(Average_t - strike, 0).mean(axis=1)}, index=t)
call.plot()
print('La prima estimada usando %i trayectorias es: %2.2f'%(NbTraj,cal... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpcionesAsiaticas.ipynb | danielch4/SPF-2021-I |
Ahora hagamos pruebas variando la cantidad de trayectorias `NbTraj` y la cantidad de números de puntos `NbStep` para ver como aumenta la precisión del método. Primero creemos una función que realice la aproximación de Riemann | # Función donde se almacenan todos los resultados
def Riemann_approach(K:'Strike price',r:'Tasa libre de riesgo',S0:'Precio inicial',
NbTraj:'Número trayectorias',NbStep:'Cantidad de pasos a simular',
sigma:'Volatilidad',T:'Tiempo de cierre del contrato en años',
... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpcionesAsiaticas.ipynb | danielch4/SPF-2021-I |
EjemploValuar la siguiente opción asiática con los siguientes datos $S_0= 100$, $r=0.10$, $\sigma=0.2$, $K=100$, $T=1$ en años, usando la siguiente combinación de trayectorias y número de pasos: | NbTraj = [1000, 10000, 20000]
NbStep = [10, 50, 100]
# Visualización de datos
filas = ['Nbtray = %i' %i for i in NbTraj]
col = ['NbStep = %i' %i for i in NbStep]
df = pd.DataFrame(index=filas,columns=col)
df
# Resolverlo acá
S0 = 100
r = 0.10
sigma = 0.2
K = 100
T = 1
df.loc[:, :] = list(map(lambda N_tra: list(map(l... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpcionesAsiaticas.ipynb | danielch4/SPF-2021-I |
Overfitting and RegularizationLet's generate a new dataset: a straight line added to a sine wave and some random noise (unwanted of course) | import numpy as np
def generate_datasets(n_points):
global train_x, train_y, test_x, test_y
def generate_dataset(seed, n_points):
train_slope = 0.1
train_offset = -1.0
x = np.linspace(-10, 10, n_points).astype(np.float32)
rng = np.random.RandomState(seed=seed)
y =... | _____no_output_____ | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Let's do some reshape of the training and test data and normalise the data into the range [-1.0, 1.0]. | train_x = train_x.reshape(-1, 1)
train_y = train_y.reshape(-1, 1)
train_x = train_x - np.mean(train_x, axis=0)
train_x = train_x / np.max(train_x, axis=0)
test_x = test_x.reshape(-1, 1)
test_y = test_y.reshape(-1, 1)
test_x = test_x - np.mean(test_x, axis=0)
test_x = test_x / np.max(test_x, axis=0) | _____no_output_____ | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Now we are going to play around with **hyperparameters** of the network, like number of layers and number of the units.We will do this in iterative way:* train the network* measure the cost and the accuracy* change the value of some hyperparameter* repeat the experiment* compare the resultsThis because there is a dange... | import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
def build_and_run_regression_graph(num_layers, num_hidden, num_steps, num_runs):
# Number of data points
m = train_x.shape[0]
training_loss_for_run = []
test_loss_for_run = []
prediction... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 6) 12
____________________________________... | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
We have run the above model with 6 units and one hidden layer. The model fits the data well in some runs but **very badly on other runs**. The gradient descend struggle to find a good minimum for the cost function in those cases.The output shows also the minimum, mean and maximum loss for training and test. The thing t... | build_and_run_regression_graph(num_layers=1, num_hidden=16, num_steps=30000, num_runs=10) | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 16) 32
____________________________________... | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Still there are runs where the model doesn't fit the data very well but we can start noticing a **stronger overfitting.**As last example we try **4 hidden layers of 16 neurons** per layer | build_and_run_regression_graph(num_layers=4, num_hidden=16, num_steps=30000, num_runs=10) | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 16) 32
____________________________________... | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Ok, in this last example the model adapted very well to the training data. It has even adapted to the noise we introduced! This is not a good thing because we can see a **strong overfit** to the trining data.In fact the loss on the test data is much higher, hence the model won't do a great job when presenting new data.... | import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.regularizers import l2
def build_and_run_regression_graph_with_l2(num_layers, num_hidden, num_steps, num_runs, lambda_=0):
# Number of data points
m = train_x.shape[0]
trai... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 16) 32
____________________________________... | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Ok, we can see now the model fits the data but not overfits (it doesn't try to pass to every point)A training dataset of just 100 points is insufficient to represent the underlying distribution, and so, unsurprisingly, the model performs worse on the test dataset.Let's try not to increase the number of data points: **t... | generate_datasets(n_points=2000)
plt.rcParams["figure.figsize"] = (12, 8)
plt.plot(train_x, train_y, 'o');
plt.show()
build_and_run_regression_graph_with_l2(num_layers=4, num_hidden=16, num_steps=30000, num_runs=10, lambda_=0.001) | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 16) 32
____________________________________... | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course |
Look at the training/test final results.They are almost identical: that means we now have a model that performs well both on training and test dataset hence the model doesn't have any bias towards the training dataset and can predict correctly unseen data. | _____no_output_____ | BSD-3-Clause | 04_overfitting.ipynb | diegorusso/deep-learning-scratch-course | |
N-ary Tree Postorder Traversal | Given an n-ary tree, return the postorder traversal of its nodes' values.
For example, given a 3-ary tree:
Return its postorder traversal as: [5,6,3,2,4,1].
Note: Recursive solution is trivial, could you do it iteratively? | _____no_output_____ | MIT | 590. N-ary Tree Postorder Traversal.ipynb | sppool/LeetCode |
 | class Node:
def __init__(self, val, children=None):
self.val = val
self.children = children # type(children) list(node1, node2...)
class Solution: # 100.00%
def postorder(self, root):
if not root: return [] # root = None 初始
self.res = []
self.order(root)
return... | _____no_output_____ | MIT | 590. N-ary Tree Postorder Traversal.ipynb | sppool/LeetCode |
TensorStandardScaler | class TensorStandardScaler:
"""Helper class for automatically normalizing inputs into the network.
"""
def __init__(self, x_dim):
"""Initializes a scaler.
Arguments:
x_dim (int): The dimensionality of the inputs into the scaler.
Returns: None.
"""
self.fitte... | [[0. 0. 0. 0.]] [[1. 1. 1. 1.]]
[[-1.2247448 -1.2247448 -1.2247448 -1.2247448]
[ 0. 0. 0. 0. ]
[ 1.2247448 1.2247448 1.2247448 1.2247448]]
[[4. 5. 6. 7.]] [[3.2659864 3.2659864 3.2659864 3.2659864]]
| MIT | play/Play.ipynb | Hyperion-shuo/handful-of-trials |
shuffle rows | def shuffle_rows(arr):
idxs = np.argsort(np.random.uniform(size=arr.shape), axis=-1)
return arr[np.arange(arr.shape[0])[:, None], idxs]
a = np.random.uniform(size=(3,3,3))
b = a.shape
print(b)
a = shuffle_rows(a)
c = a.shape
print(c)
a = np.arange(12).reshape(3,2,2)
print(a)
idxs = a.argsort()
b = a[np.array... | _____no_output_____ | MIT | play/Play.ipynb | Hyperion-shuo/handful-of-trials |
MPC ._compile_cost | # action seq
a = np.arange(12).reshape(2,2,3)
b = a[:, :, None]
c = np.tile(b, [1, 1, 5, 1])
print(a.shape, b.shape, c.shape)
# obs seq
a = np.arange(6).reshape(2,3)[None]
b = np.tile(a, [2, 1])
print(a.shape, b.shape)
print(a, "\n")
print(b, "\n")
random_array = tf.random_uniform([8, 5])
sort_idxs = tf.nn.top_k(
r... | _____no_output_____ | MIT | play/Play.ipynb | Hyperion-shuo/handful-of-trials |
TensorFlow TutorialWelcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras... | import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
%matplotlib inline
np.random.seed(1) | _____no_output_____ | MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Now that you have imported the library, we will walk you through its different applications. You will start with an example, where we compute for you the loss of one training example. $$loss = \mathcal{L}(\hat{y}, y) = (\hat y^{(i)} - y^{(i)})^2 \tag{1}$$ | y_hat = tf.constant(36, name='y_hat') # Define y_hat constant. Set to 36.
y = tf.constant(39, name='y') # Define y. Set to 39
loss = tf.Variable((y - y_hat)**2, name='loss') # Create a variable for the loss
init = tf.global_variables_initializer() # When init is run later (sessi... | 9
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Writing and running programs in TensorFlow has the following steps:1. Create Tensors (variables) that are not yet executed/evaluated. 2. Write operations between those Tensors.3. Initialize your Tensors. 4. Create a Session. 5. Run the Session. This will run the operations you'd written above. Therefore, when we create... | a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c) | Tensor("Mul:0", shape=(), dtype=int32)
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
As expected, you will not see 20! You got a tensor saying that the result is a tensor that does not have the shape attribute, and is of type "int32". All you did was put in the 'computation graph', but you have not run this computation yet. In order to actually multiply the two numbers, you will have to create a sessio... | sess = tf.Session()
print(sess.run(c)) | 20
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Great! To summarize, **remember to initialize your variables, create a session and run the operations inside the session**. Next, you'll also have to know about placeholders. A placeholder is an object whose value you can specify only later. To specify values for a placeholder, you can pass in values by using a "feed d... | # Change the value of x in the feed_dict
x = tf.placeholder(tf.int64, name = 'x')
print(sess.run(2 * x, feed_dict = {x: 3}))
sess.close() | 6
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
When you first defined `x` you did not have to specify a value for it. A placeholder is simply a variable that you will assign data to only later, when running the session. We say that you **feed data** to these placeholders when running the session. Here's what's happening: When you specify the operations needed for a... | # GRADED FUNCTION: linear_function
def linear_function():
"""
Implements a linear function:
Initializes W to be a random tensor of shape (4,3)
Initializes X to be a random tensor of shape (3,1)
Initializes b to be a random tensor of shape (4,1)
Returns:
result -- r... | result = [[-2.15657382]
[ 2.95891446]
[-1.08926781]
[-0.84538042]]
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
*** Expected Output ***: **result**[[-2.15657382] [ 2.95891446] [-1.08926781] [-0.84538042]] 1.2 - Computing the sigmoid Great! You just implemented a linear function. Tensorflow offers a variety of commonly used neural network functions like `tf.sigmoid` and `tf.softmax`. For this exercise lets compute the sigmoi... | # GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Computes the sigmoid of z
Arguments:
z -- input value, scalar or vector
Returns:
results -- the sigmoid of z
"""
### START CODE HERE ### ( approx. 4 lines of code)
# Create a placeholder for x. Name it 'x'.
x = tf.pl... | sigmoid(0) = 0.5
sigmoid(12) = 0.999994
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
*** Expected Output ***: **sigmoid(0)**0.5 **sigmoid(12)**0.999994 **To summarize, you how know how to**:1. Create placeholders2. Specify the computation graph corresponding to operations you want to compute3. Create the session4. Run the session, using a feed dictionary if necessary to specify placeholder variable... | # GRADED FUNCTION: cost
def cost(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've been calling "... | cost = [ 1.00538719 1.03664088 0.41385433 0.39956614]
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
** Expected Output** : **cost** [ 1.00538719 1.03664088 0.41385433 0.39956614] 1.4 - Using One Hot encodingsMany times in deep learning you will have a y vector with numbers ranging from 0 to C-1, where C is the number of classes. If C is for example 4, t... | # GRADED FUNCTION: one_hot_matrix
def one_hot_matrix(labels, C):
"""
Creates a matrix where the i-th row corresponds to the ith class number and the jth column
corresponds to the jth training example. So if example j had a label i. Then entry (i,j)
will be 1.
... | one_hot = [[ 0. 0. 0. 1. 0. 0.]
[ 1. 0. 0. 0. 0. 1.]
[ 0. 1. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 0. 0.]]
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **one_hot** [[ 0. 0. 0. 1. 0. 0.] [ 1. 0. 0. 0. 0. 1.] [ 0. 1. 0. 0. 1. 0.] [ 0. 0. 1. 0. 0. 0.]] 1.5 - Initialize with zeros and onesNow you will learn how to initialize a vector of zeros and ones. The function you w... | # GRADED FUNCTION: ones
def ones(shape):
"""
Creates an array of ones of dimension shape
Arguments:
shape -- shape of the array you want to create
Returns:
ones -- array containing only ones
"""
### START CODE HERE ###
# Create "ones" tensor using tf.ones(..... | ones = [ 1. 1. 1.]
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output:** **ones** [ 1. 1. 1.] 2 - Building your first neural network in tensorflowIn this part of the assignment you will build a neural network using tensorflow. Remember that there are two parts to implement a tensorflow model:- Create the com... | # Loading the dataset
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() | _____no_output_____ | MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Change the index below and run the cell to visualize some examples in the dataset. | # Example of a picture
index = 0
plt.imshow(X_train_orig[index])
print ("y = " + str(np.squeeze(Y_train_orig[:, index]))) | y = 5
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
As usual you flatten the image dataset, then normalize it by dividing by 255. On top of that, you will convert each label to a one-hot vector as shown in Figure 1. Run the cell below to do so. | # Flatten the training and test images
X_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T
X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T
# Normalize image vectors
X_train = X_train_flatten/255.
X_test = X_test_flatten/255.
# Convert training and test labels to one hot matrices
Y_train... | number of training examples = 1080
number of test examples = 120
X_train shape: (12288, 1080)
Y_train shape: (6, 1080)
X_test shape: (12288, 120)
Y_test shape: (6, 120)
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Note** that 12288 comes from $64 \times 64 \times 3$. Each image is square, 64 by 64 pixels, and 3 is for the RGB colors. Please make sure all these shapes make sense to you before continuing. **Your goal** is to build an algorithm capable of recognizing a sign with high accuracy. To do so, you are going to build a t... | # GRADED FUNCTION: create_placeholders
def create_placeholders(n_x, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288)
n_y -- scalar, number of classes (from 0 to 5, so -> 6)
Returns:... | X = Tensor("X_1:0", shape=(12288, ?), dtype=float32)
Y = Tensor("Y:0", shape=(6, ?), dtype=float32)
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **X** Tensor("Placeholder_1:0", shape=(12288, ?), dtype=float32) (not necessarily Placeholder_1) **Y** Tensor("Placeholder_2:0", shape=(10, ?), dtype=float32) (not necessarily Placeholder_2) ... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters():
"""
Initializes parameters to build a neural network with tensorflow. The shapes are:
W1 : [25, 12288]
b1 : [25, 1]
W2 : [12, 25]
b2 : [12, 1]
... | W1 = <tf.Variable 'W1:0' shape=(25, 12288) dtype=float32_ref>
b1 = <tf.Variable 'b1:0' shape=(25, 1) dtype=float32_ref>
W2 = <tf.Variable 'W2:0' shape=(12, 25) dtype=float32_ref>
b2 = <tf.Variable 'b2:0' shape=(12, 1) dtype=float32_ref>
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **W1** **b1** **W2** **b2** As expected, the parameters ... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX
Arguments:
X -- input dataset placeholder, of shape (input size, number of examples)
parameters -- python d... | Z3 = Tensor("add_2:0", shape=(6, ?), dtype=float32)
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **Z3** Tensor("Add_2:0", shape=(6, ?), dtype=float32) You may have noticed that the forward propagation doesn't output any cache. You will understand why below, when we get to brackpropagation. 2.4 Compute costAs seen before, it is very ... | # GRADED FUNCTION: compute_cost
def compute_cost(Z3, Y):
"""
Computes the cost
Arguments:
Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples)
Y -- "true" labels vector placeholder, same shape as Z3
Returns:
cost - Tensor of the c... | cost = Tensor("Mean:0", shape=(), dtype=float32)
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **cost** Tensor("Mean:0", shape=(), dtype=float32) 2.5 - Backward propagation & parameter updatesThis is where you become grateful to programming frameworks. All the backpropagation and the parameters update is taken care of in 1 line of... | def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 1... | _____no_output_____ | MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Run the following cell to train your model! On our machine it takes about 5 minutes. Your "Cost after epoch 100" should be 1.016458. If it's not, don't waste time; interrupt the training by clicking on the square (⬛) in the upper bar of the notebook, and try to correct your code. If it is the correct cost, take a break... | parameters = model(X_train, Y_train, X_test, Y_test) | Cost after epoch 0: 1.855702
Cost after epoch 100: 1.016458
Cost after epoch 200: 0.733102
Cost after epoch 300: 0.572940
Cost after epoch 400: 0.468774
Cost after epoch 500: 0.381021
Cost after epoch 600: 0.313822
Cost after epoch 700: 0.254158
Cost after epoch 800: 0.203829
Cost after epoch 900: 0.166421
Cost after e... | MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
**Expected Output**: **Train Accuracy** 0.999074 **Test Accuracy** 0.716667 Amazing, your algorithm can recognize a sign representing a figure between 0 and 5 with 71.7% accuracy.**Insights**:- Your mod... | import scipy
from PIL import Image
from scipy import ndimage
## START CODE HERE ## (PUT YOUR IMAGE NAME)
my_image = "thumbs_up.jpg"
## END CODE HERE ##
# We preprocess your image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(... | Your algorithm predicts: y = 3
| MIT | 2_Improving_Deep_Neural_Networks/week 03/Tensorflow Tutorial(solution).ipynb | JifuZhao/Deep-Learning-Specialization |
Machine Learning Engineer Nanodegree Introduction and Foundations Project 0: Titanic Survival ExplorationIn 1912, the ship RMS Titanic struck an iceberg on its maiden voyage and sank, resulting in the deaths of most of its passengers and crew. In this introductory project, we will explore a subset of the RMS Titanic p... | import numpy as np
import pandas as pd
# RMS Titanic data visualization code
from titanic_visualizations import survival_stats
from IPython.display import display
%matplotlib inline
# Load the dataset
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
# Print the first few entries of the RMS Titanic data... | /usr/local/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
From a sample of the RMS Titanic data, we can see the various features present for each passenger on the ship:- **Survived**: Outcome of survival (0 = No; 1 = Yes)- **Pclass**: Socio-economic class (1 = Upper class; 2 = Middle class; 3 = Lower class)- **Name**: Name of passenger- **Sex**: Sex of the passenger- **Age**:... | # Store the 'Survived' feature in a new variable and remove it from the dataset
outcomes = full_data['Survived']
data = full_data.drop('Survived', axis = 1)
# Show the new dataset with 'Survived' removed
display(data.head()) | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
The very same sample of the RMS Titanic data now shows the **Survived** feature removed from the DataFrame. Note that `data` (the passenger data) and `outcomes` (the outcomes of survival) are now *paired*. That means for any passenger `data.loc[i]`, they have the survival outcome `outcome[i]`.To measure the performance... | def accuracy_score(truth, pred):
""" Returns accuracy score for input truth and predictions. """
# Ensure that the number of predictions matches number of outcomes
if len(truth) == len(pred):
# Calculate and return the accuracy as a percent
return "Predictions have an accuracy... | Predictions have an accuracy of 60.00%.
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
> **Tip:** If you save an iPython Notebook, the output from running code blocks will also be saved. However, the state of your workspace will be reset once a new session is started. Make sure that you run all of the code blocks from your previous session to reestablish variables and functions before picking up where yo... | def predictions_0(data):
""" Model with no features. Always predicts a passenger did not survive. """
predictions = []
for _, passenger in data.iterrows():
# Predict the survival of 'passenger'
predictions.append(0)
# Return our predictions
return pd.Series(predictions... | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Question 1*Using the RMS Titanic data, how accurate would a prediction be that none of the passengers survived?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 61.62%.
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
**Answer:** 61.62% ***Let's take a look at whether the feature **Sex** has any indication of survival rates among passengers using the `survival_stats` function. This function is defined in the `titanic_visualizations.py` Python script included with this project. The first two parameters passed to the function are the ... | survival_stats(data, outcomes, 'Sex') | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Examining the survival statistics, a large majority of males did not survive the ship sinking. However, a majority of females *did* survive the ship sinking. Let's build on our previous prediction: If a passenger was female, then we will predict that they survived. Otherwise, we will predict the passenger did not survi... | def predictions_1(data):
""" Model with one feature:
- Predict a passenger survived if they are female. """
predictions = []
for _, passenger in data.iterrows():
# Remove the 'pass' statement below
# and write your prediction conditions here
if passenger.S... | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Question 2*How accurate would a prediction be that all female passengers survived and the remaining passengers did not survive?* **Hint:** Run the code cell below to see the accuracy of this prediction. | print accuracy_score(outcomes, predictions) | Predictions have an accuracy of 78.68%.
| MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
**Answer**: 78.68% ***Using just the **Sex** feature for each passenger, we are able to increase the accuracy of our predictions by a significant margin. Now, let's consider using an additional feature to see if we can further improve our predictions. For example, consider all of the male passengers aboard the RMS Tita... | survival_stats(data, outcomes, 'Age', ["Sex == 'male'"]) | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Examining the survival statistics, the majority of males younger than 10 survived the ship sinking, whereas most males age 10 or older *did not survive* the ship sinking. Let's continue to build on our previous prediction: If a passenger was female, then we will predict they survive. If a passenger was male and younger... | def predictions_2(data):
""" Model with two features:
- Predict a passenger survived if they are female.
- Predict a passenger survived if they are male and younger than 10. """
predictions = []
for _, passenger in data.iterrows():
# Remove the 'pass' statement... | _____no_output_____ | MIT | python/titanic_survival_exploration/Titanic_Survival_Exploration.ipynb | robertodias/machine_learning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.