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
We now modify the `LeoParser` to keep track of the chain of constrains that we mentioned earlier.
class LeoParser(LeoParser): def __init__(self, grammar, **kwargs): super().__init__(grammar, **kwargs) self._postdots = {}
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Next, we update the `uniq_postdot()` so that it tracks the chain of links.
class LeoParser(LeoParser): def uniq_postdot(self, st_A): col_s1 = st_A.s_col parent_states = [ s for s in col_s1.states if s.expr and s.at_dot() == st_A.name ] if len(parent_states) > 1: return None matching_st_B = [s for s in parent_states if s.dot =...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We next define a method `expand_tstate()` that, when given a `TState`, generates all the intermediate links that we threw away earlier for a given end column.
class LeoParser(LeoParser): def expand_tstate(self, state, e): if state._t() not in self._postdots: return c_C = self._postdots[state._t()] e.add(c_C.advance()) self.expand_tstate(c_C.back(), e)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We define a `rearrange()` method to generate a reversed table where each column contains states that start at that column.
class LeoParser(LeoParser): def rearrange(self, table): f_table = [Column(c.index, c.letter) for c in table] for col in table: for s in col.states: f_table[s.s_col.index].states.append(s) return f_table
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Here is the rearranged table. (Can you explain why the Column 0 has a large number of `` items?)
ep = LeoParser(RR_GRAMMAR) columns = ep.chart_parse(mystring, ep.start_symbol()) r_table = ep.rearrange(columns) for col in r_table: print(col, "\n")
None chart[0] <A>:= |(0,0) <start>:= <A> |(0,0) <A>:= a <A> |(0,1) <start>:= <A> |(0,1) <start>:= <A> |(0,2) <start>:= <A> |(0,3) <start>:= <A> |(0,4) <start>:= <A> |(0,5) <start>:= <A> |(0,6) a chart[1] <A>:= |(1,1) <A>:= a <A> |(1,2) a chart[2] <A>:= |(2,2) <A>:= a <A> |(2,3) a chart[3] <A>:= |(3,3) <A>:= a <A>...
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We save the result of rearrange before going into `parse_forest()`.
class LeoParser(LeoParser): def parse(self, text): cursor, states = self.parse_prefix(text) start = next((s for s in states if s.finished()), None) if cursor < len(text) or not start: raise SyntaxError("at " + repr(text[cursor:])) self.r_table = self.rearrange(self.table...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Finally, during `parse_forest()`, we first check to see if it is a transitive state, and if it is, expand it to the original sequence of states using `traverse_constraints()`.
class LeoParser(LeoParser): def parse_forest(self, chart, state): if isinstance(state, TState): self.expand_tstate(state.back(), state.e_col) return super().parse_forest(chart, state)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
This completes our implementation of `LeoParser`. We check whether the previously defined right recursive grammars parse and return the correct parse trees.
result = LeoParser(RR_GRAMMAR).parse(mystring) for tree in result: assert mystring == tree_to_string(tree) result = LeoParser(RR_GRAMMAR2).parse(mystring2) for tree in result: assert mystring2 == tree_to_string(tree) result = LeoParser(RR_GRAMMAR3).parse(mystring3) for tree in result: assert mystring3 == tr...
'bbbbbbb' 'bbbbbbb'
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Exercise 6: Filtered Earley Parser One of the problems with our Earley and Leo Parsers is that it can get stuck in infinite loops when parsing with grammars that contain token repetitions in alternatives. For example, consider the grammar below.
RECURSION_GRAMMAR: Grammar = { "<start>": ["<A>"], "<A>": ["<A>", "<A>aa", "AA", "<B>"], "<B>": ["<C>", "<C>cc", "CC"], "<C>": ["<B>", "<B>bb", "BB"] }
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
With this grammar, one can produce an infinite chain of derivations of ``, (direct recursion) or an infinite chain of derivations of ` -> -> ...` (indirect recursion). The problem is that, our implementation can get stuck trying to derive one of these infinite chains. One possibility is to use the `LazyExtractor`. An...
from ExpectError import ExpectTimeout with ExpectTimeout(1, print_traceback=False): mystring = 'AA' parser = LeoParser(RECURSION_GRAMMAR) tree, *_ = parser.parse(mystring) assert tree_to_string(tree) == mystring display_tree(tree)
RecursionError: maximum recursion depth exceeded (expected)
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Can you implement a solution such that any tree that contains such a chain is discarded? **Solution.** Here is a possible solution.
class FilteredLeoParser(LeoParser): def forest(self, s, kind, seen, chart): return self.parse_forest(chart, s, seen) if kind == 'n' else (s, []) def parse_forest(self, chart, state, seen=None): if isinstance(state, TState): self.expand_tstate(state.back(), state.e_col) def ...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
With the `FilteredLeoParser`, we should be able to recover minimal parse trees in reasonable time.
mystring = 'AA' parser = FilteredLeoParser(RECURSION_GRAMMAR) tree, *_ = parser.parse(mystring) assert tree_to_string(tree) == mystring display_tree(tree) mystring = 'AAaa' parser = FilteredLeoParser(RECURSION_GRAMMAR) tree, *_ = parser.parse(mystring) assert tree_to_string(tree) == mystring display_tree(tree) mystring...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
As can be seen, we are able to recover minimal parse trees without hitting on infinite chains. Exercise 7: Iterative Earley ParserRecursive algorithms are quite handy in some cases but sometimes we might want to have iteration instead of recursion due to memory or speed problems. Can you implement an iterative version...
class IterativeEarleyParser(EarleyParser): def parse_paths(self, named_expr_, chart, frm, til_): return_paths = [] path_build_stack = [(named_expr_, til_, [])] def iter_paths(path_prefix, path, start, k, e): x = path_prefix + [(path, k)] if not e: ret...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Next we used these paths to recover the forest data structure using `parse_forest()`. Since `parse_forest()` does not recurse, we reuse the original definition. Next, we define `extract_a_tree()` Now we are ready to extract trees from the forest using `extract_a_tree()`
class IterativeEarleyParser(IterativeEarleyParser): def choose_a_node_to_explore(self, node_paths, level_count): first, *rest = node_paths return first def extract_a_tree(self, forest_node_): start_node = (forest_node_[0], []) tree_build_stack = [(forest_node_, start_node[-1], 0...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
For now, we simply extract the first tree found.
class IterativeEarleyParser(IterativeEarleyParser): def extract_trees(self, forest): yield self.extract_a_tree(forest)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Let's see if it works with some of the grammars we have seen so far.
test_cases: List[Tuple[Grammar, str]] = [ (A1_GRAMMAR, '1-2-3+4-5'), (A2_GRAMMAR, '1+2'), (A3_GRAMMAR, '1+2+3-6=6-1-2-3'), (LR_GRAMMAR, 'aaaaa'), (RR_GRAMMAR, 'aa'), (DIRECTLY_SELF_REFERRING, 'select a from a'), (INDIRECTLY_SELF_REFERRING, 'select a from a'), (RECURSION_GRAMMAR, 'AA'), ...
0 1-2-3+4-5 1 1+2 2 1+2+3-6=6-1-2-3 3 aaaaa 4 aa 5 select a from a 6 select a from a 7 AA 8 AAaaaa 9 BBccbb
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
As can be seen, our `IterativeEarleyParser` is able to handle recursive grammars. However, it can only extract the first tree found. What should one do to get all possible parses? What we can do, is to keep track of options to explore at each `choose_a_node_to_explore()`. Next, capture in the nodes explored in a tree d...
def firstset(grammar, nullable): first = {i: {i} for i in terminals(grammar)} for k in grammar: first[k] = {EPSILON} if k in nullable else set() return firstset_((rules(grammar), first, nullable))[1]
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Finally, we rely on the `fixpoint` to update the first set with the contents of the current first set until the first set stops changing.
def first_expr(expr, first, nullable): tokens = set() for token in expr: tokens |= first[token] if token not in nullable: break return tokens @fixpoint def firstset_(arg): (rules, first, epsilon) = arg for A, expression in rules: first[A] |= first_expr(expression,...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Exercise 9: Follow Set of a NonterminalThe follow set definition is similar to the first set. The follow set of a nonterminal is the set of terminals that can occur just after that nonterminal is used in any derivation. The follow set of the start symbol is `EOF`, and the follow set of any nonterminal is the super set...
EOF = '\0' def followset(grammar, start): follow = {i: set() for i in grammar} follow[start] = {EOF} epsilon = nullable(grammar) first = firstset(grammar, epsilon) return followset_((grammar, epsilon, first, follow))[-1]
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Given the current follow set, one can update the follow set as follows:
@fixpoint def followset_(arg): grammar, epsilon, first, follow = arg for A, expression in rules(grammar): f_B = follow[A] for t in reversed(expression): if t in grammar: follow[t] |= f_B f_B = f_B | first[t] if t in epsilon else (first[t] - {EPSILON}) ...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Exercise 10: A LL(1) ParserAs we mentioned previously, there exist other kinds of parsers that operate left-to-right with right most derivation (*LR(k)*) or left-to-right with left most derivation (*LL(k)*) with _k_ signifying the amount of lookahead the parser is permitted to use.What should one do with the lookahead...
class LL1Parser(Parser): def parse_table(self): self.my_rules = rules(self.cgrammar) self.table = ... # fill in here to produce def rules(self): for i, rule in enumerate(self.my_rules): print(i, rule) def show_table(self): ts = list(sorted(terminals(sel...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
On invocation of `LL1Parser(A2_GRAMMAR).show_table()`It should result in the following table:
for i, r in enumerate(rules(canonical(A2_GRAMMAR))): print("%d\t %s := %s" % (i, r[0], r[1]))
0 <start> := ['<expr>'] 1 <expr> := ['<integer>', '<expr_>'] 2 <expr_> := ['+', '<expr>'] 3 <expr_> := ['-', '<expr>'] 4 <expr_> := [] 5 <integer> := ['<digit>', '<integer_>'] 6 <integer_> := ['<integer>'] 7 <integer_> := [] 8 <digit> := ['0'] 9 <digit> := ['1'] 10 <digit> := ['2'] 11 <digit> := ['3'] 12 <...
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
|Rule Name || + | - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9||-----------||---|---|---|---|---|---|---|---|---|---|---|--||start || | | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0||expr || | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1||expr_ || 2 | 3 | | | | | | | | | | ||integer || | | 5 ...
class LL1Parser(LL1Parser): def predict(self, rulepair, first, follow, epsilon): A, rule = rulepair rf = first_expr(rule, first, epsilon) if nullable_expr(rule, epsilon): rf |= follow[A] return rf def parse_table(self): self.my_rules = rules(self.cgrammar) ...
Rule Name | + | - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 <start> | | | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 <expr> | | | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 <expr_> | 2 | 3 | | | | | | | | | | <integer> | | | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 | 5 <integer_> | 7 | 7 | 6 | 6 ...
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Part 2: The ParserOnce we have the parse table, implementing the parser is as follows: Consider the first item from the sequence of tokens to parse, and seed the stack with the start symbol.While the stack is not empty, extract the first symbol from the stack, and if the symbol is a terminal, verify that the symbol ma...
class LL1Parser(LL1Parser): def parse_helper(self, stack, inplst): inp, *inplst = inplst exprs = [] while stack: val, *stack = stack if isinstance(val, tuple): exprs.append(val) elif val not in self.cgrammar: # terminal ass...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
100 numpy exercisesThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflowand in the numpy documentation. The goal of this collection is to offer a quick reference for both oldand new users but also to provide a set of exercises for those who teach.If you find an error o...
import initialise as ini
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
1. Import the numpy package under the name `np` (★☆☆)
import numpy as np
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
2. Print the numpy version and the configuration (★☆☆)
np.__version__
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
3. Create a null vector of size 10 (★☆☆)
np.zeros(10)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
4. How to find the memory size of any array (★☆☆)
random_array = np.array(45) random_array.nbytes
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
5. How to get the documentation of the numpy add function from the command line? (★☆☆)
np.info('add')
*** Found in numpy *** add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) Add arguments element-wise. Parameters ---------- x1, x2 : array_like The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common ...
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
x = np.zeros(10) x[4] = 1
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
7. Create a vector with values ranging from 10 to 49 (★☆☆)
a = np.array(range(10,50))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
8. Reverse a vector (first element becomes last) (★☆☆)
a[::-1]
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
np.reshape(np.array(range(0,9)), (3, 3))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
a = [1,2,0,0,4,0] np.nonzero(a)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
11. Create a 3x3 identity matrix (★☆☆)
np.eye(3)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
12. Create a 3x3x3 array with random values (★☆☆)
from numpy import random random.randint(10, size=(3,3))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
from numpy import random x = random.randint(100, size=(10,10)) x, np.amax(x), np.amin(x)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
14. Create a random vector of size 30 and find the mean value (★☆☆)
from numpy import random np.mean(random.randint(10, size=(30)))
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
15. Create a 2d array with 1 on the border and 0 inside (★☆☆)
a = np.ones((4,4)) a[1: -1, 1:-1] = 0 a
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
16. How to add a border (filled with 0's) around an existing array? (★☆☆)
a = np.ones((3,3)) np.pad(a, 1)
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
17. What is the result of the following expression? (★☆☆)```python0 * np.nannp.nan == np.nannp.inf > np.nannp.nan - np.nannp.nan in set([np.nan])0.3 == 3 * 0.1``` 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
x = random.randint(5, size=(5, 5)) np.diag(x) = np.array([1, 2, 3, 4, 5])
_____no_output_____
MIT
100_Numpy_exercises.ipynb
ViniciusgCaetano/numpy-100
Predicting Boston Housing Prices Using XGBoost in SageMaker (Batch Transform)_Deep Learning Nanodegree Program | Deployment_---As an introduction to using SageMaker's Low Level Python API we will look at a relatively simple problem. Namely, we will use the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/dat...
# Make sure that we use SageMaker 1.x !pip install sagemaker==1.72.0
Collecting sagemaker==1.72.0 Downloading sagemaker-1.72.0.tar.gz (297 kB)  |████████████████████████████████| 297 kB 41.4 MB/s eta 0:00:01 [?25hRequirement already satisfied: boto3>=1.14.12 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (1.16.19) Requirement ...
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 0: Setting up the notebookWe begin by setting up all of the necessary bits required to run our notebook. To start that means loading all of the Python modules we will need.
%matplotlib inline import os import time from time import gmtime, strftime import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_boston import sklearn.model_selection
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
In addition to the modules above, we need to import the various bits of SageMaker that we will be using.
import sagemaker from sagemaker import get_execution_role from sagemaker.amazon.amazon_estimator import get_image_uri # This is an object that represents the SageMaker session that we are currently operating in. This # object contains some useful information that we will need to access later such as our region. sessio...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 1: Downloading the dataFortunately, this dataset can be retrieved using sklearn and so this step is relatively straightforward.
boston = load_boston()
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 2: Preparing and splitting the dataGiven that this is clean tabular data, we don't need to do any processing. However, we do need to split the rows in the dataset up into train, test and validation sets.
# First we package up the input data and the target variable (the median value) as pandas dataframes. This # will make saving the data to a file a little easier later on. X_bos_pd = pd.DataFrame(boston.data, columns=boston.feature_names) Y_bos_pd = pd.DataFrame(boston.target) # We split the dataset into 2/3 training ...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 3: Uploading the data files to S3When a training job is constructed using SageMaker, a container is executed which performs the training operation. This container is given access to data that is stored in S3. This means that we need to upload the data we want to use for training to S3. In addition, when we perfor...
# This is our local data directory. We need to make sure that it exists. data_dir = '../data/boston' if not os.path.exists(data_dir): os.makedirs(data_dir) # We use pandas to save our test, train and validation data to csv files. Note that we make sure not to include header # information or an index as this is requ...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Upload to S3Since we are currently running inside of a SageMaker session, we can use the object which represents this session to upload our data to the 'default' S3 bucket. Note that it is good practice to provide a custom prefix (essentially an S3 folder) to make sure that you don't accidentally interfere with data u...
prefix = 'boston-xgboost-LL' test_location = session.upload_data(os.path.join(data_dir, 'test.csv'), key_prefix=prefix) val_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix) train_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix)
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 4: Train and construct the XGBoost modelNow that we have the training and validation data uploaded to S3, we can construct a training job for our XGBoost model and build the model itself. Set up the training jobFirst, we will set up and execute a training job for our model. To do this we need to specify some info...
# We will need to know the name of the container that we want to use for training. SageMaker provides # a nice utility method to construct this for us. container = get_image_uri(session.boto_region_name, 'xgboost') # We now specify the parameters we wish to use for our training job training_params = {} # We need to s...
'get_image_uri' method will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2. There is a more up to date SageMaker XGBoost image. To use the newer image, please set 'repo_version'='1.0-1'. For example: get_image_uri(region, 'xgboost', '1.0-1').
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Execute the training jobNow that we've built the dictionary object containing the training job parameters, we can ask SageMaker to execute the job.
# First we need to choose a training job name. This is useful for if we want to recall information about our # training job at a later date. Note that SageMaker requires a training job name and that the name needs to # be unique, which we accomplish by appending the current timestamp. training_job_name = "boston-xgboos...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
The training job has now been created by SageMaker and is currently running. Since we need the output of the training job, we may wish to wait until it has finished. We can do so by asking SageMaker to output the logs generated by the training job and continue doing so until the training job terminates.
session.logs_for_job(training_job_name, wait=True)
2020-12-17 03:42:31 Starting - Starting the training job... 2020-12-17 03:42:33 Starting - Launching requested ML instances...... 2020-12-17 03:43:48 Starting - Preparing the instances for training...... 2020-12-17 03:44:42 Downloading - Downloading input data... 2020-12-17 03:45:17 Training - Downloading the training ...
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Build the modelNow that the training job has completed, we have some model artifacts which we can use to build a model. Note that here we mean SageMaker's definition of a model, which is a collection of information about a specific algorithm along with the artifacts which result from a training job.
# We begin by asking SageMaker to describe for us the results of the training job. The data structure # returned contains a lot more information than we currently need, try checking it out yourself in # more detail. training_job_info = session.sagemaker_client.describe_training_job(TrainingJobName=training_job_name) m...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Step 5: Testing the modelNow that we have fit our model to the training data, using the validation data to avoid overfitting, we can test our model. To do this we will make use of SageMaker's Batch Transform functionality. In other words, we need to set up and execute a batch transform job, similar to the way that we ...
# Just like in each of the previous steps, we need to make sure to name our job and the name should be unique. transform_job_name = 'boston-xgboost-batch-transform-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) # Now we construct the data structure which will describe the batch transform job. transform_request = \ { ...
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Execute the batch transform jobNow that we have created the request data structure, it is time to ask SageMaker to set up and run our batch transform job. Just like in the previous steps, SageMaker performs these tasks in the background so that if we want to wait for the transform job to terminate (and ensure the job ...
transform_response = session.sagemaker_client.create_transform_job(**transform_request) transform_desc = session.wait_for_transform_job(transform_job_name)
..........................................................!
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Analyze the resultsNow that the transform job has completed, the results are stored on S3 as we requested. Since we'd like to do a bit of analysis in the notebook we can use some notebook magic to copy the resulting output from S3 and save it locally.
transform_output = "s3://{}/{}/batch-bransform/".format(session.default_bucket(),prefix) !aws s3 cp --recursive $transform_output $data_dir
Completed 2.3 KiB/2.3 KiB (28.7 KiB/s) with 1 file(s) remaining download: s3://sagemaker-us-east-1-302590777472/boston-xgboost-LL/batch-bransform/test.csv.out to ../data/boston/test.csv.out
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
To see how well our model works we can create a simple scatter plot between the predicted and actual values. If the model was completely accurate the resulting scatter plot would look like the line $x=y$. As we can see, our model seems to have done okay but there is room for improvement.
Y_pred = pd.read_csv(os.path.join(data_dir, 'test.csv.out'), header=None) plt.scatter(Y_test, Y_pred) plt.xlabel("Median Price") plt.ylabel("Predicted Price") plt.title("Median Price vs Predicted Price")
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Optional: Clean upThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a ...
# First we will remove all of the files contained in the data_dir directory !rm $data_dir/* # And then we delete the directory itself !rmdir $data_dir
_____no_output_____
MIT
Tutorials/Boston Housing - XGBoost (Batch Transform) - Low Level.ipynb
jobquiroz/sagemaker-deployment
Problema do negócio A empresa deseja uma análise dos preços dos produtos das lojas concorrentes para precificar melhor o próprio produto no mercado, neste caso, calças. Saída (Produto final)1. Descobrir a reposta para a pergunta calculando a mediana dos preços dos concorrentes2. Formato da entrega: tabela ou gráfico...
import requests import pandas as pd import numpy as np from bs4 import BeautifulSoup from datetime import datetime html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their n...
_____no_output_____
MIT
Web-Scraping-Beautiful-Soup.ipynb
FelipeOshiro/E-commerce-market-analysis
Buscar os detalhes de cada produto em suas paginas individuais: para extrair cor, tipo do tecido e codigo do produto
#Realizando a request da API url= 'https://www2.hm.com/en_us/productpage.0985159001.html' headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} page = requests.get(url, headers=headers) #requisição provinda de um navegador ...
_____no_output_____
MIT
Web-Scraping-Beautiful-Soup.ipynb
FelipeOshiro/E-commerce-market-analysis
Codigo único para extração dos detalhes de um produto
#Realizando a request da API url= 'https://www2.hm.com/en_us/productpage.0985159001.html' headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} page = requests.get(url, headers=headers) #requisição provinda de um navegador ...
_____no_output_____
MIT
Web-Scraping-Beautiful-Soup.ipynb
FelipeOshiro/E-commerce-market-analysis
Para vários produtos
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} #criando um dataframe vazio df_details = pd.DataFrame() aux=[] cols=['Art. No.','Composition','Fit','More sustainable materials','color_id','style_id','Size'] df_patte...
_____no_output_____
MIT
Web-Scraping-Beautiful-Soup.ipynb
FelipeOshiro/E-commerce-market-analysis
Project: Investigate Children Out of School Table of ContentsIntroductionData WranglingExploratory Data AnalysisConclusions Introduction> **Key notes**: "Gapminder has collected a lot of information about how people live their lives in different countries, tracked across the years, and on a number of different indica...
# Set up import statements for all of the packages that are planed to use; # Include a 'magic word' so that visualizations are plotted; # call on dataframe to display the first 5 rows. import pandas as pd import numpy as np import datetime from statistics import mode % matplotlib inline import matplotlib.pyplot as plt...
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Data Wrangling> **Key notes**: In this section of the report, the following work will be done: load the data; check for cleanliness; trim and clean dataset for analysis. General Properties
# return the datatypes of the columns. df1.dtypes # check for duplicates in the data. sum(df1.duplicated()) # check if any value is NaN in DataFrame and in how many columns df1.isnull().any().any(), sum(df1.isnull().any()) # Generates descriptive statistics, excluding NaN values. df1.describe()
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Data Cleaning
# Locate the columns whose NaN values needs to be treated col = df1.drop(['Children out of school, primary', 'Children out of school, primary, female'\ , 'Children out of school, primary, male'], axis=1) # Replace NaN with mean for c in col: c_mean = df1[c].mean() df1[c].fillna(c_mean, inplace...
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Exploratory Data Analysis Research Question 1: What is the total numbers of children out of primary school over years, indicate the male and female numbers as well?
# Get the sum for each group sum_tot = df1.iloc[:, 1:43] m_tot = df1.iloc[:, 44:86] f_tot = df1.iloc[:, 87:] tot = [] for t in sum_tot.columns: tot.append(sum_tot[t].sum()) m = [] for ma in m_tot.columns: m.append(m_tot[ma].sum()) f = [] for fa in f_tot.columns: f.append(f_tot[fa].sum()) # Plot x =...
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Research Question 2: What is distribution of female children who was out of primary school from 1980 to 1995?
# Target the year and plot sum_tot1 = sum_tot.iloc[:, 10:26] new_col = [] for ele in sum_tot1.columns: new_col.append(ele.split('_x')[0]) sum_tot1.columns = new_col plt.figure(figsize=(20,15)) sns.boxplot(data = sum_tot1);
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Research Question 3: What are numbers of children out of school in total, by male and female in China, 1985?
china = df1.copy() china = china.set_index('country') tot_chi = china.loc['China', '1985_x'] f_chi = china.loc['China', '1985_y'] m_chi = china.loc['China', '1985'] print('The numbers of children out of school in total, by male and female in China were \ {0:.0f}, {1:.0f} and {2:.0f} in 1985, respectively.'.format(tot_...
The numbers of children out of school in total, by male and female in China were 284172, 177367 and 122195 in 1985, respectively.
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Research Question 4: What are relationship of children out of school of female in China in russian and usa over time? Which has a better trend?
rus_us = df1.iloc[:, 0:42].copy() new_col1 = [] for ele in rus_us: new_col1.append(ele.split('_x')[0]) rus_us.columns = new_col1 rus_us = rus_us.set_index('country') rus_us_df = pd.DataFrame(columns=['USA','Russia']) rus_us_df['USA'] = rus_us.loc['United States'].values rus_us_df['Russia'] = rus_us.loc['Russ...
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
> There is a positive correlation between children droped out of primary school in Russia and USA. The estimated linear regression is shown as the blue line, the estimates varies in the light blue shade with 95% confident level. The trend of children out of school in USA is much higher than that of Russia over that pas...
overall_df = pd.DataFrame(columns=['year','numbers']) overall_df['year'] = rus_us.columns n_list =[] for n in rus_us.columns: n_list.append(rus_us[n].mean()) overall_df['numbers'] = np.array(n_list) overall_df.index = overall_df.year overall_df.plot(); plt.ylabel('Numers') plt.xlabel('Year') plt.title('Numbers...
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
> From the analysis we can conclude that the overall trend of children out of primary school had been descreasing starting between 1970 and 1975 at which point of time the numbers fell down dramatically Conclusions> In current study, a good amount of profound analysis has been carried out. Prior to each step, deailed ...
from subprocess import call call(['python', '-m', 'nbconvert', 'Investigate_Children_Out_of_School_20180108.ipynb'])
_____no_output_____
MIT
Investigate_Children_Out_of_School_20180108.ipynb
Shilin-Li/Investigate_Children_Out_of_School
Apache Kafka Integration + Preprocessing / Interactive Analysis with KSQL This notebook uses the combination of Python, Apache Kafka, KSQL for Machine Learning infrastructures. It includes code examples using ksql-python and other widespread components from Python’s machine learning ecosystem, like Numpy, pandas, Tens...
# Shows correct startup but does not work 100% yet. Better run this command from outside Jupyter if you have any problems (e.g. from Terminal)! ! confluent start ksql-server
This CLI is intended for development only, not for production https://docs.confluent.io/current/cli/index.html Using CONFLUENT_CURRENT: /var/folders/0s/0xdkb9n12yqdb3fs71926z3c0000gp/T/confluent.KQJxmlHC Starting zookeeper zookeeper is [UP] Starting kafka kafka is [UP] Starting schema-registry sc...
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Data Integration and Preprocessing with Python and KSQL First of all, create the Kafka Topic 'creditcardfraud_source' if it does not exist already:
! kafka-topics --zookeeper localhost:2181 --create --topic creditcardfraud_source --partitions 3 --replication-factor 1
WARNING: Due to limitations in metric names, topics with a period ('.') or underscore ('_') could collide. To avoid issues it is best to use either, but not both. Created topic "creditcardfraud_source".
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Then load KSQL library and initiate connection to KSQL server:
from ksql import KSQLAPI client = KSQLAPI('http://localhost:8088')
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Consume source data from Kafka Topic "creditcardfraud_source":
client.create_stream(table_name='creditcardfraud_source', columns_type=['Id bigint', 'Timestamp varchar', 'User varchar', 'Time int', 'V1 double', 'V2 double', 'V3 double', 'V4 double', 'V5 double', 'V6 double', 'V7 double', 'V8 double', 'V9 double', 'V10 double', 'V11 double', 'V12 double', 'V13 d...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Preprocessing: - Filter columns which are not needed - Filter messages where column 'class' is empty- Change data format to Avro for more convenient further processing
client.create_stream_as(table_name='creditcardfraud_preprocessed_avro', select_columns=['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Take a look at the creates KSQL Streams:
client.ksql('show streams')
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Take a look at the metadata of the KSQL Stream:
client.ksql('describe CREDITCARDFRAUD_PREPROCESSED_AVRO')
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Interactive query statement:
query = client.query('SELECT * FROM CREDITCARDFRAUD_PREPROCESSED_AVRO LIMIT 1') for item in query: print(item)
{"row":{"columns":[1547818491376,null,0,-1.3598071336738,-0.0727811733098497,2.53634673796914,1.37815522427443,-0.338320769942518,0 .462387777762292,0.239598554061257,0.0986979012610507,0.363786969611213,0.0907941719789316,-0.551599533260813,-0.617800855762348,-0.991389847235408,-0.311169353699879,1.46817697209427,...
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Produce single test data manually (if you did not connect to a real data stream which produces data continuously), e.g. from terminal: confluent produce creditcardfraud_source 1,"2018-12- 18T12:00:00Z","Hans",0,-1.3598071336738,-0.0727811733098497,2.53634673796914,1.37815522427443,-0.33832...
# TODO How to embed ' ' in Python ??? # See https://github.com/bryanyang0528/ksql-python/issues/54 # client.ksql('SET \'auto.offset.reset\'=\'earliest\'');
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Additional (optional) analysis and preprocessing examplesSome more examples for possible data wrangling and preprocessing with KSQL:- Anonymization- Augmentation- Merge / Join data frames
query = client.query('SELECT Id, MASK_LEFT(User, 2) FROM creditcardfraud_source LIMIT 1') for item in query: print(item) query = client.query('SELECT Id, IFNULL(Class, \'-1\') FROM creditcardfraud_source LIMIT 1') for item in query: print(item)
{"row":{"columns":[1,"-1"]},"errorMessage":null,"finalMessage":null} {"row":null,"errorMessage":null,"finalMessage":"Limit Reached"}
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Stream-Table-JoinFor the STREAM-TABLE-JOIN, you first need to create a Kafka Topic 'Users' (for the corresponding KSQL TABLE 'Users):
! kafka-topics --zookeeper localhost:2181 --create --topic users --partitions 3 --replication-factor 1
Created topic "users".
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Then create the KSQL Table:
client.create_table(table_name='users', columns_type=['userid varchar', 'gender varchar', 'regionid varchar'], topic='users', key='userid', value_format='AVRO') client.ksql("CREATE STREAM creditcardfraud_per_user WITH (VALUE_FORMAT='AVR...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Mapping from KSQL to NumPy / pandas for Machine Learning tasks
import numpy as np import pandas as pd import json
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
The query below command returns a Python generator. It can be printed e.g. by reading its values via next(query) or a for loop.Due to a current [bug in ksql-python library](https://github.com/bryanyang0528/ksql-python/issues/57), we need to to an additional line of Python code to strip out unnecessary info and change t...
query = client.query('SELECT * FROM CREDITCARDFRAUD_PREPROCESSED_AVRO LIMIT 8') # Returns a Python generator object #items = [item for item in query][:-1] # -1 to remove last record that is a dummy msg for "Limit Reached" #one_record = json.loads(''.join(items)) # Join two records as one as ksql-...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Generate some test data As discussed in the step-by-step guide, you have various options. Here we - ironically - read messages from a CSV file. This is for simple demo purposes so that you don't have to set up a real continuous Kafka stream. In real world or more advanced examples, you should connect to a real Kafka d...
# import packages # matplotlib inline #import pandas as pd #import numpy as np from scipy import stats import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns import pickle from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, precision_recall_curve fro...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
My Jupyter Notebook crashed sometimes in the next step 'model training' (probably memory issues):
# Reduce number of epochs and batch_size if your Jupyter crashes (due to memory issues) # nb_epoch = 100 # batch_size = 128 nb_epoch = 5 batch_size = 32 input_dim = train_x.shape[1] #num of columns, 30 encoding_dim = 14 hidden_dim = int(encoding_dim / 2) #i.e. 7 learning_rate = 1e-7 input_layer = Input(shape=(input_d...
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
The binary 'models/autoencoder_fraud.h5' is the trained model which can then be deployed anywhere to do prediction on new incoming events in real time. Model DeploymentThis demo focuses on the combination of Python and KSQL for data preprocessing and model training. If you want to understand the relation between Apac...
df = pd.read_csv("data/creditcard.csv") df.head() df.shape df.index df.columns df.values df.describe() df['Amount'] df[0:3] df.iloc[1,1] # Takes a minute or two (big CSV file)... #df.plot()
_____no_output_____
Apache-2.0
python-jupyter-apache-kafka-ksql-tensorflow-keras.ipynb
sundayayandele/python-jupyter-apache-kafka-ksql-tensorflow-keras
Multi-Layer Perceptron, MNIST---In this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.The process will be broken down into the following steps:>1. Load and visualize the data2. Define a neural network3. Train the model4. Evalu...
# import libraries import torch import numpy as np
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
--- Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)Downloading may take a few moments, and you should see your progress as the data is loading. You may also choose to change the `batch_size` if you want to load more data at a time.This cell will create DataLoaders for each of our...
from torchvision import datasets import torchvision.transforms as transforms from torch.utils.data.sampler import SubsetRandomSampler # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 20 # percentage of training set to use as validation valid_size = 0.2 ...
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
Visualize a Batch of Training DataThe first step in a classification task is to take a look at the data, make sure it is loaded in correctly, then make any initial observations about patterns in that data.
import matplotlib.pyplot as plt %matplotlib inline # obtain one batch of training images dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # plot the images in the batch, along with the corresponding labels fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = ...
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
View an Image in More Detail
img = np.squeeze(images[1]) fig = plt.figure(figsize = (12,12)) ax = fig.add_subplot(111) ax.imshow(img, cmap='gray') width, height = img.shape thresh = img.max()/2.5 for x in range(width): for y in range(height): val = round(img[x][y],2) if img[x][y] !=0 else 0 ax.annotate(str(val), xy=(y,x), ...
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
--- Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)The architecture will be responsible for seeing as input a 784-dim Tensor of pixel values for each image, and producing a Tensor of length 10 (our number of classes) that indicates the class scores for an input image. This particular example u...
import torch.nn as nn import torch.nn.functional as F # define the NN architecture class Net(nn.Module): def __init__(self): super(Net, self).__init__() # number of hidden nodes in each layer (512) hidden_1 = 512 hidden_2 = 512 # linear layer (784 -> hidden_1) self.f...
Net( (fc1): Linear(in_features=784, out_features=512, bias=True) (fc2): Linear(in_features=512, out_features=512, bias=True) (fc3): Linear(in_features=512, out_features=10, bias=True) (dropout): Dropout(p=0.2, inplace=False) )
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
Specify [Loss Function](http://pytorch.org/docs/stable/nn.htmlloss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)It's recommended that you use cross-entropy loss for classification. If you look at the documentation (linked above), you can see that PyTorch's cross entropy function applies a soft...
# specify loss function (categorical cross-entropy) criterion = nn.CrossEntropyLoss() # specify optimizer (stochastic gradient descent) and learning rate = 0.01 optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
--- Train the NetworkThe steps for training/learning from a batch of data are described in the comments below:1. Clear the gradients of all optimized variables2. Forward pass: compute predicted outputs by passing inputs to the model3. Calculate the loss4. Backward pass: compute gradient of the loss with respect to mode...
model.to('cuda') # number of epochs to train the model n_epochs = 50 # initialize tracker for minimum validation loss valid_loss_min = np.Inf # set initial "min" to infinity for epoch in range(n_epochs): # monitor training loss train_loss = 0.0 valid_loss = 0.0 ################### # train the...
Epoch: 1 Training Loss: 0.361179 Validation Loss: 0.291315 Validation loss decreased (inf --> 0.291315). Saving model ... Epoch: 2 Training Loss: 0.285200 Validation Loss: 0.239275 Validation loss decreased (0.291315 --> 0.239275). Saving model ... Epoch: 3 Training Loss: 0.236005 Validation Loss: 0.203692 Vali...
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
Load the Model with the Lowest Validation Loss
model.load_state_dict(torch.load('model.pt'))
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
--- Test the Trained NetworkFinally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as w...
model.to('cpu') # initialize lists to monitor test loss and accuracy test_loss = 0.0 class_correct = list(0. for i in range(10)) class_total = list(0. for i in range(10)) model.eval() # prep model for evaluation for data, target in test_loader: # forward pass: compute predicted outputs by passing inputs to the mo...
Test Loss: 0.074413 Test Accuracy of 0: 99% (971/980) Test Accuracy of 1: 98% (1123/1135) Test Accuracy of 2: 96% (1001/1032) Test Accuracy of 3: 97% (984/1010) Test Accuracy of 4: 97% (960/982) Test Accuracy of 5: 97% (870/892) Test Accuracy of 6: 97% (935/958) Test Accuracy of 7: 96% ...
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
Visualize Sample Test ResultsThis cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions.
# obtain one batch of test images dataiter = iter(test_loader) images, labels = dataiter.next() # get sample outputs output = model(images) # convert output probabilities to predicted class _, preds = torch.max(output, 1) # prep images for display images = images.numpy() # plot the images in the batch, along with pre...
_____no_output_____
MIT
convolutional-neural-networks/mnist-mlp/mnist_mlp_solution_with_validation.ipynb
ahmed-gharib89/ud_deep_learning_v2_pytorch
These notebook is used for initial training. Only necessary preprocessing is done, mainly categorical features encoding and Nans replacement. It should show the main problems with observations, show main model difficulties, and feaures importances. It should also guide the way of validation Therefore we have:- data pr...
import os import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Ridge from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_absolute_percentage_error from sklearn.model_selecti...
_____no_output_____
Apache-2.0
notebooks/initial_training.ipynb
smolendawid/ubaar-competition
Error analysisError analysis is a crucial step in working on a model. We can check the performance of the model according to specific features to find the weakest aspect of the model.
data['refs'] = results['refs'].values data['preds'] = results['preds'].values column = 'vehicleOption' for vehicle_type in data[column].unique(): tmp_data = data[data[column] == vehicle_type] title = f"{vehicle_type}, MPAE:{mean_absolute_percentage_error(tmp_data['refs'], tmp_data['preds']):.2f} #:{len(tmp_dat...
_____no_output_____
Apache-2.0
notebooks/initial_training.ipynb
smolendawid/ubaar-competition