markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
This is a bit more complex already. Proceeding from left to right, we first have the state `¬ quote ∧ ¬ tag`, which is our "standard" state for text. If we encounter a `'<'`, we again switch to the "tagged" state `¬ quote ∧ tag`. In this state, however (and only in this state), if we encounter a quotation mark, we swit...
def remove_html_markup(s): tag = False quote = False out = "" for c in s: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" and tag: quote = not quote elif not tag: out...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Now, our previous input works well:
remove_html_markup('<input type="text" value="<your name>">')
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
and our earlier tests also pass:
assert remove_html_markup("Here's some <strong>strong argument</strong>.") == \ "Here's some strong argument." assert remove_html_markup('<input type="text" value="<your name>">') == ""
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
However, the above code still has a bug. In two of these inputs, HTML markup is still not properly stripped:```htmlfoo"foo""foo"foo```Can you guess which ones these are? Again, a simple assertion will reveal the culprits:
with ExpectError(): assert remove_html_markup('<b>foo</b>') == 'foo' with ExpectError(): assert remove_html_markup('<b>"foo"</b>') == '"foo"' with ExpectError(): assert remove_html_markup('"<b>foo</b>"') == '"foo"' with ExpectError(): assert remove_html_markup('<"b">foo</"b">') == 'foo'
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
So, unfortunately, we're not done yet – our function still has errors. The Devil's Guide to DebuggingLet us now discuss a couple of methods that do _not_ work well for debugging. (These "devil's suggestions" are adapted from the 1993 book "Code Complete" from Steve McConnell.) Printf DebuggingWhen I was a student, n...
def remove_html_markup_with_print(s): tag = False quote = False out = "" for c in s: print("c =", repr(c), "tag =", tag, "quote =", quote) if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" an...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
This way of inspecting executions is commonly called "Printf debugging", after the C `printf()` function. Then, running this would allow me to see what's going on in my code:
remove_html_markup_with_print('<b>"foo"</b>')
c = '<' tag = False quote = False c = 'b' tag = True quote = False c = '>' tag = True quote = False c = '"' tag = False quote = False c = 'f' tag = False quote = True c = 'o' tag = False quote = True c = 'o' tag = False quote = True c = '"' tag = False quote = True c = '<' tag = False quote = False c = '/' tag = True q...
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Yes, one sees what is going on – but this is horribly inefficient! Think of a 1,000-character input – you'd have to go through 2,000 lines of logs. It may help you, but it's a total time waster. Plus, you have to enter these statements, remove them again... it's a maintenance nightmare. (You may even forget printf's...
def remove_html_markup_without_quotes(s): tag = False quote = False out = "" for c in s: if c == '<': # and not quote: tag = True elif c == '>': # and not quote: tag = False elif c == '"' or c == "'" and tag: quote = not quote elif n...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Cool! Unfortunately, the function still fails on the other input:
with ExpectError(): assert remove_html_markup_without_quotes('<b>"foo"</b>') == '"foo"'
Traceback (most recent call last): File "<ipython-input-28-1d8954a52bcf>", line 2, in <module> assert remove_html_markup_without_quotes('<b>"foo"</b>') == '"foo"' AssertionError (expected)
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
So, maybe we can change things again, such that both work? And maybe the other tests we had earlier won't fail? Let's just continue to change things randomly again and again and again. Oh, and of course, I would never back up earlier versions such that I would be able to keep track of what has changed and when. Use th...
def remove_html_markup_fixed(s): if s == '<b>"foo"</b>': return '"foo"' ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Miracle! Our earlier failing assertion now works! Now we can do the same for the other failing test, too, and we're done.(Rumor has it that some programmers use this technique to get their tests to pass...) Things to do InsteadAs with any devil's guide, you get an idea of how to do things by doing the _opposite._ Wha...
# ignore def execution_diagram(show_steps=True, variables=[], steps=3, error_step=666, until=666, fault_path=[]): dot = graph() dot.node('input', shape='none', fillcolor='white', label=f"Input {PASS}", fontcolor=PASS_COLOR) last_outgoing_states = ['i...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
This situation we see above is what we call a *failure*: An externally visible _error_ in the program behavior, with the error again being an unwanted and unintended deviation from what is correct, right, or true. How does this failure come to be? The execution we see above breaks down into several program _states_, on...
# ignore for until in range(1, 6): execution_diagram(show_steps=False, until=until, error_step=2)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Initially, the program state is still correct (✔). However, at some point in the execution, the state gets an _error_, also known as a *fault*. This fault – again an unwanted and unintended deviation from what is correct, right, or true – then propagates along the execution, until it becomes externally visible as a _fa...
# ignore for until in range(1, 6): execution_diagram(show_steps=True, until=until, error_step=2)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Now, in the diagram above, Step 2 gets a _correct_ state as input and produces a _faulty_ state as output. The produced fault then propagates across more steps to finally become visible as a _failure_. The goal of debugging thus is to _search_ for the step in which the state first becomes faulty. The _code_ associated ...
# ignore for until in range(1, 6): execution_diagram(show_steps=True, variables=['v1', 'v2', 'v3'], error_step=2, until=until, fault_path=['s2:v2', 's3:v2'])
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
The way these faults propagate is called a *cause-effect chain*:* The _defect_ in the code _causes_ a fault in the state when executed.* This _fault_ in the state then _propagates_ through further execution steps...* ... until it becomes visible as a _failure_. Since the code was originally written by a human, any defe...
# ignore dot = graph() dot.node('Hypothesis') dot.node('Observation') dot.node('Prediction') dot.node('Experiment') dot.edge('Hypothesis', 'Observation', label="<Hypothesis<BR/>is <I>supported:</I><BR/>Refine it>", dir='back') dot.edge('Hypothesis', 'Prediction') dot.node('Problem Report', shape='n...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
In debugging, we proceed the very same way – indeed, we are treating bugs as if they were natural phenomena. This analogy may sound far-fetched, as programs are anything but natural. Nature, by definition, is not under our control. But bugs are _out of our control just as well._ Hence, the analogy is not that far-...
for i, html in enumerate(['<b>foo</b>', '<b>"foo"</b>', '"<b>foo</b>"', '<"b">foo</"b">']): result = remove_html_markup(html) print("%-2d %-15s %s" % (i + 1, html, result))
1 <b>foo</b> foo 2 <b>"foo"</b> foo 3 "<b>foo</b>" <b>foo</b> 4 <"b">foo</"b"> foo
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Input 1 and 4 work as expected, the others do not. We can write these down in a table, such that we can always look back at our previous results:|Input|Expectation|Output|Outcome||-----|-----------|------|-------||`foo`|`foo`|`foo`|✔||`"foo"`|`"foo"`|`foo`|✘||`"foo"`|`"foo"`|`foo`|✘||`foo`|`foo`|`foo`|✔|
quiz("From the difference between success and failure," " we can already devise some observations about " " what's wrong with the output." " Which of these can we turn into general hypotheses?", ["Double quotes are stripped from the tagged input.", "Tags in double quotes are not stripped.", ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Testing a HypothesisThe hypotheses that remain are:1. Double quotes are stripped from the tagged input.2. Tags in double quotes are not stripped. These may be two separate issues, but chances are they are tied to each other. Let's focus on 1., because it is simpler. Does it hold for all inputs, even untagged ones? ...
remove_html_markup('"foo"')
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Our hypothesis is confirmed! We can add this to our list of observations. |Input|Expectation|Output|Outcome||-----|-----------|------|-------||`foo`|`foo`|`foo`|✔||`"foo"`|`"foo"`|`foo`|✘||`"foo"`|`"foo"`|`foo`|✘||`foo`|`foo`|`foo`|✔||`"foo"`|`"foo"`|`foo`|✘| You can try out the hypothesis with more inputs – and it rem...
def remove_html_markup_with_tag_assert(s): tag = False quote = False out = "" for c in s: assert not tag # <=== Just added if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" and tag: ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Our expectation is that this assertion would fail. So, do we actually get an exception? Try it out for yourself by uncommenting the following line:
# remove_html_markup_with_tag_assert('"foo"') quiz("What happens after inserting the above assertion?", ["The program raises an exception. (i.e., tag is set)", "The output is as before, i.e., foo without quotes." " (which means that tag is not set)"], 2)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Here's the solution:
with ExpectError(): result = remove_html_markup_with_tag_assert('"foo"') result
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Refuting a HypothesisWe did not get an exception, hence we reject our hypothesis:1. ~~The error is due to `tag` being set.~~ Again, let's go back to the only place in our code where quotes are handled:```pythonelif c == '"' or c == "'" and tag: quote = not quote```Because of the assertion, we already know that `tag...
def remove_html_markup_with_quote_assert(s): tag = False quote = False out = "" for c in s: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" and tag: assert False # <=== Just added ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Our expectation this time again is that the assertion fails. So, do we get an exception this time? Try it out for yourself by uncommenting the following line:
# remove_html_markup_with_quote_assert('"foo"') quiz("What happens after inserting the 'assert' tag?", ["The program raises an exception (i.e., the quote condition holds)", "The output is still foo (i.e., the quote condition does not hold)"], 29 % 7)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Here's what happens now that we have the `assert` tag:
with ExpectError(): result = remove_html_markup_with_quote_assert('"foo"')
Traceback (most recent call last): File "<ipython-input-47-9ce255289291>", line 2, in <module> result = remove_html_markup_with_quote_assert('"foo"') File "<ipython-input-44-9c8a53a91780>", line 12, in remove_html_markup_with_quote_assert assert False # <=== Just added AssertionError (expected)
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
From this observation, we can deduce that our hypothesis is _confirmed_:1. The error is due to the quote condition evaluating to true (CONFIRMED)and the _condition is actually faulty._ It evaluates to True although `tag` is always False:```pythonelif c == '"' or c == "'" and tag: quote = not quote```But this conditi...
remove_html_markup("'foo'")
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Surprise: Our hypothesis is rejected and we can add another observation to our table:|Input|Expectation|Output|Outcome||-----|-----------|------|-------||`'foo'`|`'foo'`|`'foo'`|✔|So, the condition* becomes True when a double quote is seen* becomes False (as it should) with single quotes At this point, you should have ...
quiz("How should the condition read?", ["Choice 1", "Choice 2", "Choice 3", "Something else"], 399 % 4)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Fixing the Bug So, you have spotted the defect: In Python (and most other languages), `and` takes precedence over `or`, which is why the condition is wrong. It should read:```python(c == '"' or c == "'") and tag```(Actually, good programmers rarely depend on precedence; it is considered good style to use parentheses ...
def remove_html_markup(s): tag = False quote = False out = "" for c in s: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif (c == '"' or c == "'") and tag: # <-- FIX quote = not quote elif not tag: ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
We verify that the fix was successful by running our earlier tests. Not only should the previously failing tests now pass, the previously passing tests also should not be affected. Fortunately, all tests now pass:
assert remove_html_markup("Here's some <strong>strong argument</strong>.") == \ "Here's some strong argument." assert remove_html_markup( '<input type="text" value="<your name>">') == "" assert remove_html_markup('<b>foo</b>') == 'foo' assert remove_html_markup('<b>"foo"</b>') == '"foo"' assert remove_html_mark...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
So, our hypothesis _was_ a theory, and our diagnosis was correct. Success! Alternate PathsA defect may have more than one hypothesis, and each diagnosis can be obtained by many ways. We could also have started with our other hypothesis2. Tags in double quotes are not strippedand by reasoning and experiments, we would...
quiz("Which assertion would have caught the problem?", ["assert quote and not tag", "assert quote or not tag", "assert tag or not quote", "assert tag and not quote"], 3270 - 3267)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Indeed, the statement```pythonassert tag or not quote```is correct. This excludes the situation of ¬`tag` ∧ `quote` – that is, the `tag` flag is not set, but the `quote` flag is. If you remember our state machine from above, this is actually a state that should never exist:
# ignore display(state_machine)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Here's our function in its "final" state. As software goes, software is never final – and this may also hold for our function, as there is still room for improvement. For this chapter though, we leave it be.
def remove_html_markup(s): tag = False quote = False out = "" for c in s: assert tag or not quote if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif (c == '"' or c == "'") and tag: quote = not quote ...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Commit the Fix It may sound obvious, but your fix is worth nothing if it doesn't go into production. Be sure to commit your change to the code repository, together with your diagnosis. If your fix has to be approved by a third party, a good diagnosis on why and what happened is immensely helpful. Close the Bug Report...
import hashlib bughash = hashlib.md5(b"debug").hexdigest() quiz('Where has the name "bug" been used to denote disruptive events?', [ 'In the early days of Morse telegraphy, referring to a special key ' 'that would send a string of dots', 'Among radio technicians to describe a device that...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
(Source: \cite{jargon}, \cite{wikipedia:debugging}) Synopsis In this chapter, we introduce some basics of how failures come to be as well as a general process for debugging. Lessons Learned1. An _error_ is a deviation from what is correct, right, or true. Specifically, * A _mistake_ is a human act or decision resu...
assert(...)
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Set up additional test cases as useful. **Solution.** The remaining problem stems from the fact that in `remove_html_markup()`, we do not differentiate between single and double quotes. Hence, if we have a _quote within a quoted text_, the function may get confused. Notably, a string that begins with a double quote may...
s = '<b title="<Shakespeare' + "'s play>" + '">foo</b>' s remove_html_markup(s) with ExpectError(): assert(remove_html_markup(s) == "foo")
Traceback (most recent call last): File "<ipython-input-60-00bc84e50798>", line 2, in <module> assert(remove_html_markup(s) == "foo") AssertionError (expected)
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Part 2: Identify Extent and CauseUsing the scientific method, identify the extent and cause of the problem. Write down your hypotheses and log your observations, as in|Input|Expectation|Output|Outcome||-----|-----------|------|-------||(input)|(expectation)|(output)|(outcome)| **Solution.** The first step is obviously...
def remove_html_markup_with_proper_quotes(s): tag = False quote = '' out = "" for c in s: assert tag or quote == '' if c == '<' and quote == '': tag = True elif c == '>' and quote == '': tag = False elif (c == '"' or c == "'") and tag and quote =...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Python enthusiasts may note that we could also write `not quote` instead of `quote == ''`, leaving most of the original code untouched. We stick to classic Boolean comparisons here. The function now satisfies the earlier failing test:
assert(remove_html_markup_with_proper_quotes(s) == "foo")
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
as well as all our earlier tests:
assert remove_html_markup_with_proper_quotes( "Here's some <strong>strong argument</strong>.") == \ "Here's some strong argument." assert remove_html_markup_with_proper_quotes( '<input type="text" value="<your name>">') == "" assert remove_html_markup_with_proper_quotes('<b>foo</b>') == 'foo' assert remove_...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Copyright 2017 Google LLC.
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
First Steps with TensorFlow **Learning Objectives:** * Learn fundamental TensorFlow concepts * Use the `LinearRegressor` class in TensorFlow to predict median housing price, at the granularity of city blocks, based on one input feature * Evaluate the accuracy of a model's predictions using Root Mean Squared Error (...
from __future__ import print_function import math from IPython import display from matplotlib import cm from matplotlib import gridspec from matplotlib import pyplot as plt import numpy as np import pandas as pd from sklearn import metrics import tensorflow as tf from tensorflow.python.data import Dataset tf.logging...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Next, we'll load our data set.
california_housing_dataframe = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=",") california_housing_dataframe.head() california_housing_dataframe.shape
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
We'll randomize the data, just to be sure not to get any pathological ordering effects that might harm the performance of Stochastic Gradient Descent. Additionally, we'll scale `median_house_value` to be in units of thousands, so it can be learned a little more easily with learning rates in a range that we usually use.
california_housing_dataframe = california_housing_dataframe.reindex( np.random.permutation(california_housing_dataframe.index)) california_housing_dataframe["median_house_value"] /= 1000.0 california_housing_dataframe
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Examine the DataIt's a good idea to get to know your data a little bit before you work with it.We'll print out a quick summary of a few useful statistics on each column: count of examples, mean, standard deviation, max, min, and various quantiles.
california_housing_dataframe.describe()
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Build the First ModelIn this exercise, we'll try to predict `median_house_value`, which will be our label (sometimes also called a target). We'll use `total_rooms` as our input feature.**NOTE:** Our data is at the city block level, so this feature represents the total number of rooms in that block.To train our model, ...
# Define the input feature: total_rooms. my_feature = california_housing_dataframe[["total_rooms"]] my_feature # Configure a numeric feature column for total_rooms. feature_columns = [tf.feature_column.numeric_column("total_rooms")]
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
**NOTE:** The shape of our `total_rooms` data is a one-dimensional array (a list of the total number of rooms for each block). This is the default shape for `numeric_column`, so we don't have to pass it as an argument.
print(type(feature_columns[0])) feature_columns
<class 'tensorflow.python.feature_column.feature_column_v2.NumericColumn'>
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Step 2: Define the Target Next, we'll define our target, which is `median_house_value`. Again, we can pull it from our `california_housing_dataframe`:
# Define the label. targets = california_housing_dataframe["median_house_value"]
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Step 3: Configure the LinearRegressor Next, we'll configure a linear regression model using LinearRegressor. We'll train this model using the `GradientDescentOptimizer`, which implements Mini-Batch Stochastic Gradient Descent (SGD). The `learning_rate` argument controls the size of the gradient step.**NOTE:** To be sa...
# Use gradient descent as the optimizer for training the model. my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0000001) my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0) # Configure the linear regression model with our feature columns and optimizer. # Set a learning rate of ...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Step 4: Define the Input Function To import our California housing data into our `LinearRegressor`, we need to define an input function, which instructs TensorFlow how to preprocessthe data, as well as how to batch, shuffle, and repeat it during model training.First, we'll convert our *pandas* feature data into a dict...
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None): """Trains a linear regression model of one feature. Args: features: pandas DataFrame of features targets: pandas DataFrame of targets batch_size: Size of batches to be passed to the model shuffle: True or...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
**NOTE:** We'll continue to use this same input function in later exercises. For moredetailed documentation of input functions and the `Dataset` API, see the [TensorFlow Programmer's Guide](https://www.tensorflow.org/programmers_guide/datasets). Step 5: Train the Model We can now call `train()` on our `linear_regresso...
_ = linear_regressor.train( input_fn = lambda:my_input_fn(my_feature, targets), steps=100 )
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Step 6: Evaluate the Model
_
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Let's make predictions on that training data, to see how well our model fit it during training.**NOTE:** Training error measures how well your model fits the training data, but it **_does not_** measure how well your model **_generalizes to new data_**. In later exercises, you'll explore how to split your data to evalu...
# Create an input function for predictions. # Note: Since we're making just one prediction for each example, we don't # need to repeat or shuffle the data here. prediction_input_fn =lambda: my_input_fn(my_feature, targets, num_epochs=1, shuffle=False) # Call predict() on the linear_regressor to make predictions. pred...
Mean Squared Error (on training data): 56367.025 Root Mean Squared Error (on training data): 237.417
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Is this a good model? How would you judge how large this error is?Mean Squared Error (MSE) can be hard to interpret, so we often look at Root Mean Squared Error (RMSE)instead. A nice property of RMSE is that it can be interpreted on the same scale as the original targets.Let's compare the RMSE to the difference of the...
min_house_value = california_housing_dataframe["median_house_value"].min() max_house_value = california_housing_dataframe["median_house_value"].max() min_max_difference = max_house_value - min_house_value print("Min. Median House Value: %0.3f" % min_house_value) print("Max. Median House Value: %0.3f" % max_house_value...
Min. Median House Value: 14.999 Max. Median House Value: 500.001 Difference between Min. and Max.: 485.002 Root Mean Squared Error: 237.417
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Our error spans nearly half the range of the target values. Can we do better?This is the question that nags at every model developer. Let's develop some basic strategies to reduce model error.The first thing we can do is take a look at how well our predictions match our targets, in terms of overall summary statistics.
calibration_data = pd.DataFrame() calibration_data["predictions"] = pd.Series(predictions) calibration_data["targets"] = pd.Series(targets) calibration_data.describe()
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Okay, maybe this information is helpful. How does the mean value compare to the model's RMSE? How about the various quantiles?We can also visualize the data and the line we've learned. Recall that linear regression on a single feature can be drawn as a line mapping input *x* to output *y*.First, we'll get a uniform ra...
sample = california_housing_dataframe.sample(n=300)
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Next, we'll plot the line we've learned, drawing from the model's bias term and feature weight, together with the scatter plot. The line will show up red.
# Get the min and max total_rooms values. x_0 = sample["total_rooms"].min() x_1 = sample["total_rooms"].max() # Retrieve the final weight and bias generated during training. weight = linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0] bias = linear_regressor.get_variable_value('linear/lin...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
This initial line looks way off. See if you can look back at the summary stats and see the same information encoded there.Together, these initial sanity checks suggest we may be able to find a much better line. Tweak the Model HyperparametersFor this exercise, we've put all the above code in a single function for con...
def train_model(learning_rate, steps, batch_size, input_feature="total_rooms"): """Trains a linear regression model of one feature. Args: learning_rate: A `float`, the learning rate. steps: A non-zero `int`, the total number of training steps. A training step consists of a forward and backward pass...
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Task 1: Achieve an RMSE of 180 or BelowTweak the model hyperparameters to improve loss and better match the target distribution.If, after 5 minutes or so, you're having trouble beating a RMSE of 180, check the solution for a possible combination.
train_model( learning_rate=0.0001, steps=500, batch_size=100 )
Training model... RMSE (on training data): period 00 : 186.29 period 01 : 167.02 period 02 : 166.39 period 03 : 166.39 period 04 : 166.39 period 05 : 166.73 period 06 : 166.73 period 07 : 166.39 period 08 : 166.39 period 09 : 166.73 Model training finished.
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
SolutionClick below for one possible solution.
train_model( learning_rate=0.00002, steps=500, batch_size=5 )
Training model... RMSE (on training data): period 00 : 225.63 period 01 : 214.42 period 02 : 204.04 period 03 : 194.62 period 04 : 186.92 period 05 : 180.00 period 06 : 174.79 period 07 : 171.23 period 08 : 169.08 period 09 : 167.89 Model training finished.
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
This is just one possible configuration; there may be other combinations of settings that also give good results. Note that in general, this exercise isn't about finding the *one best* setting, but to help build your intutions about how tweaking the model configuration affects prediction quality. Is There a Standard H...
# YOUR CODE HERE
_____no_output_____
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
SolutionClick below for one possible solution.
train_model( learning_rate=0.00002, steps=1000, batch_size=5, input_feature="population" )
Training model... RMSE (on training data): period 00 : 225.63 period 01 : 214.62 period 02 : 204.86 period 03 : 196.75 period 04 : 190.21 period 05 : 185.13 period 06 : 181.19 period 07 : 178.67 period 08 : 177.16 period 09 : 176.26 Model training finished.
MIT
dl/google-ml-crashcourse/exercises/01_first_steps_with_tensor_flow.ipynb
AtmaMani/pyChakras
Homework 4The homework consists of two parts: theoretical part (5 pts) and coding part (25 pts). - All theoretical questions must be answered in your own words, do not copy-paste text from the internet. Points can be deducted for terrible formatting or incomprehensible English. - Code must be commented. If you use cod...
# As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from fc_net import * from data_utils import get_CIFAR10_data from gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from solver import Solver %matplotlib inline plt...
('X_train: ', (49000, 3, 32, 32)) ('y_train: ', (49000,)) ('X_val: ', (1000, 3, 32, 32)) ('y_val: ', (1000,)) ('X_test: ', (1000, 3, 32, 32)) ('y_test: ', (1000,))
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Affine layer: foward**Task 2.1.1 (1pt):**Open the file `layers.py` and implement the `affine_forward` function. Once you are done you can test your implementaion by running the following:
# Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.p...
Testing affine_forward function: difference: 9.7698500479884e-10
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Affine layer: backward**Task 2.1.2 (1pt):**Now implement the `affine_backward` function and test your implementation using numeric gradient checking.
# Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w...
Testing affine_backward function: dx error: 1.0908199508708189e-10 dw error: 2.1752635504596857e-10 db error: 7.736978834487815e-12
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
ReLU layer: forward**Taks 2.1.3 (1pt):** Implement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following:
# Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0...
Testing relu_forward function: difference: 4.999999798022158e-08
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
ReLU layer: backward**Task 2.1.4 (1pt):** Now implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking:
np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel...
Testing relu_backward function: dx error: 3.2756349136310288e-12
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
"Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `layer_utils.py`.For now take a look at the `affine_relu_for...
from layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient...
Testing affine_relu_forward: dx error: 6.395535042049294e-11 dw error: 8.162011105764925e-11 db error: 7.826724021458994e-12
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Softmax loss layerYou implemented this loss function in the last assignment, so we'll give it to you for free here. You should still make sure you understand how they work by looking at the implementation in `layers.py`.You can make sure that the implementations are correct by running the following:
np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2...
Testing softmax_loss: loss: 2.302545844500738 dx error: 9.384673161989355e-09
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.**Task 2.2 (3pts):** Open the file `fc_net.py` and ...
np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(mode...
Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.22e-08 W2 relative error: 3.17e-10 b1 relative error: 6.19e-09 b2 relative error: 4.33e-10 Running numeric gradient check with reg = 0.7 W1 relat...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.**Task 2.3 (1pt):** Open the file `solver.py` and read through it to familiarize yourself with the...
model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ##############################################...
_____no_output_____
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers. Read through the `FullyConnectedNet` class in the file `fc_net.py`.**Task 2.4.1 (6pts):** Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing d...
np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.fl...
Running check with reg = 0 Initial loss: 2.3004790897684924 W1 relative error: 1.48e-07 W2 relative error: 2.21e-05 W3 relative error: 3.53e-07 b1 relative error: 5.38e-09 b2 relative error: 2.09e-09 b3 relative error: 5.80e-11 Running check with reg = 3.14 Initial loss: 7.052114776533016 W1 relative error: 6.86e-0...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
**Task 2.4.2 (1pt):** As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy with...
# TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } # weight_scale = 1e-2 # learning_rate = 1e-4 # after several test with many values, th...
(Iteration 1 / 40) loss: 357.428290 (Epoch 0 / 20) train acc: 0.220000; val_acc: 0.111000 (Epoch 1 / 20) train acc: 0.380000; val_acc: 0.141000 (Epoch 2 / 20) train acc: 0.520000; val_acc: 0.138000 (Epoch 3 / 20) train acc: 0.740000; val_acc: 0.130000 (Epoch 4 / 20) train acc: 0.820000; val_acc: 0.153000 (Epoch 5 / 20)...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
**Task 2.4.2 (1pt):** Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
# TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } # learning_rate = 1e-3 # weight_scale = 1e-5 # Found the best combination learning rate...
(Iteration 1 / 40) loss: 166.501707 (Epoch 0 / 20) train acc: 0.220000; val_acc: 0.116000 (Epoch 1 / 20) train acc: 0.240000; val_acc: 0.083000 (Epoch 2 / 20) train acc: 0.160000; val_acc: 0.104000 (Epoch 3 / 20) train acc: 0.520000; val_acc: 0.106000 (Epoch 4 / 20) train acc: 0.700000; val_acc: 0.131000 (Epoch 5 / 20)...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
**Task 2.4.2 (2pt):** Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net?**Your Answer:** - Five-layer network is more sensitive to small changes in comparison with three-layer network- With the same weight scale and learning rate, the process of over...
from optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray(...
next_w error: 8.882347033505819e-09 velocity error: 4.269287743278663e-09
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, ...
running with sgd (Iteration 1 / 200) loss: 2.559978 (Epoch 0 / 5) train acc: 0.103000; val_acc: 0.108000 (Iteration 11 / 200) loss: 2.291086 (Iteration 21 / 200) loss: 2.153591 (Iteration 31 / 200) loss: 2.082693 (Epoch 1 / 5) train acc: 0.277000; val_acc: 0.242000 (Iteration 41 / 200) loss: 2.004171 (Iteration 51 / 2...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.**Task 2.5.2 (4pts):** In the file `optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` funct...
# Test RMSProp implementation; you should see errors less than 1e-7 from optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _...
next_w error: 1.1395691798535431e-07 v error: 4.208314038113071e-09 m error: 4.214963193114416e-09
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules:
learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, updat...
running with adam (Iteration 1 / 200) loss: 3.476928 (Epoch 0 / 5) train acc: 0.143000; val_acc: 0.114000 (Iteration 11 / 200) loss: 2.089203 (Iteration 21 / 200) loss: 2.211850 (Iteration 31 / 200) loss: 1.786014 (Epoch 1 / 5) train acc: 0.393000; val_acc: 0.340000 (Iteration 41 / 200) loss: 1.743813 (Iteration 51 / ...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Train a good model!**Task 2.6 (2pts):** Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%...
best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. ...
Running: Learning rate: 3.000000e-04 Weight scale: 2.500000e-02 Dropout: 9.000000e-01 (Iteration 1 / 16330) loss: 3.387063 (Epoch 0 / 10) train acc: 0.080000; val_acc: 0.112000 (Iteration 401 / 16330) loss: 2.038029 (Iteration 801 / 16330) loss: 1.914008 (Iteration 1201 / 16330) loss: 1.880346 (Iteration 1601 / 16330) ...
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
Test your modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set.
y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean())
Validation set accuracy: 0.507 Test set accuracy: 0.516
MIT
practice4/FullyConnectedNets_plus_bonus.ipynb
enliktjioe/nn2020
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier...
import json from google.colab import files license_keys = files.upload() with open(list(license_keys.keys())[0]) as f: license_keys = json.load(f) license_keys.keys() import os # Install java ! apt-get update -qq ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null os.environ["JAVA_HOME"] = "/usr/lib/j...
2.6.2
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
ADE Classifier Pipeline (with a pretrained model)`True` : The sentence is talking about a possible ADE`False` : The sentences doesn't have any information about an ADE. ADE Classifier with BioBert ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABaIAAAEECAYAAADal0MeAAAgAElEQVR4Aeyd2ascxfv//Qe89corL7zwwgtBEE...
# Annotator that transforms a text column from dataframe into an Annotation ready for NLP documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("sentence") # Tokenizer splits words in a relevant format for NLP tokenizer = Tokenizer()\ .setInputCols(["sentence"])\ .setOutputCol("token") ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
as you see `gastric problems` is not detected as `ADE` as it is in a negative context. So, classifier did a good job detecting that.
text="I just took a Metformin and started to feel dizzy." ade_lp_pipeline.annotate(text)['class'][0] t=''' Always tired, and possible blood clots. I was on Voltaren for about 4 years and all of the sudden had a minor stroke and had blood clots that traveled to my eye. I had every test in the book done at the hospital,...
True False True False
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
ADE Classifier trained with conversational (short) sentences This model is trained on short, conversational sentences related to ADE and is supposed to do better on the text that is short and used in a daily context. ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABc4AAAESCAYAAADEw0ZmAAAgAElEQVR4Aeyd2Y8U1fu...
conv_classsifierdl = ClassifierDLModel.pretrained("classifierdl_ade_conversational_biobert", "en", "clinical/models")\ .setInputCols(["sentence", "sentence_embeddings"]) \ .setOutputCol("class") conv_ade_clf_pipeline = Pipeline( stages=[documentAssembler, tokenizer, bert_embed...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
ADE NERExtracts `ADE` and `DRUG` entities from text. ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACAwAAAEMCAYAAABKwbYWAAAgAElEQVR4Aeydd7cURfe23w/yM2cwYUIFUdFHQYIBDKgIBlABFUQxICqgIj4ogiIIAipBERBFUARJCgYwgAFUEAUDiDk9/9a7rmLtsaZP95zuPnPgzMzNWmd1T3dVddWuq6ub3nft+n8u4d+XX37p+Pvf//6nP9lADIgBMSAGxIAYEANiQAyIATE...
documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentenceDetector = SentenceDetector()\ .setInputCols(["document"])\ .setOutputCol("sentence") tokenizer = Tokenizer()\ .setInputCols(["sentence"])\ .setOutputCol("token") word_embeddings = WordEmbeddingsModel.pretrai...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
as you see `gastric problems` is not detected as `ADE` as it is in a negative context. So, NER did a good job ignoring that. ADE NER with Bert embeddings ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACCQAAAEKCAYAAADAEhYvAAAgAElEQVR4Aeyd95cURfu33z/ka8SMCROGRRETKqACBkwYABUwIIoBUQETPiiCD4IiJoIgIkpQBCUJJhRBBV...
documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentenceDetector = SentenceDetector()\ .setInputCols(["document"])\ .setOutputCol("sentence") tokenizer = Tokenizer()\ .setInputCols(["sentence"])\ .setOutputCol("token") bert_embeddings = BertEmbeddings.pretrained("...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
Looks like Bert version of NER returns more entities than clinical embeddings version. NER and Classifier combined with AssertionDL Model
assertion_ner_converter = NerConverter() \ .setInputCols(["sentence", "token", "ner"]) \ .setOutputCol("ass_ner_chunk")\ .setWhiteList(['ADE']) biobert_assertion = AssertionDLModel.pretrained("assertiondl_biobert", "en", "clinical/models") \ .setInputCols(["sentence", "ass_ner_chunk", "embeddings"]) \ .s...
I feel a bit drowsy & have a little blurred vision, so far no gastric problems. I have been on Arthrotec 50 for over 10 years on and off, only taking it when I needed it. Due to my arthritis getting progressively worse, to the point where I am in tears with the agony, gp's started me on 75 twice a day and I have to tak...
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
Looks great ! `gastric problems` is detected as `ADE` and `absent` ADE models applied to Spark Dataframes
import pyspark.sql.functions as F ! wget -q https://raw.githubusercontent.com/JohnSnowLabs/spark-nlp-workshop/master/tutorials/Certification_Trainings/Healthcare/data/sample_ADE_dataset.csv ade_DF = spark.read\ .option("header", "true")\ .csv("./sample_ADE_dataset.csv")\ ...
+--------------------------------------------------+-----+ | text|label| +--------------------------------------------------+-----+ |Do U know what Meds are R for bipolar depressio...|False| |# hypercholesterol: Because of elevated CKs (pe...| True| |Her weight, respirtory s...
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
**With BioBert version of NER** (will be slower but more accurate)
import pyspark.sql.functions as F ner_converter = NerConverter() \ .setInputCols(["sentence", "token", "ner"]) \ .setOutputCol("ner_chunk")\ .setWhiteList(['ADE']) ner_pipeline = Pipeline(stages=[ documentAssembler, sentenceDetector, tokenizer, bert_embeddings, ade_ner_bert, ner_convert...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
**Doing the same with clinical embeddings version** (faster results)
import pyspark.sql.functions as F ner_converter = NerConverter() \ .setInputCols(["sentence", "token", "ner"]) \ .setOutputCol("ner_chunk")\ .setWhiteList(['ADE']) ner_pipeline = Pipeline(stages=[ documentAssembler, sentenceDetector, tokenizer, word_embeddings, ade_ner, ner_converter]) ...
+----------------------------------------------------------------------+----------------------------------------------------------------------+ | text| ADE_phrases| +-------------------------------...
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
creating sentence dataframe (one sentence per row) and getting ADE entities and categories
documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentenceDetector = SentenceDetector()\ .setInputCols(["document"])\ .setOutputCol("sentence")\ .setExplodeSentences(True) tokenizer = Tokenizer()\ .setInputCols(["sentence"])\ .setOutputCol("token") bert_embeddings...
+------------------------------------------------------------+---------------------------------------------+-------+ | sentence| ADE_phrases| is_ADE| +------------------------------------------------------------+------------------------...
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
Creating a pretrained pipeline with ADE NER, Assertion and Classifer
# Annotator that transforms a text column from dataframe into an Annotation ready for NLP documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("sentence") # Tokenizer splits words in a relevant format for NLP tokenizer = Tokenizer()\ .setInputCols(["sentence"])\ .setOutputCol("token") ...
_____no_output_____
Apache-2.0
tutorials/Certification_Trainings/Healthcare/16.Adverse_Drug_Event_ADE_NER_and_Classifier.ipynb
ewbolme/spark-nlp-workshop
📝 Exercise M1.03The goal of this exercise is to compare the statistical performance of ourclassifier (81% accuracy) to some baseline classifiers that would ignore theinput data and instead make constant predictions.- What would be the score of a model that always predicts `' >50K'`?- What would be the score of a mode...
import pandas as pd adult_census = pd.read_csv("../datasets/adult-census.csv")
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_01.ipynb
ThomasBourgeois/scikit-learn-mooc
We will first split our dataset to have the target separated from the dataused to train our predictive model.
target_name = "class" target = adult_census[target_name] data = adult_census.drop(columns=target_name)
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_01.ipynb
ThomasBourgeois/scikit-learn-mooc
We start by selecting only the numerical columns as seen in the previousnotebook.
numerical_columns = [ "age", "capital-gain", "capital-loss", "hours-per-week"] data_numeric = data[numerical_columns]
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_01.ipynb
ThomasBourgeois/scikit-learn-mooc
Next, let's split the data and target into a train and test set.
from sklearn.model_selection import train_test_split data_numeric_train, data_numeric_test, target_train, target_test = \ train_test_split(data_numeric, target, random_state=0) from sklearn.model_selection import train_test_split from sklearn.dummy import DummyClassifier # Write your code here.
_____no_output_____
CC-BY-4.0
notebooks/02_numerical_pipeline_ex_01.ipynb
ThomasBourgeois/scikit-learn-mooc
Attack Password with Timing Analysis (Preparation)Supported setups:SCOPES:* OPENADCPLATFORMS:* CWLITEXMEGA Basic setup for Chip-Whisperer Lite
SCOPETYPE = 'OPENADC' PLATFORM = 'CWLITEXMEGA' CRYPTO_TARGET = 'NONE'
_____no_output_____
MIT
VM_Files/Mikrocontroller_1_Prepare.ipynb
stefanwitossek/securec_ws1920
Firmware Setup our `PLATFORM`, then build the firmware:
%%bash -s "$PLATFORM" "$CRYPTO_TARGET" cd ../hardware/victims/firmware/Mikrocontroller_1 make PLATFORM=$1 CRYPTO_TARGET=$2
rm -f -- basic-passwdcheck-CWLITEXMEGA.hex rm -f -- basic-passwdcheck-CWLITEXMEGA.eep rm -f -- basic-passwdcheck-CWLITEXMEGA.cof rm -f -- basic-passwdcheck-CWLITEXMEGA.elf rm -f -- basic-passwdcheck-CWLITEXMEGA.map rm -f -- basic-passwdcheck-CWLITEXMEGA.sym rm -f -- basic-passwdcheck-CWLITEXMEGA.lss rm -f -- objdir/*.o...
MIT
VM_Files/Mikrocontroller_1_Prepare.ipynb
stefanwitossek/securec_ws1920
Setup Flash compiled Code to Target
%run "Helper_Scripts/Setup_Generic.ipynb" fw_path = '../hardware/victims/firmware/Mikrocontroller_1/basic-passwdcheck-{}.hex'.format(PLATFORM) cw.program_target(scope, prog, fw_path)
XMEGA Programming flash... XMEGA Reading flash... Verified flash OK, 2709 bytes
MIT
VM_Files/Mikrocontroller_1_Prepare.ipynb
stefanwitossek/securec_ws1920
Disconnect Scope and Target
scope.dis() target.dis()
_____no_output_____
MIT
VM_Files/Mikrocontroller_1_Prepare.ipynb
stefanwitossek/securec_ws1920
Annotation Converter> Converter to covert annotations into different formats.
# export def convert(input_adapter: AnnotationAdapter, output_adapter: AnnotationAdapter): """ Convert input annotations to output annotations. `input_adapter`: the input annotation adapter `output_adapter`: the output annotation adapter """ categories = input_adapter.read_categories() annot...
_____no_output_____
Apache-2.0
annotation_converter.ipynb
AI-Force/aiforce
Helper Methods
# export def configure_logging(logging_level=logging.INFO): """ Configures logging for the system. :param logging_level: The logging level to use. """ logging.basicConfig(level=logging_level)
_____no_output_____
Apache-2.0
annotation_converter.ipynb
AI-Force/aiforce
Run from command line To run the annotation converter from command line, use the following command:`python -m mlcore.annotation_converter [parameters]` The following parameters are supported:- `-i`, `--input_adapter`: The annotation adapter to the annotations to convert from (e.g.: *VIAAnnotationAdapter*)- `-o`, `--ou...
# export if __name__ == '__main__' and '__file__' in globals(): # for direct shell execution configure_logging() # read annotation adapters to use adapters = list_subclasses(annotation_package, AnnotationAdapter) parser = argparse.ArgumentParser() parser.add_argument("-i", ...
_____no_output_____
Apache-2.0
annotation_converter.ipynb
AI-Force/aiforce
Example: Image Object Detection to Multi Category Image Classification To convert image object detection annotations to multi category image classifications, run the following command: `python -m mlcore.annotation_converter --input_adapter VIAAnnotationAdapter --input_path data/image_object_detection/my_collection --o...
# hide # for generating scripts from notebook directly from nbdev.export import notebook2script notebook2script()
Converted annotation-core.ipynb. Converted annotation-folder_category_adapter.ipynb. Converted annotation-multi_category_adapter.ipynb. Converted annotation-via_adapter.ipynb. Converted annotation-yolo_adapter.ipynb. Converted annotation_converter.ipynb. Converted annotation_viewer.ipynb. Converted category_tools.ipynb...
Apache-2.0
annotation_converter.ipynb
AI-Force/aiforce