markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Looking at these, it appears that there are some overlap between the hospitals. Hospital 17, 21, 42, and 95 are the 4 common hospital that are in the top ten of both these products. We will turn to a hospital examination down the road. | set(data.get_hospitals_by_product('product_1842').index.tolist()) & set(data.get_hospitals_by_product('product_1807').index.tolist()) | reports/neiss.ipynb | minh5/cpsc | mit |
Could be useful to compare stratum types - Do large hospitals see different rates of injury than small hospitals?
Another way of examining product harm would not only to count the total numbers of products but also to see what is the top product that is reported for each hosptial. Here we can look at not only the sheer number which could be due to over reporting or awareness but also to see if there are geographic differences for product harm. However, after examining this, we see that 70 out of the 82 hospitals surveyed have product 1842 and 1807 as the top product.
However an interesting finding is that product_1267, product_3299, and product_3283 are in the top ten list of top products by hospital but not in the top ten overall. However, the number is small as it only affects 5 hospitals and 14,844 reported cases. It would be interesting to see where these five hospital are at and why these products are the top of their product harm. | data.top_product_for_hospital() | reports/neiss.ipynb | minh5/cpsc | mit |
Another way of approaching would be to fit a Negative Binomial Regression to see if there are any meaningful differences between the sizes of the hospitals. I use a negative binomial regression rather than a poisson regression because there is strong evidence of overdispersion, that is, the variance of the data is much higher than the mean, as shown below. This also occurs across all stratum (only shown for small, medium, and large). | counts = data.data.ix[data.data['product'] == 'product_1842',:]['hospital'].value_counts()
print('variance of product 1842 counts:', np.var(counts.values))
print('mean of product 1842 counts:', np.mean(counts.values))
data.plot_stratum_dist('product_1842', 'S')
data.plot_stratum_dist('product_1842', 'M')
data.plot_stratum_dist('product_1842', 'L')
df = data.prepare_stratum_modeling('product_1842')
df.head()
model = smf.glm("counts ~ stratum", data=df,
family=sm.families.NegativeBinomial()).fit()
model.summary() | reports/neiss.ipynb | minh5/cpsc | mit |
From the model, we see that there are only significant differences between Medium and Small hospital. Given the coefficients, the log count difference between Medium and Small hospitals is -1.55. Other than that there doesn't seem to be any other signficant differences between hospital sizes for Product 1842.
We can do the same to examine the 2nd most reported product, Product 1807. Below I check the assumption to fit a negative binomial regression, that the variance is far greater than the mean. In this case we see that it is the case. | data.plot_stratum_dist('product_1807', 'S')
data.plot_stratum_dist('product_1807', 'M')
data.plot_stratum_dist('product_1807', 'L') | reports/neiss.ipynb | minh5/cpsc | mit |
The assumptions have been met and after building the model, we see very similar results as the previous model, that there are only significant differences between the small and large hospitals. For future research, we can use similar techniques to see significant differences between hospital sizes for all products. | df2 = data.prepare_stratum_modeling('product_1807')
model = smf.glm("counts ~ stratum", data=df,
family=sm.families.NegativeBinomial()).fit()
model.summary() | reports/neiss.ipynb | minh5/cpsc | mit |
Do we see meaningful trends when race is reported?
From the top items, we don't see any meaningful differences between the top ten items for people who have race reported and race not reported. Even among the data where we do have race reported, there doesn't seem to be much variation when it comes to the top ten products causes most harm. | data.retrieve_query('race_reported', 'reported', 'product')
data.retrieve_query('race_reported', 'not reported', 'product')
races = ['white', 'black', 'hispanic', 'other']
for race in races:
print(race)
print(data.retrieve_query('new_race', race, 'product')) | reports/neiss.ipynb | minh5/cpsc | mit |
Integral 1
$$ I_1 = \int_0^a {\sqrt{a^2-x^2} dx} = \frac{\pi a^2}{4} $$ | def integrand(x, a):
return np.sqrt(a**2 - x**2)
def integral_approx(a):
# Use the args keyword argument to feed extra arguments to your integrand
I, e = integrate.quad(integrand, 0, a, args=(a,))
return I
def integral_exact(a):
return 0.25*np.pi
print("Numerical: ", integral_approx(1.0))
print("Exact : ", integral_exact(1.0))
assert True # leave this cell to grade the above integral | Integration/IntegrationEx02.ipynb | JAmarel/Phys202 | mit |
Integral 2
$$ I_2 = \int_0^{\frac{\pi}{2}} {\sin^2{x}}{ } {dx} = \frac{\pi}{4} $$ | def integrand(x):
return np.sin(x)**2
def integral_approx():
I, e = integrate.quad(integrand, 0, np.pi/2)
return I
def integral_exact():
return 0.25*np.pi
print("Numerical: ", integral_approx())
print("Exact : ", integral_exact())
assert True # leave this cell to grade the above integral | Integration/IntegrationEx02.ipynb | JAmarel/Phys202 | mit |
Integral 3
$$ I_3 = \int_0^{2\pi} \frac{dx}{a+b\sin{x}} = {\frac{2\pi}{\sqrt{a^2-b^2}}} $$ | def integrand(x,a,b):
return 1/(a+ b*np.sin(x))
def integral_approx(a,b):
I, e = integrate.quad(integrand, 0, 2*np.pi,args=(a,b))
return I
def integral_exact(a,b):
return 2*np.pi/np.sqrt(a**2-b**2)
print("Numerical: ", integral_approx(10,0))
print("Exact : ", integral_exact(10,0))
assert True # leave this cell to grade the above integral | Integration/IntegrationEx02.ipynb | JAmarel/Phys202 | mit |
Integral 4
$$ I_4 = \int_0^{\infty} \frac{x}{e^{x}+1} = {\frac{\pi^2}{12}} $$ | def integrand(x):
return x/(np.exp(x)+1)
def integral_approx():
I, e = integrate.quad(integrand, 0, np.inf)
return I
def integral_exact():
return (1/12)*np.pi**2
print("Numerical: ", integral_approx())
print("Exact : ", integral_exact())
assert True # leave this cell to grade the above integral | Integration/IntegrationEx02.ipynb | JAmarel/Phys202 | mit |
Integral 5
$$ I_5 = \int_0^{\infty} \frac{x}{e^{x}-1} = {\frac{\pi^2}{6}} $$ | def integrand(x):
return x/(np.exp(x)-1)
def integral_approx():
I, e = integrate.quad(integrand, 0, np.inf)
return I
def integral_exact():
return (1/6)*np.pi**2
print("Numerical: ", integral_approx())
print("Exact : ", integral_exact())
assert True # leave this cell to grade the above integral | Integration/IntegrationEx02.ipynb | JAmarel/Phys202 | mit |
EXERCISE: Use any of the solvers we've seen thus far to find the minimum of the zimmermann function (i.e. use mystic.models.zimmermann as the objective). Use the bounds suggested below, if your choice of solver allows it. | import scipy.optimize as opt
import mystic.models
result = opt.minimize(mystic.models.zimmermann, [10., 1.], method='powell')
print(result.x) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Do the same for the fosc3d function found at mystic.models.fosc3d, using the bounds suggested by the documentation, if your chosen solver accepts bounds or constraints. | import scipy.optimize as opt
import mystic.models
result = opt.minimize(mystic.models.fosc3d, [-5., 0.5], method='powell')
print(result.x) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Use mystic to find the minimum for the peaks test function, with the bound specified by the mystic.models.peaks documentation. | import mystic
import mystic.models
result = mystic.solvers.fmin_powell(mystic.models.peaks, [0., -2.], bounds=[(-5.,5.)]*2)
print(result) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Use mystic to do a fit to the noisy data in the scipy.optimize.curve_fit example (the least squares fit). | import numpy as np
import scipy.stats as stats
from mystic.solvers import fmin_powell
from mystic import reduced
# Define the function to fit.
def function(coeffs, x):
a,b,f,phi = coeffs
return a * np.exp(-b * np.sin(f * x + phi))
# Create a noisy data set around the actual parameters
true_params = [3, 2, 1, np.pi/4]
print("target parameters: {}".format(true_params))
x = np.linspace(0, 2*np.pi, 25)
exact = function(true_params, x)
noisy = exact + 0.3*stats.norm.rvs(size=len(x))
# Define an objective that fits against the noisy data
@reduced(lambda x,y: abs(x)+abs(y))
def objective(coeffs, x, y):
return function(coeffs, x) - y
# Use curve_fit to estimate the function parameters from the noisy data.
initial_guess = [1,1,1,1]
args = (x, noisy)
estimated_params = fmin_powell(objective, initial_guess, args=args)
print("solved parameters: {}".format(estimated_params)) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Solve the chebyshev8.cost example exactly, by applying the knowledge that the last term in the chebyshev polynomial will always be be one. Use numpy.round or mystic.constraints.integers or to constrain solutions to the set of integers. Does using mystic.suppressed to supress small numbers accelerate the solution? | # Differential Evolution solver
from mystic.solvers import DifferentialEvolutionSolver2
# Chebyshev polynomial and cost function
from mystic.models.poly import chebyshev8, chebyshev8cost
from mystic.models.poly import chebyshev8coeffs
# tools
from mystic.termination import VTR, CollapseAt, Or
from mystic.strategy import Best1Exp
from mystic.monitors import VerboseMonitor
from mystic.tools import random_seed
from mystic.math import poly1d
import numpy as np
if __name__ == '__main__':
print("Differential Evolution")
print("======================")
ndim = 9
random_seed(123)
# configure monitor
stepmon = VerboseMonitor(50,50)
# build a constraints function
def constraints(x):
x[-1] = 1.
return np.round(x)
stop = Or(VTR(0.0001), CollapseAt(0.0, generations=2))
# use DE to solve 8th-order Chebyshev coefficients
npop = 10*ndim
solver = DifferentialEvolutionSolver2(ndim,npop)
solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)
solver.SetGenerationMonitor(stepmon)
solver.SetConstraints(constraints)
solver.enable_signal_handler()
solver.Solve(chebyshev8cost, termination=stop, strategy=Best1Exp, \
CrossProbability=1.0, ScalingFactor=0.9)
solution = solver.Solution()
# use monitor to retrieve results information
iterations = len(stepmon)
cost = stepmon.y[-1]
print("Generation %d has best Chi-Squared: %f" % (iterations, cost))
# use pretty print for polynomials
print(poly1d(solution))
# compare solution with actual 8th-order Chebyshev coefficients
print("\nActual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs)) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Replace the symbolic constraints in the following "Pressure Vessel Design" code with explicit penalty functions (i.e. use a compound penalty built with mystic.penalty.quadratic_inequality). | "Pressure Vessel Design"
def objective(x):
x0,x1,x2,x3 = x
return 0.6224*x0*x2*x3 + 1.7781*x1*x2**2 + 3.1661*x0**2*x3 + 19.84*x0**2*x2
bounds = [(0,1e6)]*4
# with penalty='penalty' applied, solution is:
xs = [0.72759093, 0.35964857, 37.69901188, 240.0]
ys = 5804.3762083
from mystic.constraints import as_constraint
from mystic.penalty import quadratic_inequality
def penalty1(x): # <= 0.0
return -x[0] + 0.0193*x[2]
def penalty2(x): # <= 0.0
return -x[1] + 0.00954*x[2]
def penalty3(x): # <= 0.0
from math import pi
return -pi*x[2]**2*x[3] - (4/3.)*pi*x[2]**3 + 1296000.0
def penalty4(x): # <= 0.0
return x[3] - 240.0
@quadratic_inequality(penalty1, k=1e12)
@quadratic_inequality(penalty2, k=1e12)
@quadratic_inequality(penalty3, k=1e12)
@quadratic_inequality(penalty4, k=1e12)
def penalty(x):
return 0.0
if __name__ == '__main__':
from mystic.solvers import diffev2
from mystic.math import almostEqual
result = diffev2(objective, x0=bounds, bounds=bounds, penalty=penalty,
npop=40, gtol=500, disp=True, full_output=True)
print(result[0]) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Solve the cvxopt "qp" example with mystic. Use symbolic constaints, penalty functions, or constraints operators. If you get it quickly, do all three methods. | def objective(x):
x0,x1 = x
return 2*x0**2 + x1**2 + x0*x1 + x0 + x1
bounds = [(0.0, None),(0.0, None)]
# with penalty='penalty' applied, solution is:
xs = [0.25, 0.75]
ys = 1.875
from mystic.math.measures import normalize
def constraint(x): # impose exactly
return normalize(x, 1.0)
if __name__ == '__main__':
from mystic.solvers import diffev2, fmin_powell
result = diffev2(objective, x0=bounds, bounds=bounds, npop=40,
constraints=constraint, disp=False, full_output=True)
print(result[0]) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
EXERCISE: Convert one of our previous mystic examples to use parallel computing. Note that if the solver has a SetMapper method, it can take a parallel map. | from mystic.termination import VTR, ChangeOverGeneration, And, Or
stop = Or(And(VTR(), ChangeOverGeneration()), VTR(1e-8))
from mystic.models import rosen
from mystic.monitors import VerboseMonitor
from mystic.solvers import DifferentialEvolutionSolver2
from pathos.pools import ThreadPool
if __name__ == '__main__':
solver = DifferentialEvolutionSolver2(3,40)
solver.SetRandomInitialPoints([-10,-10,-10],[10,10,10])
solver.SetGenerationMonitor(VerboseMonitor(10))
solver.SetMapper(ThreadPool().map) #NOTE: evaluation of objective in parallel
solver.SetTermination(stop)
solver.SetObjective(rosen)
solver.SetStrictRanges([-10,-10,-10],[10,10,10])
solver.SetEvaluationLimits(generations=600)
solver.Solve()
print(solver.bestSolution) | solutions.ipynb | mmckerns/tutmom | bsd-3-clause |
Rabi Oscillations
$\hat{H} = \hat{H}_0 + \Omega \sin((\omega_0+\Delta)t) \hat{\sigma}_x$
$\hat{H}_0 = \frac{\omega_0}{2}\hat{\sigma}_z$ | initial_state = basis(2, 0)
initial_state
ω0 = 1
Δ = 0.002
Ω = 0.005
ts = 6*np.pi/Ω*np.linspace(0,1,120)
H = ω0/2 * sigmaz() + Ω * sigmax() * sin((ω0+Δ)*t)
H
res = mesolve(H, [], initial_state, ts)
σz_expect = expect(sigmaz(), res)
res[20]
plt.plot(ts*Ω/np.pi, σz_expect, 'r.', label='numerical result')
Ωp = (Ω**2+Δ**2)**0.5
plt.plot(ts*Ω/np.pi, 1-(Ω/Ωp)**2*2*np.sin(Ωp*ts/2)**2, 'b-',
label=r'$1-2(\Omega^\prime/\Omega)^2\sin^2(\Omega^\prime t/2)$')
plt.title(r'$\langle\sigma_z\rangle$-vs-$t\Omega/\pi$ at '
r'$\Delta/\Omega=%.2f$, $\omega_0/\Omega=%.2f$'%(Δ/Ω, ω0/Ω))
plt.ylim(-1,1)
plt.legend(loc=3); | examples/Lindblad_Master_Equation_Solver_Examples.ipynb | Krastanov/cutiepy | bsd-3-clause |
With Rotating Wave Approximation
$\hat{H}^\prime = e^{i\hat{H}_0 t}\hat{H} e^{-i\hat{H}_0 t} \approx \frac{\Delta}{2} \hat{\sigma}_z + \frac{\Omega}{2} \hat{\sigma}_x$ | Hp = Δ/2 * sigmaz() + Ω/2 * sigmax()
Hp
res = mesolve(Hp, [], initial_state, ts)
σz_expect = expect(sigmaz(), res)
plt.plot(ts*Ω/np.pi, σz_expect, 'r.', label='numerical result')
Ωp = (Ω**2+Δ**2)**0.5
plt.plot(ts*Ω/np.pi, 1-(Ω/Ωp)**2*2*np.sin(Ωp*ts/2)**2, 'b-',
label=r'$1-2(\Omega^\prime/\Omega)^2\sin^2(\Omega^\prime t/2)$')
plt.title(r'$\langle\sigma_z\rangle$-vs-$t\Omega/\pi$ at '
r'$\Delta/\Omega=%.2f$ in RWA'%(Δ/Ω))
plt.ylim(-1,1)
plt.legend(loc=3); | examples/Lindblad_Master_Equation_Solver_Examples.ipynb | Krastanov/cutiepy | bsd-3-clause |
With $\gamma_1$ collapse | γ1 = 0.2*Ω
c1 = γ1**0.5 * sigmam()
c1
res = mesolve(Hp, [c1], initial_state, ts)
σz_expect = expect(sigmaz(), res)
plt.plot(ts*Ω/np.pi, σz_expect, 'r.', label='numerical result')
plt.ylim(-1,1)
plt.title(r'$\langle\sigma_z\rangle$-vs-$t\Omega/\pi$ at '
r'$\Delta/\Omega=%.2f$ in RWA'%(Δ/Ω) + '\n' +
r'with $\gamma_1 \hat{\sigma}_-$ at $\gamma_1=0.2\Omega$')
plt.hlines(0,0,ts[-1]*Ω/np.pi)
plt.legend(loc=3); | examples/Lindblad_Master_Equation_Solver_Examples.ipynb | Krastanov/cutiepy | bsd-3-clause |
With $\gamma_2$ collapse | γ2 = 0.2*Ω
c2 = γ2**0.5 * sigmaz()
c2
res = mesolve(Hp, [c2], initial_state, ts)
σz_expect = expect(sigmaz(), res)
plt.plot(ts*Ω/np.pi, σz_expect, 'r.', label='numerical result')
plt.ylim(-1,1)
plt.title(r'$\langle\sigma_z\rangle$-vs-$t\Omega/\pi$ at '
r'$\Delta/\Omega=%.2f$ in RWA'%(Δ/Ω) + '\n' +
r'with $\gamma_2 \hat{\sigma}_z$ at $\gamma_2=0.2\Omega$')
plt.hlines(0,0,ts[-1]*Ω/np.pi)
plt.legend(loc=3); | examples/Lindblad_Master_Equation_Solver_Examples.ipynb | Krastanov/cutiepy | bsd-3-clause |
Coherent State in a Harmonic Oscillator
$|\alpha\rangle$ evolving under $\hat{H} = \hat{n}$ coupled to a zero temperature heat bath $\kappa = 0.5$ | N_cutoff = 40
α = 2.5
initial_state = coherent(N_cutoff, α)
initial_state
H = num(N_cutoff)
H
κ = 0.5
n_th = 0
c_down = (κ * (1 + n_th))**2 * destroy(N_cutoff)
c_down
ts = 2*np.pi*np.linspace(0,1,41)
res = mesolve(H, [c_down], initial_state, ts)
a = destroy(N_cutoff)
a_expect = expect(a, res, keep_complex=True)
plt.figure(figsize=(4,4))
plt.plot(np.real(a_expect), np.imag(a_expect), 'b-')
for t, alpha in list(zip(ts,a_expect))[:40:4]:
plt.plot(np.real(alpha), np.imag(alpha), 'r.')
plt.text(np.real(alpha), np.imag(alpha), r'$t=%.1f\pi$'%(t/np.pi), fontsize=14)
plt.title(r'$\langle\hat{a}\rangle$-vs-$t$')
plt.ylabel(r'$\mathcal{I}(\alpha)$')
plt.xlabel(r'$\mathcal{R}(\alpha)$')
l = abs(a_expect[0])
plt.xlim(-l,l)
plt.ylim(-l,l); | examples/Lindblad_Master_Equation_Solver_Examples.ipynb | Krastanov/cutiepy | bsd-3-clause |
Estimate aggregated features | from datetime import datetime, timedelta
from tqdm import tqdm | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Split for each account and create the date as index | card_numbers = data['card_number'].unique()
data['trx_id'] = data.index
data.index = pd.DatetimeIndex(data['date'])
data_ = []
for card_number in tqdm(card_numbers):
data_.append(data.query('card_number == ' + str(card_number))) | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Create Aggregated Features for one account | res_agg = pd.DataFrame(index=data['trx_id'].values,
columns=['Trx_sum_7D', 'Trx_count_1D'])
trx = data_[0]
for i in range(trx.shape[0]):
date = trx.index[i]
trx_id = int(trx.ix[i, 'trx_id'])
# Sum 7 D
agg_ = trx[date-pd.datetools.to_offset('7D').delta:date-timedelta(0,0,1)]
res_agg.loc[trx_id, 'Trx_sum_7D'] = agg_['amount'].sum()
# Count 1D
agg_ = trx[date-pd.datetools.to_offset('1D').delta:date-timedelta(0,0,1)]
res_agg.loc[trx_id, 'Trx_count_1D'] = agg_['amount'].shape[0]
res_agg.mean() | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
All accounts | for trx in tqdm(data_):
for i in range(trx.shape[0]):
date = trx.index[i]
trx_id = int(trx.ix[i, 'trx_id'])
# Sum 7 D
agg_ = trx[date-pd.datetools.to_offset('7D').delta:date-timedelta(0,0,1)]
res_agg.loc[trx_id, 'Trx_sum_7D'] = agg_['amount'].sum()
# Count 1D
agg_ = trx[date-pd.datetools.to_offset('1D').delta:date-timedelta(0,0,1)]
res_agg.loc[trx_id, 'Trx_count_1D'] = agg_['amount'].shape[0]
res_agg.head()
data.index = data.trx_id
data = data.join(res_agg)
data.sample(15, random_state=42).sort_index() | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Split train and test | X = data.loc[~data.fraud.isnull()]
y = X.fraud
X = X.drop(['fraud', 'date', 'card_number'], axis=1)
X_kaggle = data.loc[data.fraud.isnull()]
X_kaggle = X_kaggle.drop(['fraud', 'date', 'card_number'], axis=1)
X_kaggle.head() | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Simple Random Forest | from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100, n_jobs=-1, class_weight='balanced')
from sklearn.metrics import fbeta_score | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
KFold cross-validation | from sklearn.cross_validation import KFold
kf = KFold(X.shape[0], n_folds=5)
res = []
for train, test in kf:
X_train, X_test, y_train, y_test = X.iloc[train], X.iloc[test], y.iloc[train], y.iloc[test]
clf.fit(X_train, y_train)
y_pred_proba = clf.predict_proba(X_test)[:, 1]
y_pred = (y_pred_proba>0.05).astype(int)
res.append(fbeta_score(y_test, y_pred, beta=2))
pd.Series(res).describe() | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Train with all
Predict and send to Kaggle | clf.fit(X, y)
y_pred = clf.predict_proba(X_kaggle)[:, 1]
y_pred = (y_pred>0.05).astype(int)
y_pred = pd.Series(y_pred,name='fraud', index=X_kaggle.index)
y_pred.head(10)
y_pred.to_csv('fraud_transactions_kaggle_1.csv', header=True, index_label='ID') | notebooks/14-KaggleCompetition.ipynb | albahnsen/ML_SecurityInformatics | mit |
Vertex AI Pipelines: AutoML text classification pipelines using google-cloud-pipeline-components
<table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb">
<img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
</a>
</td>
<td>
<a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb">
<img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
View on GitHub
</a>
</td>
<td>
<a href="https://console.cloud.google.com/vertex-ai/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb">
Open in Vertex AI Workbench
</a>
</td>
</table>
<br/><br/><br/>
Overview
This notebook shows how to use the components defined in google_cloud_pipeline_components to build an AutoML text classification workflow on Vertex AI Pipelines.
Dataset
The dataset used for this tutorial is the Happy Moments dataset from Kaggle Datasets. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket.
Objective
In this tutorial, you create an AutoML text classification using a pipeline with components from google_cloud_pipeline_components.
The steps performed include:
Create a Dataset resource.
Train an AutoML Model resource.
Creates an Endpoint resource.
Deploys the Model resource to the Endpoint resource.
The components are documented here.
Costs
This tutorial uses billable components of Google Cloud:
Vertex AI
Cloud Storage
Learn about Vertex AI
pricing and Cloud Storage
pricing, and use the Pricing
Calculator
to generate a cost estimate based on your projected usage.
Set up your local development environment
If you are using Colab or Google Cloud Notebook, your environment already meets all the requirements to run this notebook. You can skip this step.
Otherwise, make sure your environment meets this notebook's requirements. You need the following:
The Cloud Storage SDK
Git
Python 3
virtualenv
Jupyter notebook running in a virtual environment with Python 3
The Cloud Storage guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions:
Install and initialize the SDK.
Install Python 3.
Install virtualenv and create a virtual environment that uses Python 3.
Activate that environment and run pip3 install Jupyter in a terminal shell to install Jupyter.
Run jupyter notebook on the command line in a terminal shell to launch Jupyter.
Open this notebook in the Jupyter Notebook Dashboard.
Installation
Install the latest version of Vertex AI SDK for Python. | import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Install the latest GA version of google-cloud-storage library as well. | ! pip3 install -U google-cloud-storage $USER_FLAG | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Install the latest GA version of google-cloud-pipeline-components library as well. | ! pip3 install $USER kfp google-cloud-pipeline-components --upgrade | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Check the versions of the packages you installed. The KFP SDK version should be >=1.6. | ! python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))"
! python3 -c "import google_cloud_pipeline_components; print('google_cloud_pipeline_components version: {}'.format(google_cloud_pipeline_components.__version__))" | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Before you begin
GPU runtime
This tutorial does not require a GPU runtime.
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
Enable the Vertex AI APIs, Compute Engine APIs, and Cloud Storage.
The Google Cloud SDK is already installed in Google Cloud Notebook.
Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.
Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $. | PROJECT_ID = "[your-project-id]" # @param {type:"string"}
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
# Get your GCP project id from gcloud
shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT_ID = shell_output[0]
print("Project ID:", PROJECT_ID)
! gcloud config set project $PROJECT_ID | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Authenticate your Google Cloud account
If you are using Google Cloud Notebook, your environment is already authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.
Otherwise, follow these steps:
In the Cloud Console, go to the Create service account key page.
Click Create service account.
In the Service account name field, enter a name, and click Create.
In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.
Click Create. A JSON file that contains your key downloads to your local environment.
Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. | # If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
import os
import sys
# If on Google Cloud Notebook, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
if "google.colab" in sys.modules:
from google.colab import auth as google_auth
google_auth.authenticate_user()
# If you are running this notebook locally, replace the string below with the
# path to your service account key and run this cell to authenticate your GCP
# account.
elif not os.getenv("IS_TESTING"):
%env GOOGLE_APPLICATION_CREDENTIALS '' | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
When you initialize the Vertex AI SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions.
Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. | BUCKET_NAME = "gs://[your-bucket-name]" # @param {type:"string"}
if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "gs://[your-bucket-name]":
BUCKET_NAME = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Service Account
If you don't know your service account, try to get your service account using gcloud command by executing the second cell below. | SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}
if (
SERVICE_ACCOUNT == ""
or SERVICE_ACCOUNT is None
or SERVICE_ACCOUNT == "[your-service-account]"
):
# Get your GCP project id from gcloud
shell_output = !gcloud auth list 2>/dev/null
SERVICE_ACCOUNT = shell_output[2].strip()
print("Service Account:", SERVICE_ACCOUNT) | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Set service account access for Vertex AI Pipelines
Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account. | ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_NAME
! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_NAME | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Vertex AI Pipelines constants
Setup up the following constants for Vertex AI Pipelines: | PIPELINE_ROOT = "{}/pipeline_root/happydb".format(BUCKET_NAME) | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Additional imports. | import kfp | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Initialize Vertex AI SDK for Python
Initialize the Vertex AI SDK for Python for your project and corresponding bucket. | aip.init(project=PROJECT_ID, staging_bucket=BUCKET_NAME) | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Define AutoML text classification model pipeline that uses components from google_cloud_pipeline_components
Next, you define the pipeline.
Create and deploy an AutoML text classification Model resource using a Dataset resource. | IMPORT_FILE = "gs://cloud-ml-data/NL-classification/happiness.csv"
@kfp.dsl.pipeline(name="automl-text-classification" + TIMESTAMP)
def pipeline(
project: str = PROJECT_ID, region: str = REGION, import_file: str = IMPORT_FILE
):
from google_cloud_pipeline_components import aiplatform as gcc_aip
from google_cloud_pipeline_components.v1.endpoint import (EndpointCreateOp,
ModelDeployOp)
dataset_create_task = gcc_aip.TextDatasetCreateOp(
display_name="train-automl-happydb",
gcs_source=import_file,
import_schema_uri=aip.schema.dataset.ioformat.text.multi_label_classification,
project=project,
)
training_run_task = gcc_aip.AutoMLTextTrainingJobRunOp(
dataset=dataset_create_task.outputs["dataset"],
display_name="train-automl-happydb",
prediction_type="classification",
multi_label=True,
training_fraction_split=0.6,
validation_fraction_split=0.2,
test_fraction_split=0.2,
model_display_name="train-automl-happydb",
project=project,
)
endpoint_op = EndpointCreateOp(
project=project,
location=region,
display_name="train-automl-flowers",
)
ModelDeployOp(
model=training_run_task.outputs["model"],
endpoint=endpoint_op.outputs["endpoint"],
automatic_resources_min_replica_count=1,
automatic_resources_max_replica_count=1,
) | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Compile the pipeline
Next, compile the pipeline. | from kfp.v2 import compiler # noqa: F811
compiler.Compiler().compile(
pipeline_func=pipeline,
package_path="text classification_pipeline.json".replace(" ", "_"),
) | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Run the pipeline
Next, run the pipeline. | DISPLAY_NAME = "happydb_" + TIMESTAMP
job = aip.PipelineJob(
display_name=DISPLAY_NAME,
template_path="text classification_pipeline.json".replace(" ", "_"),
pipeline_root=PIPELINE_ROOT,
enable_caching=False,
)
job.run()
! rm text_classification_pipeline.json | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Click on the generated link to see your run in the Cloud Console.
<!-- It should look something like this as it is running:
<a href="https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png" target="_blank"><img src="https://storage.googleapis.com/amy-jo/images/mp/automl_tabular_classif.png" width="40%"/></a> -->
In the UI, many of the pipeline DAG nodes will expand or collapse when you click on them. Here is a partially-expanded view of the DAG (click image to see larger version).
<a href="https://storage.googleapis.com/amy-jo/images/mp/automl_text_classif.png" target="_blank"><img src="https://storage.googleapis.com/amy-jo/images/mp/automl_text_classif.png" width="40%"/></a>
Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial -- Note: this is auto-generated and not all resources may be applicable for this tutorial:
Dataset
Pipeline
Model
Endpoint
Batch Job
Custom Job
Hyperparameter Tuning Job
Cloud Storage Bucket | delete_dataset = True
delete_pipeline = True
delete_model = True
delete_endpoint = True
delete_batchjob = True
delete_customjob = True
delete_hptjob = True
delete_bucket = True
try:
if delete_model and "DISPLAY_NAME" in globals():
models = aip.Model.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
model = models[0]
aip.Model.delete(model)
print("Deleted model:", model)
except Exception as e:
print(e)
try:
if delete_endpoint and "DISPLAY_NAME" in globals():
endpoints = aip.Endpoint.list(
filter=f"display_name={DISPLAY_NAME}_endpoint", order_by="create_time"
)
endpoint = endpoints[0]
endpoint.undeploy_all()
aip.Endpoint.delete(endpoint.resource_name)
print("Deleted endpoint:", endpoint)
except Exception as e:
print(e)
if delete_dataset and "DISPLAY_NAME" in globals():
if "text" == "tabular":
try:
datasets = aip.TabularDataset.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
dataset = datasets[0]
aip.TabularDataset.delete(dataset.resource_name)
print("Deleted dataset:", dataset)
except Exception as e:
print(e)
if "text" == "image":
try:
datasets = aip.ImageDataset.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
dataset = datasets[0]
aip.ImageDataset.delete(dataset.resource_name)
print("Deleted dataset:", dataset)
except Exception as e:
print(e)
if "text" == "text":
try:
datasets = aip.TextDataset.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
dataset = datasets[0]
aip.TextDataset.delete(dataset.resource_name)
print("Deleted dataset:", dataset)
except Exception as e:
print(e)
if "text" == "video":
try:
datasets = aip.VideoDataset.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
dataset = datasets[0]
aip.VideoDataset.delete(dataset.resource_name)
print("Deleted dataset:", dataset)
except Exception as e:
print(e)
try:
if delete_pipeline and "DISPLAY_NAME" in globals():
pipelines = aip.PipelineJob.list(
filter=f"display_name={DISPLAY_NAME}", order_by="create_time"
)
pipeline = pipelines[0]
aip.PipelineJob.delete(pipeline.resource_name)
print("Deleted pipeline:", pipeline)
except Exception as e:
print(e)
if delete_bucket and "BUCKET_NAME" in globals():
! gsutil rm -r $BUCKET_NAME | notebooks/official/pipelines/google_cloud_pipeline_components_automl_text.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
K-fold CV
K-fold CV(cross-validation) 방법은 데이터 셋을 K개의 sub-set로 분리하는 방법이다. 분리된 K개의 sub-set 중 하나만 제외한 K-1개의 sub-sets를 training set으로 이용하여 K개의 모형 추정한다.
<img src="https://docs.google.com/drawings/d/1JdgUDzuE75LBxqT5sKOhlPgP6umEkvD3Sm-gKnu-jqA/pub?w=762&h=651" style="margin: 0 auto 0 auto;">
Scikit-Learn 의 cross_validation 서브 패키지는 K-Fold를 위한 KFold 클래스를 제공한다. | N = 5
X = np.arange(8 * N).reshape(-1, 2) * 10
y = np.hstack([np.ones(N), np.ones(N) * 2, np.ones(N) * 3, np.ones(N) * 4])
print("X:\n", X, sep="")
print("y:\n", y, sep="")
from sklearn.cross_validation import KFold
cv = KFold(len(X), n_folds=3, random_state=0)
for train_index, test_index in cv:
print("test y:", y[test_index])
print("." * 80 )
print("train y:", y[train_index])
print("=" * 80 ) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
Stratified K-Fold
target class가 어느 한 data set에 몰리지 않도록 한다 | from sklearn.cross_validation import StratifiedKFold
cv = StratifiedKFold(y, n_folds=3, random_state=0)
for train_index, test_index in cv:
print("test X:\n", X[test_index])
print("." * 80 )
print("test y:", y[test_index])
print("=" * 80 ) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
Leave-One-Out (LOO)
하나의 sample만을 test set으로 남긴다. | from sklearn.cross_validation import LeaveOneOut
cv = LeaveOneOut(5)
for train_index, test_index in cv:
print("test X:", X[test_index])
print("." * 80 )
print("test y:", y[test_index])
print("=" * 80 ) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
Label K-Fold
같은 label이 test와 train에 동시에 들어가지 않게 조절
label에 의한 영향을 최소화 | from sklearn.cross_validation import LabelKFold
cv = LabelKFold(y, n_folds=3)
for train_index, test_index in cv:
print("test y:", y[test_index])
print("." * 80 )
print("train y:", y[train_index])
print("=" * 80 ) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
ShuffleSplit
중복된 데이터를 허용 | from sklearn.cross_validation import ShuffleSplit
cv = ShuffleSplit(5)
for train_index, test_index in cv:
print("test X:", X[test_index])
print("=" * 20 ) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
교차 평가 시행
CV는 단순히 데이터 셋을 나누는 역할을 수행할 뿐이다. 실제로 모형의 성능(편향 오차 및 분산)을 구하려면 이렇게 나누어진 데이터셋을 사용하여 평가를 반복하여야 한다. 이 과정을 자동화하는 명령이 cross_val_score() 이다.
cross_val_score(estimator, X, y=None, scoring=None, cv=None)
cross validation iterator cv를 이용하여 X, y data 를 분할하고 estimator에 넣어서 scoring metric을 구하는 과정을 반복
인수
estimator : ‘fit’메서드가 제공되는 모형
X : 배열
독립 변수 데이터
y : 배열
종속 변수 데이터
scoring : 문자열
성능 검증에 사용할 함수
cv : Cross Validator
None 이면 디폴트인 3-폴드 CV
숫자 K 이면 K-폴드 CV
Cross Validator 클래스 객체
반환값
scores
계산된 성능 값의 리스트 | from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X, y, coef = make_regression(n_samples=1000, n_features=1, noise=20, coef=True, random_state=0)
model = LinearRegression()
cv = KFold(1000, 10)
scores = np.zeros(10)
for i, (train_index, test_index) in enumerate(cv):
X_train = X[train_index]
y_train = y[train_index]
X_test = X[test_index]
y_test = y[test_index]
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
scores[i] = mean_squared_error(y_test, y_pred)
scores
from sklearn.cross_validation import cross_val_score
cross_val_score(model, X, y, "mean_squared_error", cv) | 16. 과최적화와 정규화/02. 교차 검증.ipynb | zzsza/Datascience_School | mit |
Camera Calibration with OpenCV
Run the code in the cell below to extract object points and image points for camera calibration. | import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
%matplotlib qt
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*8,3), np.float32)
objp[:,:2] = np.mgrid[0:8, 0:6].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image plane.
# Make a list of calibration images
images = glob.glob('calibration_wide/GO*.jpg')
# Step through the list and search for chessboard corners
for idx, fname in enumerate(images):
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (8,6), None)
# If found, add object points, image points
if ret == True:
objpoints.append(objp)
imgpoints.append(corners)
# Draw and display the corners
cv2.drawChessboardCorners(img, (8,6), corners, ret)
#write_name = 'corners_found'+str(idx)+'.jpg'
#cv2.imwrite(write_name, img)
cv2.imshow('img', img)
cv2.waitKey(500)
cv2.destroyAllWindows() | CarND-Camera-Calibration/camera_calibration.ipynb | phuongxuanpham/SelfDrivingCar | gpl-3.0 |
IO: Reading and preprocess the data
We can define a function which will read the data and process them. | def read_spectra(path_csv):
"""Read and parse data in pandas DataFrames.
Parameters
----------
path_csv : str
Path to the CSV file to read.
Returns
-------
spectra : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
concentration : pandas Series, shape (n_spectra,)
Series containing the concentration of the molecule.
molecule : pandas Series, shape (n_spectra,)
Series containing the type of chemotherapeutic agent.
"""
if not isinstance(path_csv, six.string_types):
raise TypeError("'path_csv' needs to be string. Got {}"
" instead.".format(type(path_csv)))
else:
if not path_csv.endswith('.csv'):
raise ValueError('Wrong file format. Expecting csv file')
data = pd.read_csv(path_csv)
concentration = data['concentration']
molecule = data['molecule']
spectra_string = data['spectra']
spectra = []
for spec in spectra_string:
# remove the first and last bracket and convert to a numpy array
spectra.append(np.fromstring(spec[1:-1], sep=','))
spectra = pd.DataFrame(spectra)
return spectra, concentration, molecule
# read the frequency and get a pandas serie
frequency = pd.read_csv('data/freq.csv')['freqs']
# read all data for training
filenames = ['data/spectra_{}.csv'.format(i)
for i in range(4)]
spectra, concentration, molecule = [], [], []
for filename in filenames:
spectra_file, concentration_file, molecule_file = read_spectra(filename)
spectra.append(spectra_file)
concentration.append(concentration_file)
molecule.append(molecule_file)
# Concatenate in single DataFrame and Serie
spectra = pd.concat(spectra)
concentration = pd.concat(concentration)
molecule = pd.concat(molecule) | Day_2_Software_engineering_best_practices/solutions/03_code_style.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Plot helper functions
We can create two functions: (i) to plot all spectra and (ii) plot the mean spectra with the std intervals.
We will make a "private" function which will be used by both plot types. | def _apply_axis_layout(ax, title):
"""Apply despine style and add labels to axis."""
ax.set_xlabel('Frequency')
ax.set_ylabel('Intensity')
ax.set_title(title)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))
def plot_spectra(frequency, spectra, title=''):
"""Plot a bunch of Raman spectra.
Parameters
----------
frequency : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
spectra : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing all Raman spectra.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = plt.subplots()
ax.plot(frequency, spectra.T)
_apply_axis_layout(ax, title)
return fig, ax
def plot_spectra_by_type(frequency, spectra, classes, title=''):
"""Plot mean spectrum with its variance for a given class.
Parameters
----------
frequency : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
spectra : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing all Raman spectra.
classes : array-like, shape (n_classes,)
Array contining the different spectra class which will be plotted.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = plt.subplots()
for label in np.unique(classes):
label_index = np.flatnonzero(classes == label)
spectra_mean = np.mean(spectra.iloc[label_index], axis=0)
spectra_std = np.std(spectra.iloc[label_index], axis=0)
ax.plot(frequency, spectra_mean, label=label)
ax.fill_between(frequency,
spectra_mean + spectra_std,
spectra_mean - spectra_std,
alpha=0.2)
_apply_axis_layout(ax, title)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
return fig, ax
fig, ax = plot_spectra(frequency, spectra, 'All training spectra')
fig, ax = plot_spectra_by_type(frequency, spectra, molecule)
ax.set_title('Mean spectra in function of the molecules')
fig, ax = plot_spectra_by_type(frequency, spectra, concentration,
'Mean spectra in function of the concentrations') | Day_2_Software_engineering_best_practices/solutions/03_code_style.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Reusability for new data: | spectra_test, concentration_test, molecule_test = read_spectra('data/spectra_4.csv')
plot_spectra(frequency, spectra_test,
'All training spectra')
plot_spectra_by_type(frequency, spectra_test, molecule_test,
'Mean spectra in function of the molecules')
plot_spectra_by_type(frequency, spectra_test, concentration_test,
'Mean spectra in function of the concentrations'); | Day_2_Software_engineering_best_practices/solutions/03_code_style.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Training and testing a machine learning model for classification | def plot_cm(cm, classes, title):
"""Plot a confusion matrix.
Parameters
----------
cm : ndarray, shape (n_classes, n_classes)
Confusion matrix.
classes : array-like, shape (n_classes,)
Array contining the different spectra classes used in the
classification problem.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = plt.subplots()
plt.imshow(cm, interpolation='nearest', cmap='bwr')
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
return fig, ax
for clf in [RandomForestClassifier(random_state=0),
LinearSVC(random_state=0)]:
pipeline = make_pipeline(StandardScaler(),
PCA(n_components=100, random_state=0),
clf)
y_pred = pipeline.fit(spectra, molecule).predict(spectra_test)
plot_cm(confusion_matrix(molecule_test, y_pred),
pipeline.classes_,
'Confusion matrix using {}'.format(clf.__class__.__name__))
print('Accuracy score: {0:.2f}'.format(pipeline.score(spectra_test,
molecule_test))) | Day_2_Software_engineering_best_practices/solutions/03_code_style.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Training and testing a machine learning model for regression | def plot_regression(y_true, y_pred, title):
"""Plot actual vs. predicted scatter plot.
Parameters
----------
y_true : array-like, shape (n_samples,)
Ground truth (correct) target values.
y_pred : array-like, shape (n_samples,)
Estimated targets as returned by a regressor.
title : str
Title added to the plot.
Returns
-------
None
"""
fig, ax = plt.subplots()
ax.scatter(y_true, y_pred)
ax.plot([0, 25000], [0, 25000], '--k')
ax.set_ylabel('Target predicted')
ax.set_xlabel('True Target')
ax.set_title(title)
ax.text(1000, 20000, r'$R^2$=%.2f, MAE=%.2f' % (
r2_score(y_true, y_pred), median_absolute_error(y_true, y_pred)))
ax.set_xlim([0, 25000])
ax.set_ylim([0, 25000])
return fig, ax
def regression_experiment(X_train, X_test, y_train, y_test):
"""Perform regression experiment.
Build a pipeline using PCA and either a Ridge
or a RandomForestRegressor model.
Parameters
----------
X_train : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing training Raman spectra.
X_test : pandas DataFrame, shape (n_spectra, n_freq_points)
DataFrame containing testing Raman spectra.
y_training : pandas Serie, shape (n_spectra,)
Serie containing the training concentrations acting as targets.
y_testing : pandas Serie, shape (n_spectra,)
Serie containing the testing concentrations acting as targets.
Returns
-------
None
"""
for reg in [RidgeCV(), RandomForestRegressor(random_state=0)]:
pipeline = make_pipeline(PCA(n_components=100), reg)
y_pred = pipeline.fit(X_train, y_train).predict(X_test)
plot_regression(y_test, y_pred,
'Regression using {}'.format(reg.__class__.__name__))
regression_experiment(spectra, spectra_test,
concentration, concentration_test)
def fit_params(data):
"""Compute statistics for robustly scale data.
Compute the median and the variance, i.e. the difference
between the 75th and 25th percentiles.
These statistics are used later to scale data.
Parameters
----------
data : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
Returns
-------
median : ndarray, shape (n_freq_point,)
Median for each wavelength.
variance : ndarray, shape (n_freq_point,)
Variance (difference between the 75th and 25th
percentiles) for each wavelength.
"""
median = np.median(data, axis=0)
percentile_25 = np.percentile(data, 25, axis=0)
percentile_75 = np.percentile(data, 75, axis=0)
return median, (percentile_75 - percentile_25)
def transform(data, median, var_25_75):
"""Scale data using robust estimators.
Scale the data by subtracting the median and dividing by the
variance, i.e. the difference between the 75th and 25th percentiles.
Parameters
----------
data : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all Raman spectra.
median : ndarray, shape (n_freq_point,)
Median for each wavelength.
var_25_75 : ndarray, shape (n_freq_point,)
Variance (difference between the 75th and 25th
percentiles) for each wavelength.
Returns
-------
data_scaled : pandas DataFrame, shape (n_spectra, n_freq_point)
DataFrame containing all scaled Raman spectra.
"""
return (data - median) / var_25_75
# compute the statistics on the training data
med, var = fit_params(spectra)
# transform the training and testing data
spectra_scaled = transform(spectra, med, var)
spectra_test_scaled = transform(spectra_test, med, var)
regression_experiment(spectra_scaled, spectra_test_scaled,
concentration, concentration_test) | Day_2_Software_engineering_best_practices/solutions/03_code_style.ipynb | paris-saclay-cds/python-workshop | bsd-3-clause |
Exemple d'un Socket client qui envoi des données | msg = b'GET /ETS/media/Prive/logo/ETS-rouge-devise-ecran.jpg HTTP/1.1\r\nHost:etsmtl.ca\r\n\r\n'
sock.sendall(msg) | IntroductionIOAsync/IntroductionIOAsync.ipynb | luctrudeau/Teaching | lgpl-3.0 |
Exemple d'un Socket qui reçoit des données | recvd = b''
while True:
data = sock.recv(1024)
if not data:
break
recvd += data
sock.shutdown(1)
sock.close()
response = recvd.split(b'\r\n\r\n', 1)
Image(data=response[1]) | IntroductionIOAsync/IntroductionIOAsync.ipynb | luctrudeau/Teaching | lgpl-3.0 |
Quoique les versions de l'interface Socket ont évolué avec les années, surtout sur les plateformes orientées-objet, l'essence de l'interface de 1983 reste très présente dans les implémentations modernes.
2.3.1.5. Making connections
connect(s, name, namelen);
2.3.1.6. Sending and receiving data
cc = sendto(s, buf, len, flags, to, tolen);
msglen = recvfrom(s, buf, len, flags, from, fromlenaddr);
Extrait du manuel system de BSD 4.2 [1983]
Socket Synchrone
Le Socket Berkeley de 1983 est synchrone
Ceci implique que lorsqu'une fonction comme connect, sendto, recvfrom... est invoquée, le processus bloque jusqu'à l'obtention de la réponse.
Notons la présence dans le même document d'une fonction d'I/O asynchrone.
Fail Whale
Le Socket synchrone n'est pas efficace en conditions de charge élevée
Le déploiement de réseaux haute vitesse combiné à l'explosion de la popularité des réseaux sociaux le démontre bien
Les sites de réseau sociaux ne savent pas comment gérer cette impasse.
La situation est telle, que les pages d'erreurs de Twitter deviennent célèbres.
Le Problème:
Lors d'un appel bloquant, le processus et ses ressources sont suspendus. Lorsque la charge augmente, la quantité de ressources suspendue devient ingérable pour le système d'exploitation
La Solution:
Il ne faut pas bloquer
Le Socket Asynchrone
Dès 1983, le socket de Berkley offre un mode asynchrones. Cependant, il n'est pas très utilisé, car ils sont beaucoup plus complexes et prône à l'erreur.
Le Patron Reactor
En 1995, le Patron Reactor est découvert
ce patron simplifie grandement l'I/O Asynchrone
http://www.dre.vanderbilt.edu/~schmidt/PDF/reactor-siemens.pdf
Une influence est du patron Reactor est la fonction Select
Select est la fonction asynchrone présentée dans le même document que le Socket
Exemple d'un Socket client asynchrone qui se connecte
(Avec le Patron Reactor) | import selectors
import socket
import errno
sel = selectors.DefaultSelector()
def connector(sock, mask):
msg = b'GET /ETS/media/Prive/logo/ETS-rouge-devise-ecran.jpg HTTP/1.1\r\nHost:etsmtl.ca\r\n\r\n'
sock.sendall(msg)
# Le connector a pour responsabilité
# d'instancier un nouveau Handler
# et de l'ajouter au Selector
h = HTTPHandler()
sel.modify(sock, selectors.EVENT_READ, h.handle)
class HTTPHandler:
recvd = b''
def handle(self, sock, mask):
data = sock.recv(1024)
if not data:
# Le Handler se retire
# lorsqu'il a terminé.
sel.unregister(sock)
response = self.recvd.split(b'\r\n\r\n', 1)
display(Image(data=response[1]))
else:
self.recvd += data | IntroductionIOAsync/IntroductionIOAsync.ipynb | luctrudeau/Teaching | lgpl-3.0 |
Création d'un Socket Asynchrone | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(False)
try:
sock.connect(("etsmtl.ca" , 80))
except socket.error:
pass # L'exception est toujours lancé!
# C'est normal, l'OS veut nous avertir que
# nous ne sommes pas encore connecté
| IntroductionIOAsync/IntroductionIOAsync.ipynb | luctrudeau/Teaching | lgpl-3.0 |
Enregistrement du Connector | # L'application enregistre le Connector
sel.register(sock, selectors.EVENT_WRITE, connector)
# Le Reactor
while len(sel.get_map()):
events = sel.select()
for key, mask in events:
handleEvent = key.data
handleEvent(key.fileobj, mask) | IntroductionIOAsync/IntroductionIOAsync.ipynb | luctrudeau/Teaching | lgpl-3.0 |
Unit Test
The following unit test is expected to fail until you solve the challenge. | # %load test_check_balance.py
from nose.tools import assert_equal
class TestCheckBalance(object):
def test_check_balance(self):
node = Node(5)
insert(node, 3)
insert(node, 8)
insert(node, 1)
insert(node, 4)
assert_equal(check_balance(node), True)
node = Node(5)
insert(node, 3)
insert(node, 8)
insert(node, 9)
insert(node, 10)
assert_equal(check_balance(node), False)
print('Success: test_check_balance')
def main():
test = TestCheckBalance()
test.test_check_balance()
if __name__ == '__main__':
main() | interactive-coding-challenges/graphs_trees/check_balance/check_balance_challenge.ipynb | ThunderShiviah/code_guild | mit |
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 (session.run(init)),
# the loss variable will be initialized and ready to be computed
with tf.Session() as session: # Create a session and print the output
session.run(init) # Initializes the variables
print(session.run(loss)) # Prints the loss | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Writing and running programs in TensorFlow has the following steps:
Create Tensors (variables) that are not yet executed/evaluated.
Write operations between those Tensors.
Initialize your Tensors.
Create a Session.
Run the Session. This will run the operations you'd written above.
Therefore, when we created a variable for the loss, we simply defined the loss as a function of other quantities, but did not evaluate its value. To evaluate it, we had to run init=tf.global_variables_initializer(). That initialized the loss variable, and in the last line we were finally able to evaluate the value of loss and print its value.
Now let us look at an easy example. Run the cell below: | a = tf.constant(2)
b = tf.constant(10)
c = tf.multiply(a,b)
print(c) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 session and run it. | sess = tf.Session()
print(sess.run(c)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 dictionary" (feed_dict variable). Below, we created a placeholder for x. This allows us to pass in a number later when we run the session. | # 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() | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 computation, you are telling TensorFlow how to construct a computation graph. The computation graph can have some placeholders whose values you will specify only later. Finally, when you run the session, you are telling TensorFlow to execute the computation graph.
1.1 - Linear function
Lets start this programming exercise by computing the following equation: $Y = WX + b$, where $W$ and $X$ are random matrices and b is a random vector.
Exercise: Compute $WX + b$ where $W, X$, and $b$ are drawn from a random normal distribution. W is of shape (4, 3), X is (3,1) and b is (4,1). As an example, here is how you would define a constant X that has shape (3,1):
```python
X = tf.constant(np.random.randn(3,1), name = "X")
```
You might find the following functions helpful:
- tf.matmul(..., ...) to do a matrix multiplication
- tf.add(..., ...) to do an addition
- np.random.randn(...) to initialize randomly | # 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 -- runs the session for Y = WX + b
"""
np.random.seed(1)
### START CODE HERE ### (4 lines of code)
X = tf.constant(np.random.randn(3,1), name = 'X')
W = tf.constant(np.random.randn(4,3), name = 'W')
b = tf.constant(np.random.randn(4,1), name = 'b')
Y = tf.constant(np.random.randn(4,1), name = 'Y')
### END CODE HERE ###
# Create the session using tf.Session() and run it with sess.run(...) on the variable you want to calculate
### START CODE HERE ###
sess = tf.Session()
result = sess.run(tf.add(tf.matmul(W,X),b))
### END CODE HERE ###
# close the session
sess.close()
return result
print( "result = " + str(linear_function())) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output :
<table>
<tr>
<td>
**result**
</td>
<td>
[[-2.15657382]
[ 2.95891446]
[-1.08926781]
[-0.84538042]]
</td>
</tr>
</table>
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 sigmoid function of an input.
You will do this exercise using a placeholder variable x. When running the session, you should use the feed dictionary to pass in the input z. In this exercise, you will have to (i) create a placeholder x, (ii) define the operations needed to compute the sigmoid using tf.sigmoid, and then (iii) run the session.
Exercise : Implement the sigmoid function below. You should use the following:
tf.placeholder(tf.float32, name = "...")
tf.sigmoid(...)
sess.run(..., feed_dict = {x: z})
Note that there are two typical ways to create and use sessions in tensorflow:
Method 1:
```python
sess = tf.Session()
Run the variables initialization (if needed), run the operations
result = sess.run(..., feed_dict = {...})
sess.close() # Close the session
**Method 2:**python
with tf.Session() as sess:
# run the variables initialization (if needed), run the operations
result = sess.run(..., feed_dict = {...})
# This takes care of closing the session for you :)
``` | # 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.placeholder(tf.float32, name='x')
# compute sigmoid(x)
sigmoid = tf.sigmoid(x)
# Create a session, and run it. Please use the method 2 explained above.
# You should use a feed_dict to pass z's value to x.
with tf.Session() as sess:
# Run session and call the output "result"
result = sess.run(sigmoid, feed_dict = {x: z})
### END CODE HERE ###
return result
print ("sigmoid(0) = " + str(sigmoid(0)))
print ("sigmoid(12) = " + str(sigmoid(12))) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output :
<table>
<tr>
<td>
**sigmoid(0)**
</td>
<td>
0.5
</td>
</tr>
<tr>
<td>
**sigmoid(12)**
</td>
<td>
0.999994
</td>
</tr>
</table>
<font color='blue'>
To summarize, you how know how to:
1. Create placeholders
2. Specify the computation graph corresponding to operations you want to compute
3. Create the session
4. Run the session, using a feed dictionary if necessary to specify placeholder variables' values.
1.3 - Computing the Cost
You can also use a built-in function to compute the cost of your neural network. So instead of needing to write code to compute this as a function of $a^{2}$ and $y^{(i)}$ for i=1...m:
$$ J = - \frac{1}{m} \sum_{i = 1}^m \large ( \small y^{(i)} \log a^{ [2] (i)} + (1-y^{(i)})\log (1-a^{ [2] (i)} )\large )\small\tag{2}$$
you can do it in one line of code in tensorflow!
Exercise: Implement the cross entropy loss. The function you will use is:
tf.nn.sigmoid_cross_entropy_with_logits(logits = ..., labels = ...)
Your code should input z, compute the sigmoid (to get a) and then compute the cross entropy cost $J$. All this can be done using one call to tf.nn.sigmoid_cross_entropy_with_logits, which computes
$$- \frac{1}{m} \sum_{i = 1}^m \large ( \small y^{(i)} \log \sigma(z^{2}) + (1-y^{(i)})\log (1-\sigma(z^{2})\large )\small\tag{2}$$ | # 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 "z" and "y" in this class are respectively called "logits" and "labels"
in the TensorFlow documentation. So logits will feed into z, and labels into y.
Returns:
cost -- runs the session of the cost (formula (2))
"""
### START CODE HERE ###
# Create the placeholders for "logits" (z) and "labels" (y) (approx. 2 lines)
z = tf.placeholder(tf.float32, name='logits')
y = tf.placeholder(tf.float32, name='labels')
# Use the loss function (approx. 1 line)
cost = tf.nn.sigmoid_cross_entropy_with_logits(logits = z, labels = y)
# Create a session (approx. 1 line). See method 1 above.
sess = tf.Session()
# Run the session (approx. 1 line).
cost = sess.run(cost, feed_dict = {z:logits, y:labels})
# Close the session (approx. 1 line). See method 1 above.
sess.close()
### END CODE HERE ###
return cost
logits = sigmoid(np.array([0.2,0.4,0.7,0.9]))
cost = cost(logits, np.array([0,0,1,1]))
print ("cost = " + str(cost)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output :
<table>
<tr>
<td>
**cost**
</td>
<td>
[ 1.00538719 1.03664088 0.41385433 0.39956614]
</td>
</tr>
</table>
1.4 - Using One Hot encodings
Many 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, then you might have the following y vector which you will need to convert as follows:
<img src="images/onehot.png" style="width:600px;height:150px;">
This is called a "one hot" encoding, because in the converted representation exactly one element of each column is "hot" (meaning set to 1). To do this conversion in numpy, you might have to write a few lines of code. In tensorflow, you can use one line of code:
tf.one_hot(labels, depth, axis)
Exercise: Implement the function below to take one vector of labels and the total number of classes $C$, and return the one hot encoding. Use tf.one_hot() to do this. | # 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.
Arguments:
labels -- vector containing the labels
C -- number of classes, the depth of the one hot dimension
Returns:
one_hot -- one hot matrix
"""
### START CODE HERE ###
# Create a tf.constant equal to C (depth), name it 'C'. (approx. 1 line)
C = tf.constant(C, name='C')
# Use tf.one_hot, be careful with the axis (approx. 1 line)
one_hot_matrix = tf.one_hot(labels, C, axis=0)
# Create the session (approx. 1 line)
sess = tf.Session()
# Run the session (approx. 1 line)
one_hot = sess.run(one_hot_matrix)
# Close the session (approx. 1 line). See method 1 above.
sess.close()
### END CODE HERE ###
return one_hot
labels = np.array([1,2,3,0,2,1])
one_hot = one_hot_matrix(labels, C = 4)
print ("one_hot = " + str(one_hot)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**one_hot**
</td>
<td>
[[ 0. 0. 0. 1. 0. 0.]
[ 1. 0. 0. 0. 0. 1.]
[ 0. 1. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 0. 0.]]
</td>
</tr>
</table>
1.5 - Initialize with zeros and ones
Now you will learn how to initialize a vector of zeros and ones. The function you will be calling is tf.ones(). To initialize with zeros you could use tf.zeros() instead. These functions take in a shape and return an array of dimension shape full of zeros and ones respectively.
Exercise: Implement the function below to take in a shape and to return an array (of the shape's dimension of ones).
tf.ones(shape) | # 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(...). (approx. 1 line)
ones = tf.ones(shape)
# Create the session (approx. 1 line)
sess = tf.Session()
# Run the session to compute 'ones' (approx. 1 line)
ones = sess.run(ones)
# Close the session (approx. 1 line). See method 1 above.
sess.close()
### END CODE HERE ###
return ones
print ("ones = " + str(ones([3]))) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**ones**
</td>
<td>
[ 1. 1. 1.]
</td>
</tr>
</table>
2 - Building your first neural network in tensorflow
In 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 computation graph
Run the graph
Let's delve into the problem you'd like to solve!
2.0 - Problem statement: SIGNS Dataset
One afternoon, with some friends we decided to teach our computers to decipher sign language. We spent a few hours taking pictures in front of a white wall and came up with the following dataset. It's now your job to build an algorithm that would facilitate communications from a speech-impaired person to someone who doesn't understand sign language.
Training set: 1080 pictures (64 by 64 pixels) of signs representing numbers from 0 to 5 (180 pictures per number).
Test set: 120 pictures (64 by 64 pixels) of signs representing numbers from 0 to 5 (20 pictures per number).
Note that this is a subset of the SIGNS dataset. The complete dataset contains many more signs.
Here are examples for each number, and how an explanation of how we represent the labels. These are the original pictures, before we lowered the image resolutoion to 64 by 64 pixels.
<img src="images/hands.png" style="width:800px;height:350px;"><caption><center> <u><font color='purple'> Figure 1</u><font color='purple'>: SIGNS dataset <br> <font color='black'> </center>
Run the following code to load the dataset. | # Loading the dataset
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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]))) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 = convert_to_one_hot(Y_train_orig, 6)
Y_test = convert_to_one_hot(Y_test_orig, 6)
print ("number of training examples = " + str(X_train.shape[1]))
print ("number of test examples = " + str(X_test.shape[1]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 tensorflow model that is almost the same as one you have previously built in numpy for cat recognition (but now using a softmax output). It is a great occasion to compare your numpy implementation to the tensorflow one.
The model is LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX. The SIGMOID output layer has been converted to a SOFTMAX. A SOFTMAX layer generalizes SIGMOID to when there are more than two classes.
2.1 - Create placeholders
Your first task is to create placeholders for X and Y. This will allow you to later pass your training data in when you run your session.
Exercise: Implement the function below to create the placeholders in tensorflow. | # 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 -- placeholder for the data input, of shape [n_x, None] and dtype "float"
Y -- placeholder for the input labels, of shape [n_y, None] and dtype "float"
Tips:
- You will use None because it let's us be flexible on the number of examples you will for the placeholders.
In fact, the number of examples during test/train is different.
"""
### START CODE HERE ### (approx. 2 lines)
X = tf.placeholder(dtype=tf.float32, shape=[n_x, None], name='X')
Y = tf.placeholder(dtype=tf.float32, shape=[n_y, None], name='Y')
keep_prob = tf.placeholder(dtype=tf.float32, shape=[2], name='keep_prob')
### END CODE HERE ###
return X, Y, keep_prob
X, Y, keep_prob = create_placeholders(12288, 6)
print ("X = " + str(X))
print ("Y = " + str(Y)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**X**
</td>
<td>
Tensor("Placeholder_1:0", shape=(12288, ?), dtype=float32) (not necessarily Placeholder_1)
</td>
</tr>
<tr>
<td>
**Y**
</td>
<td>
Tensor("Placeholder_2:0", shape=(10, ?), dtype=float32) (not necessarily Placeholder_2)
</td>
</tr>
</table>
2.2 - Initializing the parameters
Your second task is to initialize the parameters in tensorflow.
Exercise: Implement the function below to initialize the parameters in tensorflow. You are going use Xavier Initialization for weights and Zero Initialization for biases. The shapes are given below. As an example, to help you, for W1 and b1 you could use:
python
W1 = tf.get_variable("W1", [25,12288], initializer = tf.contrib.layers.xavier_initializer(seed = 1))
b1 = tf.get_variable("b1", [25,1], initializer = tf.zeros_initializer())
Please use seed = 1 to make sure your results match ours. | # 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]
W3 : [6, 12]
b3 : [6, 1]
Returns:
parameters -- a dictionary of tensors containing W1, b1, W2, b2, W3, b3
"""
tf.set_random_seed(1) # so that your "random" numbers match ours
### START CODE HERE ### (approx. 6 lines of code)
W1 = tf.get_variable("W1", [25,12288], initializer = tf.contrib.layers.xavier_initializer(seed=1))
b1 = tf.get_variable("b1", [25,1], initializer = tf.zeros_initializer())
W2 = tf.get_variable('W2', [12,25], initializer = tf.contrib.layers.xavier_initializer(seed=1))
b2 = tf.get_variable('b2', [12,1], initializer = tf.zeros_initializer())
W3 = tf.get_variable('W3', [6,12], initializer = tf.contrib.layers.xavier_initializer(seed=1))
b3 = tf.get_variable('b3', [6,1], initializer = tf.zeros_initializer())
### END CODE HERE ###
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2,
"W3": W3,
"b3": b3}
return parameters
tf.reset_default_graph()
with tf.Session() as sess:
parameters = initialize_parameters()
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"])) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**W1**
</td>
<td>
< tf.Variable 'W1:0' shape=(25, 12288) dtype=float32_ref >
</td>
</tr>
<tr>
<td>
**b1**
</td>
<td>
< tf.Variable 'b1:0' shape=(25, 1) dtype=float32_ref >
</td>
</tr>
<tr>
<td>
**W2**
</td>
<td>
< tf.Variable 'W2:0' shape=(12, 25) dtype=float32_ref >
</td>
</tr>
<tr>
<td>
**b2**
</td>
<td>
< tf.Variable 'b2:0' shape=(12, 1) dtype=float32_ref >
</td>
</tr>
</table>
As expected, the parameters haven't been evaluated yet.
2.3 - Forward propagation in tensorflow
You will now implement the forward propagation module in tensorflow. The function will take in a dictionary of parameters and it will complete the forward pass. The functions you will be using are:
tf.add(...,...) to do an addition
tf.matmul(...,...) to do a matrix multiplication
tf.nn.relu(...) to apply the ReLU activation
Question: Implement the forward pass of the neural network. We commented for you the numpy equivalents so that you can compare the tensorflow implementation to numpy. It is important to note that the forward propagation stops at z3. The reason is that in tensorflow the last linear layer output is given as input to the function computing the loss. Therefore, you don't need a3! | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters, keep_prob):
"""
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 dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"
the shapes are given in initialize_parameters
Returns:
Z3 -- the output of the last LINEAR unit
"""
# Retrieve the parameters from the dictionary "parameters"
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
W3 = parameters['W3']
b3 = parameters['b3']
### START CODE HERE ### (approx. 5 lines) # Numpy Equivalents:
Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1
A1 = tf.nn.relu(Z1) # A1 = relu(Z1)
A1_dropout = tf.nn.dropout(A1, keep_prob[0]) # apply dropout (*)
Z2 = tf.add(tf.matmul(W2, A1_dropout), b2) # Z2 = np.dot(W2, a1) + b2
A2 = tf.nn.relu(Z2) # A2 = relu(Z2)
A2_dropout = tf.nn.dropout(A2, keep_prob[1]) # apply dropout (*)
Z3 = tf.add(tf.matmul(W3, A2_dropout), b3) # Z3 = np.dot(W3,Z2) + b3
### END CODE HERE ###
return Z3
tf.reset_default_graph()
with tf.Session() as sess:
X, Y, keep_prob = create_placeholders(12288, 6)
parameters = initialize_parameters()
Z3 = forward_propagation(X, parameters, keep_prob)
print("Z3 = " + str(Z3)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**Z3**
</td>
<td>
Tensor("Add_2:0", shape=(6, ?), dtype=float32)
</td>
</tr>
</table>
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 cost
As seen before, it is very easy to compute the cost using:
python
tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = ..., labels = ...))
Question: Implement the cost function below.
- It is important to know that the "logits" and "labels" inputs of tf.nn.softmax_cross_entropy_with_logits are expected to be of shape (number of examples, num_classes). We have thus transposed Z3 and Y for you.
- Besides, tf.reduce_mean basically does the summation over the examples. | # 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 cost function
"""
# to fit the tensorflow requirement for tf.nn.softmax_cross_entropy_with_logits(...,...)
logits = tf.transpose(Z3)
labels = tf.transpose(Y)
### START CODE HERE ### (1 line of code)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))
### END CODE HERE ###
return cost
tf.reset_default_graph()
with tf.Session() as sess:
X, Y, keep_prob = create_placeholders(12288, 6)
parameters = initialize_parameters()
Z3 = forward_propagation(X, parameters, keep_prob)
cost = compute_cost(Z3, Y)
print("cost = " + str(cost)) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**cost**
</td>
<td>
Tensor("Mean:0", shape=(), dtype=float32)
</td>
</tr>
</table>
2.5 - Backward propagation & parameter updates
This is where you become grateful to programming frameworks. All the backpropagation and the parameters update is taken care of in 1 line of code. It is very easy to incorporate this line in the model.
After you compute the cost function. You will create an "optimizer" object. You have to call this object along with the cost when running the tf.session. When called, it will perform an optimization on the given cost with the chosen method and learning rate.
For instance, for gradient descent the optimizer would be:
python
optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(cost)
To make the optimization you would do:
python
_ , c = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})
This computes the backpropagation by passing through the tensorflow graph in the reverse order. From cost to inputs.
Note When coding, we often use _ as a "throwaway" variable to store values that we won't need to use later. Here, _ takes on the evaluated value of optimizer, which we don't need (and c takes the value of the cost variable).
2.6 - Building the model
Now, you will bring it all together!
Exercise: Implement the model. You will be calling the functions you had previously implemented. | def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 3000, 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 = 12288, number of training examples = 1080)
Y_train -- test set, of shape (output size = 6, number of training examples = 1080)
X_test -- training set, of shape (input size = 12288, number of training examples = 120)
Y_test -- test set, of shape (output size = 6, number of test examples = 120)
learning_rate -- learning rate of the optimization
num_epochs -- number of epochs of the optimization loop
minibatch_size -- size of a minibatch
print_cost -- True to print the cost every 100 epochs
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
tf.set_random_seed(1) # to keep consistent results
seed = 3 # to keep consistent results
(n_x, m) = X_train.shape # (n_x: input size, m : number of examples in the train set)
n_y = Y_train.shape[0] # n_y : output size
costs = [] # To keep track of the cost
# Create Placeholders of shape (n_x, n_y)
### START CODE HERE ### (1 line)
X, Y, keep_prob = create_placeholders(n_x, n_y)
### END CODE HERE ###
# Initialize parameters
### START CODE HERE ### (1 line)
parameters = initialize_parameters()
### END CODE HERE ###
# Forward propagation: Build the forward propagation in the tensorflow graph
### START CODE HERE ### (1 line)
Z3 = forward_propagation(X, parameters, keep_prob)
### END CODE HERE ###
# Cost function: Add cost function to tensorflow graph
### START CODE HERE ### (1 line)
cost = compute_cost(Z3, Y)
### END CODE HERE ###
# Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.
### START CODE HERE ### (1 line)
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)
### END CODE HERE ###
# Initialize all the variables
init = tf.global_variables_initializer()
keep_prob_train = [0.9, 1.0]
# Start the session to compute the tensorflow graph
with tf.Session() as sess:
# Run the initialization
sess.run(init)
# Do the training loop
for epoch in range(num_epochs):
epoch_cost = 0. # Defines a cost related to an epoch
num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
seed = seed + 1
minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
# IMPORTANT: The line that runs the graph on a minibatch.
# Run the session to execute the "optimizer" and the "cost", the feedict should contain a minibatch for (X,Y).
### START CODE HERE ### (1 line)
_ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y, keep_prob:keep_prob_train})
### END CODE HERE ###
epoch_cost += minibatch_cost / num_minibatches
# Print the cost every epoch
if print_cost == True and epoch % 100 == 0:
print ("Cost after epoch %i: %f" % (epoch, epoch_cost))
if print_cost == True and epoch % 5 == 0:
costs.append(epoch_cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
# lets save the parameters in a variable
parameters = sess.run(parameters)
print ("Parameters have been trained!")
# Calculate the correct predictions
correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))
# Calculate accuracy on the test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print ("Train Accuracy:", accuracy.eval({X: X_train, Y: Y_train, keep_prob : [1.0, 1.0]}))
print ("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test, keep_prob : [1.0, 1.0]}))
return parameters | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
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 and come back in 5 minutes! | parameters = model(X_train, Y_train, X_test, Y_test) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
Expected Output:
<table>
<tr>
<td>
**Train Accuracy**
</td>
<td>
0.999074
</td>
</tr>
<tr>
<td>
**Test Accuracy**
</td>
<td>
0.716667
</td>
</tr>
</table>
Amazing, your algorithm can recognize a sign representing a figure between 0 and 5 with 71.7% accuracy.
Insights:
- Your model seems big enough to fit the training set well. However, given the difference between train and test accuracy, you could try to add L2 or dropout regularization to reduce overfitting.
- Think about the session as a block of code to train the model. Each time you run the session on a minibatch, it trains the parameters. In total you have run the session a large number of times (1500 epochs) until you obtained well trained parameters.
2.7 - Test with your own image (optional / ungraded exercise)
Congratulations on finishing this assignment. You can now take a picture of your hand and see the output of your model. To do that:
1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub.
2. Add your image to this Jupyter Notebook's directory, in the "images" folder
3. Write your image's name in the following code
4. Run the code and check if the algorithm is right! | 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(image, size=(64,64)).reshape((1, 64*64*3)).T
my_image_prediction = predict(my_image, parameters)
plt.imshow(image)
print("Your algorithm predicts: y = " + str(np.squeeze(my_image_prediction))) | deep_learning_ai/Tensorflow+Tutorial+dropout.ipynb | trangel/Data-Science | gpl-3.0 |
For a detailed explanation of the above, please refer to Rates Information. | response = oanda.create_order(account_id,
instrument = "AUD_USD",
units=1000,
side="buy",
type="limit",
price=0.7420,
expiry=trade_expire)
print(response)
pd.Series(response["orderOpened"])
order_id = response["orderOpened"]['id'] | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
Getting Open Orders
get_orders(self, account_id, **params) | response = oanda.get_orders(account_id)
print(response)
pd.DataFrame(response['orders']) | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
Getting Specific Order Information
get_order(self, account_id, order_id, **params) | response = oanda.get_orders(account_id)
id = response['orders'][0]['id']
oanda.get_order(account_id, order_id=id) | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
Modify Order
modify_order(self, account_id, order_id, **params) | response = oanda.get_orders(account_id)
id = response['orders'][0]['id']
oanda.modify_order(account_id, order_id=id, price=0.7040) | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
Close Order
close_order(self, account_id, order_id, **params) | response = oanda.get_orders(account_id)
id = response['orders'][0]['id']
oanda.close_order(account_id, order_id=id) | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
Now when we check the orders. The above order has been closed and removed without being filled. There is only one outstanding order now. | oanda.get_orders(account_id) | Oanda v1 REST-oandapy/04.00 Order Management.ipynb | anthonyng2/FX-Trading-with-Python-and-Oanda | mit |
This is a bog standard user registration endpoint. We create a form, check if it's valid, shove that information on a user model and then into the database and redirect off. If it's not valid or if it wasn't submitted (the user just navigated to the page), we render out some HTML.
It's all very basic, well trodden code. Besides, who wants to do registration again? It's boring. We want to do the interesting stuff. But there's some very real consequences to this code:
It's not testable
Everything is wrapped up together, form validation, database stuff, rendering. Honestly, I'm not interested in testing if SQLAlchemy, WTForms of Jinja2 work -- they have their own tests. So testing this ends up looking like this: | @mock.patch('myapp.views.RegisterUserForm')
@mock.patch('myapp.views.db')
@mock.patch('myapp.views.redirect')
@mock.patch('myapp.views.url_for')
@mock.patch('myapp.views.render_template')
def test_register_new_user(render, url_for, redirect, db, form):
# TODO: Write test
assert True | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
What's even the point of this? We're just testing if Mock works at this point. There's actual things we can do to make it more testable, but before delving into that,
It hides logic
If registering a user was solely about, "Fill this form out and we'll shove it into a database" there wouldn't be a blog post here. However, there is some logic hiding out here in the form: | class RegisterUserForm(Form):
def validate_username(self, field):
if User.query.filter(User.username == field.data).count():
raise ValidationError("Username in use already")
def validate_email(self, field):
if User.query.filter(User.email == field.data).count():
raise ValidationError("Email in use already") | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
When we call RegisterUserForm.validate_on_submit it also runs these two methods. However, I'm not of the opinion that the form should talk to the database at all, let alone run validation against database contents. So, let's write a little test harness that can prove that an existing user with a given username and email causes us to not register: | from myapp.forms import RegisterUserForm
from myapp.models import User
from collections import namedtuple
from unittest import mock
FakeData = namedtuple('User', ['username', 'email', 'password', 'confirm_password'])
def test_existing_username_fails_validation():
test_data = FakeData('fred', '[email protected]', 'a', 'a')
UserModel = mock.Mock()
UserModel.query.filter.count.return_value = 1
form = RegisterUserForm(obj=test_data)
with mock.patch('myapp.forms.User', UserModel):
form.validate()
assert form.errors['username'] == "Username in use already"
def test_existing_email_fails_validation():
test_user = FakeUser('fred', '[email protected]', 'a', 'a')
UserModel = mock.Mock()
UserModel.query.filter.first.return_value = True
form = RegisterUserForm(obj=test_user)
with mock.patch('myapp.forms.User', UserModel):
form.validate()
assert form.errors['username'] == "Email in use already" | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
If these pass -- which they should, but you may have to install mock if you're not on Python 3 -- I think we should move the username and email validation into their own callables that are independently testable: | def is_username_free(username):
return User.query.filter(User.username == username).count() == 0
def is_email_free(email):
return User.query.filter(User.email == email).count() == 0 | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
And then use these in the endpoint itself: | @app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterUserForm()
if form.validate_on_submit():
if not is_username_free(form.username.data):
form.errors['username'] = ['Username in use already']
return render_template('register.html', form=form)
if not is_email_free(form.email.data):
form.errors['email'] = ['Email in use already']
return render_template('register.html', form=form)
user = User()
form.populate_obj(user)
db.session.add(user)
db.session.commit()
return redirect('homepage')
return render_template('register.html', form=form) | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
This is really hard to test, so instead of even attempting that -- being honest, I spent the better part of an hour attempting to test the actual endpoint and it was just a complete mess -- let's extract out the actual logic and place it into it's own callable: | class OurValidationError(Exception):
def __init__(self, msg, field):
self.msg = msg
self.field = field
def register_user(username, email, password):
if not is_username_free(username):
raise OurValidationError('Username in use already', 'username')
if not is_email_free(email):
raise OurValidationError('Email in use already', 'email')
user = User(username=username, email=email, password=password)
db.session.add(user)
db.session.commit()
@app.route('/register', methods=['GET', 'POST'])
def register_user_view():
form = RegisterUserForm()
if form.validate_on_submit():
try:
register_user(form.username.data, form.email.data, form.password.data)
except OurValidationError as e:
form.errors[e.field] = [e.msg]
return render_template('register.html', form=form)
else:
return redirect('homepage')
return render_template('register.html', form=form) | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
Now we're beginning to see the fruits of our labors. These aren't the easiest functions to test, but there's less we need to mock out in order to test the actual logic we're after. | def test_duplicated_user_raises_error():
ChasteValidator = mock.Mock(return_value=False)
with mock.patch('myapp.logic.is_username_free', ChasteValidator):
with pytest.raises(OurValidationError) as excinfo:
register_user('fred', '[email protected]', 'fredpassword')
assert excinfo.value.msg == 'Username in use already'
assert excinfo.value.field == 'username'
def test_duplicated_user_raises_error():
ChasteValidator = mock.Mock(return_value=False)
PromisciousValidator = mock.Mock(return_value=True)
with mock.patch('myapp.logic.is_username_free', PromisciousValidator),
mock.patch('myapp.logic.is_email_free', ChasteValidator):
with pytest.raises(OurValidationError) as excinfo:
register_user('fred', '[email protected]', 'fredpassword')
assert excinfo.value.msg == 'Email in use already'
assert excinfo.value.field == 'email'
def test_register_user_happy_path():
PromisciousValidator = mock.Mock(return_value=True)
MockDB = mock.Mock()
with mock.patch('myapp.logic.is_username_free', PromisciousValidator),
mock.patch('myapp.logic.is_email_free', ChasteValidator),
mock.patch('myapp.logic.db', MockDB):
register_user('fred', '[email protected]', 'freddpassword')
assert MockDB.commit.call_count | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
Of course, we should also write tests for the controller. I'll leave that as an exercise. However, there's something very important we're learning from these tests. We have to mock.patch everything still. Our validators lean directly on the database, our user creation leans directly on the database, everything leans directly on the database. And I don't want to do that, we've found that it makes testing hard. We're also seeing if we need to add another registration restriction -- say we don't like people named Fred so we won't let anyone register with a username or email containing Fred in it -- we need to crack open the register_user function and add it directly. We can solve both of these problems.
The Database Problem
To address the database problem we need to realize something. We're not actually interested in the database, we're interested in the data it stores. And since we're interested in finding data rather than where it's stored at, why not stuff an interface in the way? | from abc import ABC, abstractmethod
class AbstractUserRepository(ABC):
@abstractmethod
def find_by_username(self, username):
pass
@abstractmethod
def find_by_email(self, email):
pass
@abstractmethod
def persist(self, user):
pass | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
Hmm...that's interesting. Since we'll end up depending on this instead of a concrete implementation, we can run our tests completely in memory and production on top of SQLAlchemy, Mongo, a foreign API, whatever.
But we need to inject it into our validators instead of reaching out into the global namespace like we currently are. | def is_username_free(user_repository):
def is_username_free(username):
return not user_repository.find_by_username(username)
return is_username_free
def is_email_free(user_repository):
def is_email_free(email):
return not user_repository.find_by_email(email)
return is_email_free | hexagonal/refactoring_and_interfaces.ipynb | justanr/notebooks | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.