markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
and do feature selection before training | X_train_selected = select_features(X_train, y_train)
ada = LinearRegression()
ada.fit(X_train_selected, y_train) | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Now lets check how good our prediction is: | X_test_selected = X_test[X_train_selected.columns]
y_pred = pd.Series(ada.predict(X_test_selected), index=X_test_selected.index) | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
The prediction is for the next day, so for drawing we need to shift 1 step back: | plt.figure(figsize=(15, 6))
y.plot(ax=plt.gca())
y_pred.plot(ax=plt.gca(), legend=None, marker=".") | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Model background
Here is an example based on the Henry saltwater intrusion problem. The synthetic model is a 2-dimensional SEAWAT model (X-Z domain) with 1 row, 120 columns and 20 layers. The left boundary is a specified flux of freshwater, the right boundary is a specified head and concentration saltwater boundary. ... | import pyemu | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
First create a linear_analysis object. We will use err_var derived type, which replicates the behavior of the PREDVAR suite of PEST as well as ident_par utility. We pass it the name of the jacobian matrix file. Since we don't pass an explicit argument for parcov or obscov, pyemu attempts to build them from the para... | la = pyemu.ErrVar(jco=os.path.join("henry", "pest.jcb"),
omitted_parameters=["mult1","mult2"])
print(la.jco.shape) #without the omitted parameter or the prior info
la.forecast_names | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
Parameter identifiability
The errvar dervied type exposes a method to get a pandas dataframe of parameter identifiability information. Recall that parameter identifiability is expressed as $d_i = \Sigma(\mathbf{V}_{1i})^2$, where $d_i$ is the parameter identifiability, which ranges from 0 (not identified by the data) ... | s = la.qhalfx.s
import pylab as plt
figure = plt.figure(figsize=(10, 5))
ax = plt.subplot(111)
ax.plot(s.x)
ax.set_title("singular spectrum")
ax.set_ylabel("power")
ax.set_xlabel("singular value")
ax.set_xlim(0,20)
plt.show() | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
We see that the singluar spectrum decays rapidly (not uncommon) and that we can really only support about 3 right singular vectors even though we have 600+ parameters in the inverse problem.
Let's get the identifiability dataframe at 15 singular vectors: | ident_df = la.get_identifiability_dataframe(3) # the method is passed the number of singular vectors to include in V_1
ident_df.sort_values(by="ident").iloc[0:10] | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
Plot the indentifiability:
We see that the global_k parameter has a much higher identifiability than any one of the 600 pilot points
Forecast error variance
Now let's explore the error variance of the forecasts we are interested in. We will use an extended version of the forecast error variance equation:
$\sigma_{s... | sing_vals = np.arange(40) | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
The errvar derived type exposes a convience method to get a multi-index pandas dataframe with each of the terms of the error variance equation: | errvar_df = la.get_errvar_dataframe(sing_vals)
errvar_df.iloc[0:10] | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
plot the error variance components for each forecast: | fig = plt.figure(figsize=(10, 10))
ax_1, ax_2= plt.subplot(211), plt.subplot(212)
axes = [ax_1,ax_2]
colors = {"first": 'g', "second": 'b', "third": 'c'}
max_idx = 19
idx = sing_vals[:max_idx]
for ipred, pred in enumerate(la.forecast_names):
pred = pred.lower()
ax = axes[ipred]
ax.set_title(pred)
first... | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
Here we see the trade off between getting a good fit to push down the null-space (1st) term and the penalty for overfitting (the rise of the solution space (2nd) term)). The sum of the first two terms in the "appearent" error variance (e.g. the uncertainty that standard analyses would yield) without considering the co... | schur = la.get(astype=pyemu.Schur)
schur_prior = schur.prior_forecast
schur_post = schur.posterior_forecast
print("{0:10s} {1:>12s} {2:>12s} {3:>12s} {4:>12s}"
.format("forecast","errvar prior","errvar min",
"schur prior", "schur post"))
for ipred, pred in enumerate(la.forecast_names):
first = e... | examples/errvarexample_henry.ipynb | jtwhite79/pyemu | bsd-3-clause |
Notebook Overview
In this notebook, I will construct:
- A naive model of bitcoin price prediction
A nested time series model.
What do I mean by a nested time series model?
I will illustrate with a simple example.
Let's say that I wish to predict the mkt_price on 2016-10-30. I could fit a Linear Regression on all the ... | df = unpickle_object("FINAL_DATAFRAME_PROJ_5.pkl")
df.head()
def linear_extrapolation(df, window):
pred_lst = []
true_lst = []
cnt = 0
all_rows = df.shape[0]
while cnt < window:
start = df.iloc[cnt:all_rows-window+cnt, :].index[0].date()
end = df.iloc[cnt:all_rows-window+cnt, :].... | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
Naïve Model Caveats
We can see above that we can use this extremely basic model to obtain an $R^2$ of 0.86. In fact, this should be the baseline model score that we need to beat!
Let me mention some caveats to this result:
I only have 4 months of Bitcoin data. It should be obvious to the reader that such a naive mode... | df = unpickle_object("FINAL_DATAFRAME_PROJ_5.pkl")
df.head()
df.corr()
plot_corr_matrix(df)
beta_values, pred, true = master(df, 30)
r2_score(true, pred)#blows our Prophet TS only model away! | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
Nested TS VS. FB Prophet TS
We see from the above that our model has an $R^2$ of 0.75! This greatly outperforms our baseline model of just using FaceBook Prophet to forecast the price of bitcoin! The RMSE is 1.40
This is quite impressive given that we only have 3 months of training data and are testing on one month!
Th... | plt.plot(pred)
plt.plot(true)
plt.legend(["Prediction", 'Actual'], loc='upper left')
plt.xlabel("Prediction #")
plt.ylabel("Price")
plt.title("Nested TS - Price Prediction");
fig, ax = plt.subplots()
ax.scatter(true, pred, edgecolors=(0, 0, 0))
ax.plot([min(true), max(true)], [min(true), max(true)], 'k--', lw=3)
ax.se... | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
Percent change model!
I will now run the same nested TS model as above, however, I will now make my 'target' variable the percent change in bitcoin price. In order to make this a log-og model, I will use the percentage change of all features as inputs into the TS model and thus the linear regression!
Since percent chan... | df_pct = df.copy(deep=True)
df_pct = df_pct.pct_change()
df_pct.rename(columns={"mkt_price": "percent_change"}, inplace=True)
df_pct = df_pct.iloc[1:, :] #first row is all NaN's
df_pct.head()
beta_values_p, pred_p, true_p = master(df_pct, 30)
r2_score(true_p, pred_p) # this is expected due to the range of values on t... | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
From the above, it seems that our model is not tuned well enough to anticipate the large dip shown above. This is due to a lack of training data. However, while our model might not be the best in predicting percent change how does it fair when we turn the percent change into prices. | fig, ax = plt.subplots()
ax.scatter(true_p, pred_p, edgecolors=(0, 0, 0))
ax.plot([min(true), max(true)], [min(true), max(true)], 'k--', lw=3)
ax.set_xlabel('Actual')
ax.set_ylabel('Predicted');
df.set_index('date', inplace=True)
prices_to_be_multiplied = df.loc[pd.date_range(start="2017-01-23", end="2017-02-21"), "mk... | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
We have an $R^2$ of 0.87!
This surpasses the baseline model and the nested TS model!
The caveats of the baseline model also apply here, however, it seems that the addition of additional variables have helped us slightly improve with regards to the $R^2$ | plt.plot(forecast_price_lst)
plt.plot(ground_truth_prices)
plt.legend(["Prediction", 'Actual'], loc='upper left')
plt.xlabel("Prediction #")
plt.ylabel("Price")
plt.title("Nested TS - % Change Prediction"); | 05-project-kojack/Final_Notebook.ipynb | igabr/Metis_Projects_Chicago_2017 | mit |
To provide an acceleration depending on an extra parameter, we can use closures like this one: | def constant_accel_factory(accel):
def constant_accel(t0, u, k):
v = u[3:]
norm_v = (v[0]**2 + v[1]**2 + v[2]**2)**.5
return accel * v / norm_v
return constant_accel
constant_accel_factory(accel=1e-5)(t[0], u0, k)
help(func_twobody) | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Now we setup the integrator manually using scipy.integrate.ode. We cannot provide the Jacobian since we don't know the form of the acceleration in advance. | res = np.zeros((t.size, 6))
res[0] = u0
ii = 1
accel = 1e-5
rr = ode(func_twobody).set_integrator('dop853') # All parameters by default
rr.set_initial_value(u0, t[0])
rr.set_f_params(k, constant_accel_factory(accel))
while rr.successful() and rr.t + dt < t[-1]:
rr.integrate(rr.t + dt)
res[ii] = rr.y
ii ... | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
And we plot the results: | fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.plot(*res[:, :3].T)
ax.view_init(14, 70) | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Interactivity
This is the last time we used scipy.integrate.ode directly. Instead, we can now import a convenient function from poliastro: | from poliastro.twobody.propagation import cowell
def plot_iss(thrust=0.1, mass=2000.):
r0, v0 = iss.rv()
k = iss.attractor.k
t = np.linspace(0, 10 * iss.period, 500).to(u.s).value
u0 = state_to_vector(iss)
res = np.zeros((t.size, 6))
res[0] = u0
accel = thrust / mass
# Perform the wh... | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Error checking | rtol = 1e-13
full_periods = 2
u0 = state_to_vector(iss)
tf = ((2 * full_periods + 1) * iss.period / 2).to(u.s).value
u0, tf
iss_f_kep = iss.propagate(tf * u.s, rtol=1e-18)
r0, v0 = iss.rv()
r, v = cowell(k, r0.to(u.km).value, v0.to(u.km / u.s).value, tf, rtol=rtol)
iss_f_num = Orbit.from_vectors(Earth, r * u.km, v... | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Too bad I cannot access the internal state of the solver. I will have to do it in a blackbox way. | u0 = state_to_vector(iss)
full_periods = 4
tof_vector = np.linspace(0, ((2 * full_periods + 1) * iss.period / 2).to(u.s).value, num=100)
rtol_vector = np.logspace(-3, -12, num=30)
res_array = np.zeros((rtol_vector.size, tof_vector.size))
for jj, tof in enumerate(tof_vector):
rf, vf = iss.propagate(tof * u.s, rtol... | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Numerical validation
According to [Edelbaum, 1961], a coplanar, semimajor axis change with tangent thrust is defined by:
$$\frac{\operatorname{d}!a}{a_0} = 2 \frac{F}{m V_0}\operatorname{d}!t, \qquad \frac{\Delta{V}}{V_0} = \frac{1}{2} \frac{\Delta{a}}{a_0}$$
So let's create a new circular orbit and perform the necessa... | ss = Orbit.circular(Earth, 500 * u.km)
tof = 20 * ss.period
ad = constant_accel_factory(1e-7)
r0, v0 = ss.rv()
r, v = cowell(k, r0.to(u.km).value, v0.to(u.km / u.s).value,
tof.to(u.s).value, ad=ad)
ss_final = Orbit.from_vectors(Earth, r * u.km, v * u.km / u.s, ss.epoch + rr.t * u.s)
da_a0 = (ss_final.... | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
This means we successfully validated the model against an extremely simple orbit transfer with approximate analytical solution. Notice that the final eccentricity, as originally noticed by Edelbaum, is nonzero: | ss_final.ecc | docs/source/examples/Propagation using Cowell's formulation.ipynb | anhiga/poliastro | mit |
Replace the variable values in the cell below: | PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = PROJECT # defaults to PROJECT
REGION = "us-central1" # Replace with your REGION
SEED = 0
%%bash
gsutil mb gs://$BUCKET | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Create a Dataset from BigQuery
Hacker news headlines are available as a BigQuery public dataset. The dataset contains all headlines from the sites inception in October 2006 until October 2015.
Lab Task 1a:
Complete the query below to create a sample dataset containing the url, title, and score of articles from the pub... | %%bigquery --project $PROJECT
SELECT
# TODO: Your code goes here.
FROM
# TODO: Your code goes here.
WHERE
# TODO: Your code goes here.
# TODO: Your code goes here.
# TODO: Your code goes here.
LIMIT 10 | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's do some regular expression parsing in BigQuery to get the source of the newspaper article from the URL. For example, if the url is http://mobile.nytimes.com/...., I want to be left with <i>nytimes</i>
Lab task 1b:
Complete the query below to count the number of titles within each 'source' category. Note that to g... | %%bigquery --project $PROJECT
SELECT
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source,
# TODO: Your code goes here.
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$')
# TODO: Your code goes here.... | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Now that we have good parsing of the URL to get the source, let's put together a dataset of source and titles. This will be our labeled dataset for machine learning. | regex = '.*://(.[^/]+)/'
sub_query = """
SELECT
title,
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '{0}'), '.'))[OFFSET(1)] AS source
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '{0}'), '.com$')
AND LENGTH(title) > 10
""".format(regex)
query = """
S... | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
For ML training, we usually need to split our dataset into training and evaluation datasets (and perhaps an independent test dataset if we are going to do model or feature selection based on the evaluation dataset). AutoML however figures out on its own how to create these splits, so we won't need to do that here. | bq = bigquery.Client(project=PROJECT)
title_dataset = bq.query(query).to_dataframe()
title_dataset.head() | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
AutoML for text classification requires that
* the dataset be in csv form with
* the first column being the texts to classify or a GCS path to the text
* the last colum to be the text labels
The dataset we pulled from BiqQuery satisfies these requirements. | print("The full dataset contains {n} titles".format(n=len(title_dataset))) | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's make sure we have roughly the same number of labels for each of our three labels: | title_dataset.source.value_counts() | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Finally we will save our data, which is currently in-memory, to disk.
We will create a csv file containing the full dataset and another containing only 1000 articles for development.
Note: It may take a long time to train AutoML on the full dataset, so we recommend to use the sample dataset for the purpose of learning ... | DATADIR = './data/'
if not os.path.exists(DATADIR):
os.makedirs(DATADIR)
FULL_DATASET_NAME = 'titles_full.csv'
FULL_DATASET_PATH = os.path.join(DATADIR, FULL_DATASET_NAME)
# Let's shuffle the data before writing it to disk.
title_dataset = title_dataset.sample(n=len(title_dataset))
title_dataset.to_csv(
FUL... | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Now let's sample 1000 articles from the full dataset and make sure we have enough examples for each label in our sample dataset (see here for further details on how to prepare data for AutoML).
Lab Task 1c:
Use .sample to create a sample dataset of 1,000 articles from the full dataset. Use .value_counts to see how many... | sample_title_dataset = # TODO: Your code goes here.
# TODO: Your code goes here. | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
Let's write the sample datatset to disk. | SAMPLE_DATASET_NAME = 'titles_sample.csv'
SAMPLE_DATASET_PATH = os.path.join(DATADIR, SAMPLE_DATASET_NAME)
sample_title_dataset.to_csv(
SAMPLE_DATASET_PATH, header=False, index=False, encoding='utf-8')
sample_title_dataset.head()
%%bash
gsutil cp data/titles_sample.csv gs://$BUCKET | courses/machine_learning/deepdive2/text_classification/labs/automl_for_text_classification.ipynb | turbomanage/training-data-analyst | apache-2.0 |
前台服务员系统与后台系统的交互,我们可以通过命令的模式来实现,服务员将顾客的点单内容封装成命令,直接对后台下达命令,后台完成命令要求的事,即可。前台系统构建如下: | class waiterSys():
def __init__(self):
self.menu_map=dict()
self.commandList=[]
def setOrder(self,command):
print ("WAITER:Add dish")
self.commandList.append(command)
def cancelOrder(self,command):
print ("WAITER:Cancel order...")
self.commandList.remove(comm... | DesignPattern/CommandPattern.ipynb | gaufung/Data_Analytics_Learning_Note | mit |
前台系统中的notify接口直接调用命令中的execute接口,执行命令。命令类构建如下: | class Command():
receiver = None
def __init__(self, receiver):
self.receiver = receiver
def execute(self):
pass
class foodCommand(Command):
dish=""
def __init__(self,receiver,dish):
self.receiver=receiver
self.dish=dish
def execute(self):
self.receiver.coo... | DesignPattern/CommandPattern.ipynb | gaufung/Data_Analytics_Learning_Note | mit |
Command类是个比较通用的类,foodCommand类是本例中涉及的类,相比于Command类进行了一定的改造。由于后台系统中的执行函数都是cook,因而在foodCommand类中直接将execute接口实现,如果后台系统执行函数不同,需要在三个子命令系统中实现execute接口。这样,后台三个命令类就可以直接继承,不用进行修改了。(这里子系统没有变动,可以将三个子系统的命令废弃不用,直接用foodCommand吗?当然可以,各有利蔽。请读者结合自身开发经验,进行思考相对于自己业务场景的使用,哪种方式更好。)
为使场景业务精简一些,我们再加一个菜单类来辅助业务,菜单类在本例中直接写死。 | class menuAll:
menu_map=dict()
def loadMenu(self):#加载菜单,这里直接写死
self.menu_map["hot"] = ["Yu-Shiang Shredded Pork", "Sauteed Tofu, Home Style", "Sauteed Snow Peas"]
self.menu_map["cool"] = ["Cucumber", "Preserved egg"]
self.menu_map["main"] = ["Rice", "Pie"]
def isHot(self,dish):
... | DesignPattern/CommandPattern.ipynb | gaufung/Data_Analytics_Learning_Note | mit |
Remember DRY: Don't Repeat Yourself!
Let's try to apply memoization in a generic way to not modified functions
Let's do a bit of magic to apply memoization easily | real_fibonacci = fibonacci
def fibonacci(n):
res = simcache.get_key(n)
if not res:
res = real_fibonacci(n)
simcache.set_key(n, res)
return res
t1_start = time.time()
print fibonacci(30)
t1_elapsed = time.time() - t1_start
print "fibonacci time {}".format(t1_elapsed)
t1_start = time.time()
p... | advanced/5_decorators.ipynb | ealogar/curso-python | apache-2.0 |
Let's explain the trick in slow motion | simcache.clear_keys() # Let's clean the cache
# Let's define the real fibonacci computation function
def fibonacci(n):
if n < 2:
return n
print "Real fibonacci func, calling recursively to", fibonacci, n
# Once the trick is done globals will contain a different function binded to 'fibonacci'
re... | advanced/5_decorators.ipynb | ealogar/curso-python | apache-2.0 |
We have applied our first hand-crafted decorator
How would you memoize any function, not just fibonacci?
Do you remember functions are first class objects? They can be used as arguments or return values...
Do you remember we can declare functions inside other functions?
Let's apply these concepts to find a generic met... | def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def memoize_any_function(func_to_memoize):
"""Function to return a wrapped version of input function using memoization
"""
print "Called memoize_any_function"
def memoized_version_of_func(n):
"""Wra... | advanced/5_decorators.ipynb | ealogar/curso-python | apache-2.0 |
Python decorators:
A callable which receives a funtion as only argument and returns another function. Typically the resulting function wrapps the first function executing some code before and/or after the first is called.
Used with the at @ symbol before a function or method
Don't forget to deal with 'self' as first a... | def timing_decorator(decorated_func):
print "Called timing_decorator"
def wrapper(*args): # Use variable arguments to be compatible with any function
"""Wrapper for time executions
"""
start = time.time()
res = decorated_func(*args) # Call the real function
elapsed = t... | advanced/5_decorators.ipynb | ealogar/curso-python | apache-2.0 |
It is possible to accumulate decorators
Order matters, they are run in strict top - down order | print fibonacci
# Why is the wrapper? Can we maintain the original name ?
import functools
def memoize_any_function(decorated_func):
"""Function to return a wrapped version of input function using memoization
"""
@functools.wraps(decorated_func) # Use functools.wraps to smooth the decoration
def memoi... | advanced/5_decorators.ipynb | ealogar/curso-python | apache-2.0 |
CHIRPS (Climate Hazards group Infrared Precipitation with Stations
Download the data files for the desired periods for the whole of Africa from CHIRPS. You can do this with FileZilla a free app for this purpose.
For access to the CHIRPTS data see
http://chg.ucsb.edu/data/chirps/
Next to tiff files one can find png (ima... | import glob
chirps_files = glob.glob('../**/*/*.tif')
pprint(chirps_files)
fname = chirps_files[0] | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
gdal (working with tiff files among others, GIS)
import gdal and check if the file is present by opening it. | import gdal
try: # is the file present?
g = gdal.Open(fname)
except:
exception(FileExistsError("Can't open file <{}>".fname)) | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Get some basic information from the tiff file
Ok, now with g the successfully opended CHIRPS file, get some basic information from that file. | print("\nBasic information on file <{}>\n".format(fname))
print("Driver: ", g.GetDriver().ShortName, '/', g.GetDriver().LongName)
print("Size : ", g.RasterXSize, 'x', g.RasterYSize, 'x', g.RasterCount)
print("Projection :\n", g.GetProjection())
print()
print("\nGeotransform information:\n")
gt = g.GetGeoTransform()
pri... | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
This projection says that it's WGS1984 (same as GoogleEarth and GoogleMaps. Therefore it is in longitude (x) and latitute (y) coordinates. This allows to immediately compute the WGS coordinates (lat/lon) from it, for instance for each pixel/cell center. It's also straightforward to compute the bounding box of this arra... | # Bounding box around the tiff data set
tbb = [xUL, yUL + Ny * dy, xUL + Nx * dx, yUL]
print("Boudning box of data in tiff file :", tbb)
# Generate coordinates for tiff pixel centers
xm = 0.5 * dx + np.linspace(xUL, xUL + Nx * dx, Nx)
ym = 0.5 * dy + np.linspace(yUL, yUL + Ny * dy, Ny) | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Generate a shapefile with a polyline that represents the model boundary
The contour coordinates of the Erfoud/Tafilalet groundwater model happen to be the file ErfoudModelContour.kml. Kml files come from GoogleEarth and are in WGS84 coordinates. It was obtained by digitizing the line directly in Google Earth.
We extrac... | with open('ErfoudModelContour.kml', 'r') as f:
for s in f: # read lines from this file
if s.find('coord') > 0: # word "coord" bound?
# Then the next line has all coordinates. Read it and clean up.
pnts_as_str = f.readline().replace(' ',',').replace('\t','').split(',')
... | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Generate the shapefile holding a 3 polygons a) The bonding box around the data in the tiff file, b) the bounding box of around the model contour. 3) the model contour | import shapefile as shp
tb = lambda indices: [tbb[i] for i in indices] # convenience for selecting from tiff bounding box
mb = lambda indices: [mbb[i] for i in indices] # same for selecting from model bounding box
# open a shape file writer objetc
w = shp.Writer(shapeType=shp.POLYGON)
# add the three polylines to w.... | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Show shapefile in QGIS
Fire up QGIS and load the shape file. Set its CRS to WGS84 (same coordinates as GoogleMaps, most general LatLon)
Here are the pictures taken van de screen of QGIS after the shapefile was loaded and the label under properties was set tot transparent with solid contour line.
To get the GoogleMaps i... | A = g.GetRasterBand(1).ReadAsArray()
A[A <- 9000] = 0. # replace no-dta values by 0
print()
print("min precipitation in mm ", np.min(A))
print("max precipitation in mm ", np.max(A)) | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Select a subarea equal to the bbox of the model contour. | # define a function to get the indices of the center points between the bounding box extents of the model
def between(x, a, b):
"""returns indices of ponts between a and b"""
I = np.argwhere(np.logical_and(min(a, b) < x, x < max(a, b)))
return [i[0] for i in I]
ix = between(xm, mbb[0], mbb[2])
iy = betwe... | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Read the data again, but now only the part that covers the model in Marocco: | A = g.GetRasterBand(1).ReadAsArray(xoff=int(ix[0]), yoff=int(iy[0]), win_xsize=len(ix), win_ysize=len(iy))
print("Preciptation on the Erfoud model area in Marocco from file\n{}:\n".format(fname))
prar(A) | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Just for curiosity, show the size of the area covered and the size resolution of the precipitation data. | # The extent of this area can be obtained from the latiture and longitude together with the radius of the earth.
R = 6371 # km
EWN = R * np.cos(np.pi/180 * mbb[1]) * np.pi/180. *(mbb[2] - mbb[0])
EWS = R * np.cos(np.pi/180 * mbb[3]) * np.pi/180. *(mbb[2] - mbb[0])
NS = R * np.pi/180 * (mbb[3] - mbb[1])
print("The si... | exercises/Mar14/shapesGetPrecDataForYourModelFromChirps.ipynb | Olsthoorn/IHE-python-course-2017 | gpl-2.0 |
Let us implement a Hopfield network using images from the MNIST dataset as patterns.
Initialize the dataset
First we initialize the dataset: | #### Download the dataset
# Get the script from internet
! wget https://raw.githubusercontent.com/sorki/python-mnist/master/get_data.sh > /dev/null 2>&1
# Run it to dovnload all files in a local dir named 'data'
! bash get_data.sh >/dev/null 2>&1
# We do not need the script anymore, remove it
! rm get_data.sh* > /... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
We now fill a array with all parameters. We only need few samples, we take them from the training set.
We take samples 2 and 5, representing respectively a '4' and a '2' | # Take two rows
patterns = array(mndata.train_images)[[2,5],]
labels = array(mndata.train_labels)[[2,5],]
# We need only the sign (transform to binary input)
patterns = sign(patterns/255.0 - 0.5)
# Set the number of patterns (two in out case)
n_patterns = patterns.shape[0]
# Number of units of the network
n = img_si... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
Let us visualize our two patterns: | fig = figure(figsize = (8, 4))
for i in xrange(n_patterns):
plot_img( to_mat(patterns[i]),
fig, i+1, windows = 2 ) | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
Learning the weights
Learning of the weight happens offline at the beginning, in one shot: | # Initialize weights to zero values
W = zeros([n,n])
# Accumulate outer products
for pattern in patterns :
W += outer(pattern, pattern)
# Divide times the number of patterns
W /= float(n_patterns)
# Exclude the autoconnections
W *= 1.0 - eye(n, n) | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
Recall: Iterating the timesteps
Now we implement the recall part, in which we give an initial activation to the network and iterate the timesteps unitil it relaxes to a steady state. | # Number of timesteps
stime = 1000
# Number of samples to store as long
# as spreading goes on
samples = 100
# store data at each sampling interval
sample_interval = stime/samples
# Init the stories of spreading as a zero array,
# we will fill it in at each timestep and we will
# plot it at the end
store_images = ... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
Here you can see two animations showing the network that is initially activated with one of the two patterns. The initial activation is corrupted with a lot of noise so that the bottom half of the figure is completelly obscured.
The network moves from this initial activation to the correct attractor state (the origina... | # The matplotlib object to do animations
from matplotlib import animation
# This grid allows to layout subplots in a more
# flexible way
import matplotlib.gridspec as gridspec | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
To plot the two animations we need a function to initialize a figure with three plots: the first showing the target digit, the second showing the current activity of the network and the third showing the sum of squared errors. | def init_figure(fig) :
# Init the grid and the figure
gs = gridspec.GridSpec(6, 20)
#-------------------------------------------------
# Plot 1 - plot the target digit
# Create subplot
ax1 = fig.add_subplot(gs[:4,:4])
title("target")
# Create the imshow and save the handler
im_t... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
We also need one another function that updates the figure at
each animation timestep with a new sample | # Updates images at each frame of the animation
# data : list of tuples Each row contains the
# arguments of update for
# a frame
# returns : tuple The handlers of the
# images
def update(data) :
# unpack plot ... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
Finally we use the FuncAnimation class. We first build a data list where each row is a tuple containing plot handlers and data do for plot updates.. | for target_index in xrange(n_patterns):
# Init the figure
fig = figure(figsize=(8, 3.5))
im_target, im_activation, im_energy = init_figure(fig)
# Build the sequence of update arguments.
# each row of the list contains:
# 1 the target plot handler
# 2 the activation plot hand... | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
Next cell is just for styling | from IPython.core.display import HTML
def css_styling():
styles = open("../style/ipybn.css", "r").read()
return HTML(styles)
css_styling() | course/hopfield-MNIST-simulation.ipynb | francesco-mannella/neunet-basics | mit |
In this example, we show the current year incidence up to given week.<br>
Along with the current incidence, we present the following intensity thresholds:<br>
Low activity threshold: estimated epidemic threshold based on historical levels. Minimum: incidence equivalent to 5 cases.
High activity threshold: incidence... | df_hist = pd.read_csv('../data/historical_estimated_values.csv', encoding='utf-8')
df_inci = pd.read_csv('../data/current_estimated_values.csv', encoding='utf-8')
df_typi = pd.read_csv('../data/mem-typical.csv', encoding='utf-8')
df_thre = pd.read_csv('../data/mem-report.csv', encoding='utf-8')
prepare_keys_name(df_hi... | Notebooks/historical_estimated_values.ipynb | FluVigilanciaBR/fludashboard | gpl-3.0 |
UF: locality code (includes UFs, Regions and Country)
Tipo: locality type (Estado, Regional or País)
mean: estimated mean incidence
50%: estimated median
2.5%: estimation lower 95% confidence interval
97.5%: estimation upper 95% confidence interval
L0: probability of being below epi. threshold (low level)
L1: probabili... | df_inci.head(5)
df_typi.head(5)
df_thre.tail(5) | Notebooks/historical_estimated_values.ipynb | FluVigilanciaBR/fludashboard | gpl-3.0 |
Entries with dfthresholds['se típica do inicio do surto'] = NaN have activity too low for proper epidemic threshold definition | k = ['epiyear', 'epiweek', 'base_epiyear', 'base_epiweek']
df_inci2017 = df_inci[
(df_inci.epiyear == 2017) &
# (df_inci.epiweek >= 15) &
(df_inci.dado == 'srag') &
(df_inci.escala == 'incidência') &
(df_inci.uf == 'BR')
].copy()
df_inci2017.sort_values(['epiyear', 'epiweek'], inplace=True)
df_inc... | Notebooks/historical_estimated_values.ipynb | FluVigilanciaBR/fludashboard | gpl-3.0 |
Displaying data for user selected week w<a name="_historical data display"></a>
For each week w selected by the user, the notification curve will always be that which is found on df_inci, while the estimates will be that stored in df_hist. Data df_inci only has the most recent estimates, which are based on the most rec... | df_hist[
(df_hist.base_epiyear == 2017) &
(df_hist.dado == 'srag') &
(df_hist.escala == 'incidência') &
(df_hist.uf == 'BR')
].base_epiweek.unique()
# First, last keep only stable weeksfor notification curve:
df_inci2017.loc[(df_inci2017.situation != 'stable'), 'srag'] = np.nan... | Notebooks/historical_estimated_values.ipynb | FluVigilanciaBR/fludashboard | gpl-3.0 |
Collect data | def loadMovieLens(path='./data/movielens'):
#Get movie titles
movies={}
for line in open(path+'/u.item'):
id,title=line.split('|')[0:2]
movies[id]=title
# Load data
prefs={}
for line in open(path+'/u.data'):
(user,movieid,rating,ts)=line.split('\t')
prefs.setdefa... | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Explore data | data['3'] | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Creation of train set and test set
We want to split data in two set (train and test)
Actually :
train= 80%totaldataset
test = 20%totaldataset | def split_train_test(data,percent_test):
test={}
train={}
movie={}
for u in data.keys():
test.setdefault(u,{})
train.setdefault(u,{})
for movie in data[u]:
#print(data[u][movie])
if (random()<percent_test):
test[u][movie]=data[u][movie]
... | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Part that allows to clean train and test
We don't want to have user in test set which are not in train test, the same for the movies so we delete them |
def get_moove(data):
moove = {}
for u in data:
for m in data[u]:
moove[m]=0
return moove
def get_youser(data):
youser = {}
for u in data:
youser[u]=0
return youser
def clean(d1,d2):
to_erase = {}
for i in d1:
try:
d2[i]
... | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
Collaboritive Filtering classes | class BaselineMeanUser:
def __init__(self):
self.users={}
self.movies={}
def fit(self,train):
for user in train:
note=0
for movie in train[user]:
note+=train[user][movie]
note=note/len(train[user])
self.users[user]=round(not... | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
tag_headers = ['user_id', 'movie_id', 'tag', 'timestamp']
tags = pd.read_table('data/ml-10M/tags.dat', sep='::', header=None, names=tag_headers)
rating_headers = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table('data/ml-10M/r... | FDMS/TME4/TME4_FiltrageCollaboratif.ipynb | ToqueWillot/M2DAC | gpl-2.0 | |
$$y=\frac{1}{1+\exp(x^T \beta)}$$ | x = np.linspace(-5.0,5.0,200)
y = -x
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = np.exp(-x)
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = 1.0+np.exp(-x)
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y) | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
ロジスティック・シグモイド関数 | y = 1/(1.0+np.exp(-x))
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = 1 - 1/(1.0+np.exp(-x))
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y) | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
オッズ | y = np.exp(x)
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y) | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
対数オッズ | y = x
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y) | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
微分
商の微分
\begin{eqnarray}
(\frac{1}{f(x)})'&=&\lim_{h \rightarrow 0}\frac{\frac{1}{f(x+h)}-\frac{1}{f(x)}}{h}\
&=&\lim_{h \rightarrow 0}\frac{f(x)-f(x+h)}{hf(x)f(x+h)}\
&=&\lim_{h \rightarrow 0}-\frac{1}{f(x)f(x+h)}\frac{f(x+h)-f(x)}{h}\
&=&-\frac{f'(x)}{{ f(x)}^2}
\end{eqnarray}
$${ 1+\exp(-x)}'=-\exp(-x)$$
ロジスティック関数の微... | y = 1/(1.0+np.exp(-x)) * (1 - 1/(1.0+np.exp(-x)))
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y) | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
正規分布の確率密度関数に近い形状であり,最大は0.25
線形結合が正規分布に従うのに近いイメージ
正規分布
$$f(x)= \frac{1}{\sqrt{2 \pi \sigma^2}} \exp (- \frac{(x-\mu)^2 }{2 \sigma}) $$ | y = x
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = x*x
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = -x*x
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = np.exp(x)
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y)
y = np.exp(-x)
plt.figure(figsize=(10,6))
plt.grid... | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
比較 | y1 = np.exp(-x*x/2)/np.sqrt(2*np.pi)
y2 = 1/(1.0+np.exp(-x)) * (1 - 1/(1.0+np.exp(-x)))
plt.figure(figsize=(10,6))
plt.grid(True)
plt.plot(x,y1)
plt.plot(x,y2)
sigma = 1.6
y1 = np.exp(-x*x/2/sigma)/np.sqrt(2*np.pi)/sigma
y2 = 1/(1.0+np.exp(-x)) * (1 - 1/(1.0+np.exp(-x)))
plt.figure(figsize=(10,6))
plt.grid(True)
plt... | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
ランダムなデータ | t = np.random.randint(low=0,high=2,size=50)
t
feature = np.random.normal(loc=0.0,scale=1.0,size=(50,1))
feature
m = LogisticRegression(penalty='l2',C=10000,fit_intercept=True)
m.fit(feature,t)
plt.figure(figsize=(10,6))
plt.grid(True)
plt.scatter(feature,t)
predict = m.predict(x.reshape((200,1)))
y = 1/(1.0+np.ex... | s10_logistic_regression.ipynb | ryo8128/study_python | mit |
Neural network classes for testing
The following class, NeuralNet, allows us to create identical neural networks with and without batch normalization. The code is heavily documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the notebook,... | class NeuralNet:
def __init__(self, initial_weights, activation_fn, use_batch_norm):
"""
Initializes this object, creating a TensorFlow graph using the given parameters.
:param initial_weights: list of NumPy arrays or Tensors
Initial values for the weights for every laye... | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
There are quite a few comments in the code, so those should answer most of your questions. However, let's take a look at the most important lines.
We add batch normalization to layers inside the fully_connected function. Here are some important points about that code:
1. Layers with batch normalization do not include a... | def plot_training_accuracies(*args, **kwargs):
"""
Displays a plot of the accuracies calculated during training to demonstrate
how many iterations it took for the model(s) to converge.
:param args: One or more NeuralNet objects
You can supply any number of NeuralNet objects as unnamed argum... | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Comparisons between identical networks, with and without batch normalization
The next series of cells train networks with various settings to show the differences with and without batch normalization. They are meant to clearly demonstrate the effects of batch normalization. We include a deeper discussion of batch norma... | train_and_test(False, 0.01, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
As expected, both networks train well and eventually reach similar test accuracies. However, notice that the model with batch normalization converges slightly faster than the other network, reaching accuracies over 90% almost immediately and nearing its max acuracy in 10 or 15 thousand iterations. The other network tak... | train_and_test(False, 0.01, tf.nn.relu, 2000, 50) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
As you can see, using batch normalization produces a model with over 95% accuracy in only 2000 batches, and it was above 90% at somewhere around 500 batches. Without batch normalization, the model takes 1750 iterations just to hit 80% – the network with batch normalization hits that mark after around 200 iterations! (N... | train_and_test(False, 0.01, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
With the number of layers we're using and this small learning rate, using a sigmoid activation function takes a long time to start learning. It eventually starts making progress, but it took over 45 thousand batches just to get over 80% accuracy. Using batch normalization gets to 90% in around one thousand batches.
Th... | train_and_test(False, 1, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Now we're using ReLUs again, but with a larger learning rate. The plot shows how training started out pretty normally, with the network with batch normalization starting out faster than the other. But the higher learning rate bounces the accuracy around a bit more, and at some point the accuracy in the network without ... | train_and_test(False, 1, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
In both of the previous examples, the network with batch normalization manages to gets over 98% accuracy, and get near that result almost immediately. The higher learning rate allows the network to train extremely fast.
The following creates two networks using a sigmoid activation function, a learning rate of 1, and re... | train_and_test(False, 1, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
In this example, we switched to a sigmoid activation function. It appears to hande the higher learning rate well, with both networks achieving high accuracy.
The cell below shows a similar pair of networks trained for only 2000 iterations. | train_and_test(False, 1, tf.nn.sigmoid, 2000, 50) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
As you can see, even though these parameters work well for both networks, the one with batch normalization gets over 90% in 400 or so batches, whereas the other takes over 1700. When training larger networks, these sorts of differences become more pronounced.
The following creates two networks using a ReLU activation f... | train_and_test(False, 2, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
With this very large learning rate, the network with batch normalization trains fine and almost immediately manages 98% accuracy. However, the network without normalization doesn't learn at all.
The following creates two networks using a sigmoid activation function, a learning rate of 2, and reasonable starting weights... | train_and_test(False, 2, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Once again, using a sigmoid activation function with the larger learning rate works well both with and without batch normalization.
However, look at the plot below where we train models with the same parameters but only 2000 iterations. As usual, batch normalization lets it train faster. | train_and_test(False, 2, tf.nn.sigmoid, 2000, 50) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose random values with a standard deviation of 5. If you were really training a neural network, you would not want to do this. But these examples demonstrate ... | train_and_test(True, 0.01, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
As the plot shows, without batch normalization the network never learns anything at all. But with batch normalization, it actually learns pretty well and gets to almost 80% accuracy. The starting weights obviously hurt the network, but you can see how well batch normalization does in overcoming them.
The following cre... | train_and_test(True, 0.01, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Using a sigmoid activation function works better than the ReLU in the previous example, but without batch normalization it would take a tremendously long time to train the network, if it ever trained at all.
The following creates two networks using a ReLU activation function, a learning rate of 1, and bad starting wei... | train_and_test(True, 1, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
The higher learning rate used here allows the network with batch normalization to surpass 90% in about 30 thousand batches. The network without it never gets anywhere.
The following creates two networks using a sigmoid activation function, a learning rate of 1, and bad starting weights. | train_and_test(True, 1, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Using sigmoid works better than ReLUs for this higher learning rate. However, you can see that without batch normalization, the network takes a long time tro train, bounces around a lot, and spends a long time stuck at 90%. The network with batch normalization trains much more quickly, seems to be more stable, and achi... | train_and_test(True, 2, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
We've already seen that ReLUs do not do as well as sigmoids with higher learning rates, and here we are using an extremely high rate. As expected, without batch normalization the network doesn't learn at all. But with batch normalization, it eventually achieves 90% accuracy. Notice, though, how its accuracy bounces aro... | train_and_test(True, 2, tf.nn.sigmoid) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
In this case, the network with batch normalization trained faster and reached a higher accuracy. Meanwhile, the high learning rate makes the network without normalization bounce around erratically and have trouble getting past 90%.
Full Disclosure: Batch Normalization Doesn't Fix Everything
Batch normalization isn't ma... | train_and_test(True, 1, tf.nn.relu) | batch-norm/Batch_Normalization_Lesson.ipynb | JasonNK/udacity-dlnd | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.