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
If we invoke `sum3()` with strings instead, we get different invariants. Notably, we obtain the postcondition that the return value starts with the value of `a` – a universal postcondition if strings are used.
with InvariantTracker() as tracker: y = sum3('a', 'b', 'c') y = sum3('f', 'e', 'd') pretty_invariants(tracker.invariants('sum3'))
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
If we invoke `sum3()` with both strings and numbers (and zeros, too), there are no properties left that would hold across all calls. That's the price of flexibility.
with InvariantTracker() as tracker: y = sum3('a', 'b', 'c') y = sum3('c', 'b', 'a') y = sum3(-4, -5, -6) y = sum3(0, 0, 0) pretty_invariants(tracker.invariants('sum3'))
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Converting Mined Invariants to AnnotationsAs with types, above, we would like to have some functionality where we can add the mined invariants as annotations to existing functions. To this end, we introduce the `InvariantAnnotator` class, extending `InvariantTracker`. We start with a helper method. `params()` return...
class InvariantAnnotator(InvariantTracker): def params(self, function_name): arguments, return_value = self.calls(function_name)[0] return ", ".join(arg_name for (arg_name, arg_value) in arguments) with InvariantAnnotator() as annotator: y = my_sqrt(25.0) y = sum3(1, 2, 3) annotator.params('...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Now for the actual annotation. `preconditions()` returns the preconditions from the mined invariants (i.e., those propertes that do not depend on the return value) as a string with annotations:
class InvariantAnnotator(InvariantAnnotator): def preconditions(self, function_name): conditions = [] for inv in pretty_invariants(self.invariants(function_name)): if inv.find(RETURN_VALUE) >= 0: continue # Postcondition cond = "@precondition(lambda " + sel...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
`postconditions()` does the same for postconditions:
class InvariantAnnotator(InvariantAnnotator): def postconditions(self, function_name): conditions = [] for inv in pretty_invariants(self.invariants(function_name)): if inv.find(RETURN_VALUE) < 0: continue # Precondition cond = ("@postcondition(lambda " + ...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
With these, we can take a function and add both pre- and postconditions as annotations:
class InvariantAnnotator(InvariantAnnotator): def functions_with_invariants(self): functions = "" for function_name in self.invariants(): try: function = self.function_with_invariants(function_name) except KeyError: continue functio...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Here comes `function_with_invariants()` in all its glory:
with InvariantAnnotator() as annotator: y = my_sqrt(25.0) y = my_sqrt(0.01) y = sum3(1, 2, 3) print_content(annotator.function_with_invariants('my_sqrt'), '.py')
@precondition(lambda x: isinstance(x, float)) @precondition(lambda x: x != 0) @precondition(lambda x: x > 0) @precondition(lamb...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Quite a lot of invariants, is it? Further below (and in the exercises), we will discuss on how to focus on the most relevant properties. Some ExamplesHere's another example. `list_length()` recursively computes the length of a Python function. Let us see whether we can mine its invariants:
def list_length(L): if L == []: length = 0 else: length = 1 + list_length(L[1:]) return length with InvariantAnnotator() as annotator: length = list_length([1, 2, 3]) print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda L: L != 0) @precondition(lambda L: isinstance(L, list)) @postcondition(lambda return_value, L: isinstance(return_value, int[...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Almost all these properties (except for the very first) are relevant. Of course, the reason the invariants are so neat is that the return value is equal to `len(L)` is that `X == len(Y)` is part of the list of properties to be checked. The next example is a very simple function:
def sum2(a, b): return a + b with InvariantAnnotator() as annotator: sum2(31, 45) sum2(0, 0) sum2(-1, -5)
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The invariants all capture the relationship between `a`, `b`, and the return value as `return_value == a + b` in all its variations.
print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda a, b: isinstance(a, int)) @precondition(lambda a, b: isinstance(b, int)) @postcondition(lambda return_value, a, b: a == return_val...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
If we have a function without return value, the return value is `None` and we can only mine preconditions. (Well, we get a "postcondition" that the return value is non-zero, which holds for `None`).
def print_sum(a, b): print(a + b) with InvariantAnnotator() as annotator: print_sum(31, 45) print_sum(0, 0) print_sum(-1, -5) print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda a, b: isinstance(a, int)) @precondition(lambda a, b: isinstance(b, int)) @postcondition(lambda return_value, a, b: return_value !=...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Checking SpecificationsA function with invariants, as above, can be fed into the Python interpreter, such that all pre- and postconditions are checked. We create a function `my_sqrt_annotated()` which includes all the invariants mined above.
with InvariantAnnotator() as annotator: y = my_sqrt(25.0) y = my_sqrt(0.01) my_sqrt_def = annotator.functions_with_invariants() my_sqrt_def = my_sqrt_def.replace('my_sqrt', 'my_sqrt_annotated') print_content(my_sqrt_def, '.py') exec(my_sqrt_def)
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The "annotated" version checks against invalid arguments – or more precisely, against arguments with properties that have not been observed yet:
with ExpectError(): my_sqrt_annotated(-1.0)
Traceback (most recent call last): File "<ipython-input-170-c3c5c372ccd1>", line 2, in <module> my_sqrt_annotated(-1.0) File "<ipython-input-100-39ada1fd0b7e>", line 8, in wrapper retval = func(*args, **kwargs) # call original function or method File "<ipython-input-100-39ada1fd0b7e>", line 8, in wrapper ...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
This is in contrast to the original version, which just hangs on negative values:
with ExpectTimeout(1): my_sqrt(-1.0)
Traceback (most recent call last): File "<ipython-input-171-afc7add26ad6>", line 2, in <module> my_sqrt(-1.0) File "<ipython-input-5-47185ad159a1>", line 7, in my_sqrt guess = (approx + x / approx) / 2 File "<ipython-input-5-47185ad159a1>", line 7, in my_sqrt guess = (approx + x / approx) / 2 File "...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
If we make changes to the function definition such that the properties of the return value change, such _regressions_ are caught as violations of the postconditions. Let us illustrate this by simply inverting the result, and return $-2$ as square root of 4.
my_sqrt_def = my_sqrt_def.replace('my_sqrt_annotated', 'my_sqrt_negative') my_sqrt_def = my_sqrt_def.replace('return approx', 'return -approx') print_content(my_sqrt_def, '.py') exec(my_sqrt_def)
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Technically speaking, $-2$ _is_ a square root of 4, since $(-2)^2 = 4$ holds. Yet, such a change may be unexpected by callers of `my_sqrt()`, and hence, this would be caught with the first call:
with ExpectError(): my_sqrt_negative(2.0)
Traceback (most recent call last): File "<ipython-input-175-c80e4295dbf8>", line 2, in <module> my_sqrt_negative(2.0) File "<ipython-input-100-39ada1fd0b7e>", line 8, in wrapper retval = func(*args, **kwargs) # call original function or method File "<ipython-input-100-39ada1fd0b7e>", line 8, in wrapper ...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
We see how pre- and postconditions, as well as types, can serve as *oracles* during testing. In particular, once we have mined them for a set of functions, we can check them again and again with test generators – especially after code changes. The more checks we have, and the more specific they are, the more likely i...
def sum2(a, b): return a + b with InvariantAnnotator() as annotator: y = sum2(2, 2) print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda a, b: a != 0) @precondition(lambda a, b: a <= b) @precondition(lambda a, b: a == b) @precondition(lambda a, b: a > 0) @...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The mined precondition `a == b`, for instance, only holds for the single call observed; the same holds for the mined postcondition `return_value == a * b`. Yet, `sum2()` can obviously be successfully called with other values that do not satisfy these conditions. To get out of this trap, we have to _learn from more and...
with InvariantAnnotator() as annotator: length = sum2(1, 2) length = sum2(-1, -2) length = sum2(0, 0) print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda a, b: isinstance(a, int)) @precondition(lambda a, b: isinstance(b, int)) @postcondition(lambda return_value, a, b: a == return_val...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
But where to we get such diverse runs from? This is the job of generating software tests. A simple grammar for calls of `sum2()` will easily resolve the problem.
from GrammarFuzzer import GrammarFuzzer # minor dependency from Grammars import is_valid_grammar, crange, convert_ebnf_grammar # minor dependency SUM2_EBNF_GRAMMAR = { "<start>": ["<sum2>"], "<sum2>": ["sum2(<int>, <int>)"], "<int>": ["<_int>"], "<_int>": ["(-)?<leaddigit><digit>*", "0"], "<leaddi...
@precondition(lambda a, b: a != 0) @precondition(lambda a, b: isinstance(a, int)) @precondition(lambda a, b: isinstance(b, int)) [30;0...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
But then, writing tests (or a test driver) just to derive a set of pre- and postconditions may possibly be too much effort – in particular, since tests can easily be derived from given pre- and postconditions in the first place. Hence, it would be wiser to first specify invariants and then let test generators or progr...
def sum2(a, b): return a + b with TypeAnnotator() as type_annotator: sum2(1, 2) sum2(-4, -5) sum2(0, 0)
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The `typed_functions()` method will return a representation of `sum2()` annotated with types observed during execution.
print(type_annotator.typed_functions())
def sum2(a: int, b: int) ->int: return a + b
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The invariant annotator works in a similar fashion:
with InvariantAnnotator() as inv_annotator: sum2(1, 2) sum2(-4, -5) sum2(0, 0)
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The `functions_with_invariants()` method will return a representation of `sum2()` annotated with inferred pre- and postconditions that all hold for the observed values.
print(inv_annotator.functions_with_invariants())
@precondition(lambda a, b: isinstance(a, int)) @precondition(lambda a, b: isinstance(b, int)) @postcondition(lambda return_value, a, b: a == return_value - b) @postcondition(lambda return_value, a, b: b == return_value - a) @postcondition(lambda return_value, a, b: isinstance(return_value, int)) @postcondition(lambda r...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Such type specifications and invariants can be helpful as _oracles_ (to detect deviations from a given set of runs) as well as for all kinds of _symbolic code analyses_. The chapter gives details on how to customize the properties checked for. Lessons Learned* Type annotations and explicit invariants allow for _check...
from typing import Union, Optional def my_sqrt_with_union_type(x: Union[int, float]) -> float: ...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Extend the `TypeAnnotator` such that it supports union types for arguments and return values. Use `Optional[X]` as a shorthand for `Union[X, None]`. **Solution.** Left to the reader. Hint: extend `type_string()`. Exercise 2: Types for Local VariablesIn Python, one cannot only annotate arguments with types, but actual...
def my_sqrt_with_local_types(x: Union[int, float]) -> float: """Computes the square root of x, using the Newton-Raphson method""" approx: Optional[float] = None guess: float = x / 2 while approx != guess: approx: float = guess guess: float = (approx + x / approx) / 2 return approx
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Extend the `TypeAnnotator` such that it also annotates local variables with types. Search the function AST for assignments, determine the type of the assigned value, and make it an annotation on the left hand side. **Solution.** Left to the reader. Exercise 3: Verbose Invariant CheckersOur implementation of invariant...
@precondition(lambda s: len(s) > 0) def remove_first_char(s): return s[1:] with ExpectError(): remove_first_char('')
Traceback (most recent call last): File "<ipython-input-193-dda18930f6db>", line 2, in <module> remove_first_char('') File "<ipython-input-100-39ada1fd0b7e>", line 6, in wrapper assert precondition(*args, **kwargs), "Precondition violated" AssertionError: Precondition violated (expected)
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The following implementation adds an optional `doc` keyword argument which is printed if the invariant is violated:
def condition(precondition=None, postcondition=None, doc='Unknown'): def decorator(func): @functools.wraps(func) # preserves name, docstring, etc def wrapper(*args, **kwargs): if precondition is not None: assert precondition(*args, **kwargs), "Precondition violated: " + doc ...
Traceback (most recent call last): File "<ipython-input-196-dda18930f6db>", line 2, in <module> remove_first_char('') File "<ipython-input-194-683ee268305f>", line 6, in wrapper assert precondition(*args, **kwargs), "Precondition violated: " + doc AssertionError: Precondition violated: len(s) > 0 (expected)...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Extend `InvariantAnnotator` such that it includes the conditions in the generated pre- and postconditions. **Solution.** Here's a simple solution:
class InvariantAnnotator(InvariantAnnotator): def preconditions(self, function_name): conditions = [] for inv in pretty_invariants(self.invariants(function_name)): if inv.find(RETURN_VALUE) >= 0: continue # Postcondition cond = "@precondition(lambda " + self.para...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
The resulting annotations are harder to read, but easier to diagnose:
with InvariantAnnotator() as annotator: y = sum2(2, 2) print_content(annotator.functions_with_invariants(), '.py')
@precondition(lambda a, b: a != 0, doc='a != 0') @precondition(lambda a, b: a <= b, doc='a <= b') @precondition(la...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
As an alternative, one may be able to use `inspect.getsource()` on the lambda expression or unparse it. This is left to the reader. Exercise 4: Save Initial ValuesIf the value of an argument changes during function execution, this can easily confuse our implementation: The values are tracked at the beginning of the f...
class EmbeddedInvariantAnnotator(InvariantTracker): def functions_with_invariants_ast(self, function_name=None): if function_name is None: return annotate_functions_with_invariants(self.invariants()) return annotate_function_with_invariants(function_name, self.invariants(functio...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Part 2: Preconditions
class PreconditionTransformer(ast.NodeTransformer): def __init__(self, invariants): self.invariants = invariants super().__init__() def preconditions(self): preconditions = [] for (prop, var_names) in self.invariants: assertion = "assert " + instantiate_prop(...
def sum3(a, b, c): assert isinstance(c, int), 'violated precondition' assert isinstance(b, int), 'violated precondi...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Part 3: PostconditionsWe make a few simplifying assumptions: * Variables do not change during execution.* There is a single `return` statement at the end of the function.
class EmbeddedInvariantTransformer(PreconditionTransformer): def postconditions(self): postconditions = [] for (prop, var_names) in self.invariants: assertion = "assert " + instantiate_prop(prop, var_names) + ', "violated postcondition"' assertion_ast = ast.parse(assertion) ...
_____no_output_____
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Here's the full definition with included assertions:
print_content(my_sqrt_def, '.py') exec(my_sqrt_def.replace('my_sqrt', 'my_sqrt_annotated')) with ExpectError(): my_sqrt_annotated(-1)
Traceback (most recent call last): File "<ipython-input-214-bf1ed929743a>", line 2, in <module> my_sqrt_annotated(-1) File "<string>", line 3, in my_sqrt_annotated AssertionError: violated precondition (expected)
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Here come some more examples:
with EmbeddedInvariantAnnotator() as annotator: y = sum3(3, 4, 5) y = sum3(-3, -4, -5) y = sum3(0, 0, 0) print_content(annotator.functions_with_invariants(), '.py') with EmbeddedInvariantAnnotator() as annotator: length = list_length([1, 2, 3]) print_content(annotator.functions_with_invariants(), '.py'...
def print_sum(a, b): assert a <= b, 'violated precondition' assert b > 0, 'violated precondition' assert b != 0...
MIT
docs/notebooks/DynamicInvariants.ipynb
abhilashgupta/fuzzingbook
Maclaurin series for $\sin(x)$ is:\begin{align}\sin(x)&= \sum_{k=0}^{\infty} \frac{ (-1)^k }{ (2k+1)! } x^{2k+1} \\&= x - \frac{1}{3!} x^3 + \frac{1}{5!} x^5 - \frac{1}{7!} x^7 + \frac{1}{9!} x^9 - \frac{1}{11!} x^{11} +\ldots \\%%% &= x \left( 1 - \frac{1}{2.3} x^2 \left( 1 - \frac{1}{4.5} x^2 \left( 1 - \frac{1}{6.7}...
# Significance of each term to leading term k, eps = numpy.arange(1,30,2), numpy.finfo(float).eps n = (k+1)/2 print('epsilon = %.2e'%eps, "= 2**%i"%int(math.log(eps)/math.log(2))) plt.semilogy(n, eps * (1+0*n), 'k--', label=r'$\epsilon$' ) plt.semilogy(n, (numpy.pi-eps)**(k-1) / scipy.special.factorial(k), '.-', label=...
epsilon = 2.22e-16 = 2**-52
MIT
Calculation of sin(x).ipynb
adcroft/intrinsics
\begin{align}\sin(x)&\approx x - \frac{1}{3!} x^3 + \frac{1}{5!} x^5 - \frac{1}{7!} x^7 + \frac{1}{9!} x^9 - \frac{1}{11!} x^{11} +\ldots \\&= x \left( 1 - \frac{1}{2.3} x^2 \left( 1 - \frac{1}{4.5} x^2 \left( 1 - \frac{1}{6.7} x^2 \left(1 - \frac{1}{8.9} x^2 \left( 1 - \frac{1}{10.11} x^{2} \left( \ldots \right) \righ...
# Coefficients in series print(' t',' k','%26s'%'(2k+1)!','%22s'%'1/(2k+1)!','1/c[t]','%21s'%'c[t]') for t in range(1,17): k=2*t-1 print('%2i'%t, '%2i'%k, '%26i'%math.factorial(k), '%.16e'%(1./math.factorial(k)),'%5i'%(2*t*(2*t+1)),'%.16e'%(1./(2*t*(2*t+1))))
t k (2k+1)! 1/(2k+1)! 1/c[t] c[t] 1 1 1 1.0000000000000000e+00 6 1.6666666666666666e-01 2 3 6 1.6666666666666666e-01 20 5.0000000000000003e-02 3 5 120 8.3333333333333332e-03 42 2.3...
MIT
Calculation of sin(x).ipynb
adcroft/intrinsics
\begin{align}\sin(x)&\approx x - \frac{1}{3!} x^3 + \frac{1}{5!} x^5 - \frac{1}{7!} x^7 + \frac{1}{9!} x^9 - \frac{1}{11!} x^{11} +\ldots \\&= x \left( 1 - \frac{1}{2.3} x^2 \right) + \frac{1}{5!} x^5 \left( 1 - \frac{1}{6.7} x^2 \right) + \frac{1}{9!} x^9 \left( 1 - \frac{1}{10.11} x^2 \right) + \ldots \\&= \sum_{...
# Coefficients in paired series print(' l','4l+1','%26s'%'a[l]=(4l+1)!','%22s'%'1/a[l]',' b[l]','%22s'%'1/b[l]') for l in range(0,7,1): print('%2i'%l, '%4i'%(4*l+1), '%26i'%math.factorial(4*l+1), '%.16e'%(1./math.factorial(4*l+1)), '%5i'%((4*l+2)*(4*l+3)),'%.16e'%(1./((4*l+2)*(4*l+3)))) def sin_map_x( x )...
_____no_output_____
MIT
Calculation of sin(x).ipynb
adcroft/intrinsics
Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1: Predicting Boston Housing PricesWelcome to the first project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to succ...
# Import libraries necessary for this project import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.cross_validation import ShuffleSplit # Pretty display for notebooks %matplotlib inline # Load the Boston housing dataset data = pd.read_csv('housing.csv') prices = data['MDEV'] f...
Boston housing dataset has 489 data points with 4 variables each.
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Data ExplorationIn this first section of this project, you will make a cursory investigation about the Boston housing data and provide your observations. Familiarizing yourself with the data through an explorative process is a fundamental practice to help you better understand and justify your results.Since the main g...
# TODO: Minimum price of the data minimum_price = np.min(prices) # TODO: Maximum price of the data maximum_price = np.max(prices) # TODO: Mean price of the data mean_price = np.mean(prices) # TODO: Median price of the data median_price = np.median(prices) # TODO: Standard deviation of prices of the data std_price =...
Statistics for Boston housing dataset: Minimum price: $105,000.00 Maximum price: $1,024,800.00 Mean price: $454,342.94 Median price $438,900.00 Standard deviation of prices: $165,171.13
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Question 1 - Feature ObservationAs a reminder, we are using three features from the Boston housing dataset: `'RM'`, `'LSTAT'`, and `'PTRATIO'`. For each data point (neighborhood):- `'RM'` is the average number of rooms among homes in the neighborhood.- `'LSTAT'` is the percentage of all Boston homeowners who have a gr...
# TODO: Import 'r2_score' from sklearn.metrics import r2_score def performance_metric(y_true, y_predict): """ Calculates and returns the performance score between true and predicted values based on the metric chosen. """ # TODO: Calculate the performance score between 'y_true' and 'y_predict' ...
_____no_output_____
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Question 2 - Goodness of FitAssume that a dataset contains five data points and a model made the following predictions for the target variable:| True Value | Prediction || :-------------: | :--------: || 3.0 | 2.5 || -0.5 | 0.0 || 2.0 | 2.1 || 7.0 | 7.8 || 4.2 | 5.3 |*Would you consider this model to have successfully...
# Calculate the performance of this model score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3]) print "Model has a coefficient of determination, R^2, of {:.3f}.".format(score)
Model has a coefficient of determination, R^2, of 0.923.
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
**Answer:** The R^2 is 0.923 which is closed to 1 so i think can show the relationship well. Implementation: Shuffle and Split DataYour next implementation requires that you take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is also shuffled into a random order wh...
# TODO: Import 'train_test_split' from sklearn.cross_validation import train_test_split # TODO: Shuffle and split the data into training and testing subsets X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.8, random_state=20) # Success print "Training and testing split was successful."
Training and testing split was successful.
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Question 3 - Training and Testing*What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm?* **Hint:** What could go wrong with not having a way to test your model? **Answer: **In my opinion split dataset can let you know whether your model can fit other data...
# Produce learning curves for varying training set sizes and maximum depths vs.ModelLearning(features, prices)
_____no_output_____
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Question 4 - Learning the Data*Choose one of the graphs above and state the maximum depth for the model. What happens to the score of the training curve as more training points are added? What about the testing curve? Would having more training points benefit the model?* **Hint:** Are the learning curves converging t...
vs.ModelComplexity(X_train, y_train)
_____no_output_____
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Question 5 - Bias-Variance Tradeoff*When the model is trained with a maximum depth of 1, does the model suffer from high bias or from high variance? How about when the model is trained with a maximum depth of 10? What visual cues in the graph justify your conclusions?* **Hint:** How do you know when a model is suffer...
# TODO: Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV' from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import make_scorer from sklearn.grid_search import GridSearchCV def fit_model(X, y): """ Performs grid search over the 'max_depth' parameter for a decision tree regr...
_____no_output_____
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
Making PredictionsOnce a model has been trained on a given set of data, it can now be used to make predictions on new sets of input data. In the case of a *decision tree regressor*, the model has learned *what the best questions to ask about the input data are*, and can respond with a prediction for the **target varia...
# Fit the training data to the model using grid search reg = fit_model(X_train, y_train) # Produce the value for 'max_depth' print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth'])
Parameter 'max_depth' is 3 for the optimal model.
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
**Answer: **After so many times trying i get the correct answer!How happy am i!!!OK,then come to the question,when max_depth equals to 3 it is the optimal model.In question 6 i think it's 5,and it shows that man's intuition is not reliable. Question 10 - Predicting Selling PricesImagine that you were a real estate age...
# Produce a matrix for client data client_data = [[5, 34, 15], # Client 1 [4, 55, 22], # Client 2 [8, 7, 12]] # Client 3 # Show predictions for i, price in enumerate(reg.predict(client_data)): print "Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price)
Predicted selling price for Client 1's home: $252,787.50 Predicted selling price for Client 2's home: $252,787.50 Predicted selling price for Client 3's home: $971,600.00
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
**Answer: **I will recommend each client sell their house at 252,787.5USD and 252,787.5USD and 971,600USD.As we concluded in Data Exploration that the more RM it has,the less LSTAT,PTRATIO it has,the more valuable it will be. SensitivityAn optimal model is not necessarily a robust model. Sometimes, a model is either t...
vs.PredictTrials(features, prices, fit_model, client_data)
Trial 1: $324,240.00 Trial 2: $324,450.00 Trial 3: $346,500.00 Trial 4: $420,622.22 Trial 5: $302,400.00 Trial 6: $411,931.58 Trial 7: $344,750.00 Trial 8: $407,232.00 Trial 9: $352,315.38 Trial 10: $316,890.00 Range in prices: $118,222.22
Apache-2.0
Udacity/boston/boston_housing.ipynb
Vayne-Lover/Machine-Learning
**定义各阶矩阵的RI大小**
RI_dict = {1: 0, 2: 0, 3: 0.58, 4: 0.90, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45}
_____no_output_____
MIT
python业务代码/AHP层次分析法/AHP.ipynb
RobinYaoWenbin/Python-CommonCode
**定义计算出一个判断矩阵的一致性指标以及最大特征根的归一化特征向量的函数。**输入:np.array格式的一个二维矩阵,该二维矩阵的含义是判断矩阵。输出:若没有通过一致性检验,则输出提示信息:没有通过一致性检验。若通过一致性检验,则输出提示信息,并返回归一化的特征向量。
# 出入判断矩阵,判断矩阵需要是numpy格式的,若通过一致性检验则返回最大特征根的特征向量,若不通过,则输出提示。 def get_w(array): row = array.shape[0] # 计算出阶数 a_axis_0_sum = array.sum(axis=0) # print(a_axis_0_sum) b = array / a_axis_0_sum # 新的矩阵b # print(b) b_axis_0_sum = b.sum(axis=0) b_axis_1_sum = b.sum(axis=1) # 每一行的特征向量 # print(b_a...
_____no_output_____
MIT
python业务代码/AHP层次分析法/AHP.ipynb
RobinYaoWenbin/Python-CommonCode
**对输入数据进行格式判断,若正确则调用get_w(array)进行计算,若不正确则输出提示信息。**
def main(array): # 判断下判断矩阵array的数据类型,并给出提示,若格式正确,则可继续下一步计算一致性和特征向量 if type(array) is np.ndarray: return get_w(array) else: print('请输入numpy对象')
_____no_output_____
MIT
python业务代码/AHP层次分析法/AHP.ipynb
RobinYaoWenbin/Python-CommonCode
**对博文中选干部的例子进行了计算,具体说明我都做了注释。博文连接:https://www.cnblogs.com/yhll/p/9967726.html**感谢大佬!
if __name__ == '__main__': # 定义判断矩阵 e = np.array([[1, 2, 7, 5, 5], [1 / 2, 1, 4, 3, 3], [1 / 7, 1 / 4, 1, 1 / 2, 1 / 3], \ [1 / 5, 1 / 3, 2, 1, 1], [1 / 5, 1 / 3, 3, 1, 1]]) # 准则层对目标层判断矩阵 a = np.array([[1, 1 / 3, 1 / 8], [3, 1, 1 / 3], [8, 3, 1]]) # 对B1的判断矩阵 b = np.array([[1, 2, 5], ...
0.016 满足一致性 权重特征向量为: [0.47439499 0.26228108 0.0544921 0.09853357 0.11029827] 0.001 满足一致性 权重特征向量为: [0.08199023 0.23644689 0.68156288] 0.005 满足一致性 权重特征向量为: [0.59488796 0.27661064 0.1285014 ] 0.0 满足一致性 权重特征向量为: [0.42857143 0.42857143 0.14285714] 0.008 满足一致性 权重特征向量为: [0.63274854 0.19239766 0.1748538 ] 0.046 满足一致性 权重特征向量为:...
MIT
python业务代码/AHP层次分析法/AHP.ipynb
RobinYaoWenbin/Python-CommonCode
From Binomial Distribution to Poisson DistributionThe binomial distribution is given by,$$Bin(k|n,\theta) \triangleq \frac{n!}{k!(n-k)!}\theta^k(1-\theta)^{n-k} $$The poisson distribution is given by,$$Poi(k|\lambda) \triangleq e^{-\lambda}\frac{\lambda^k}{k!} $$Proof:Consider $\theta=\frac{\lambda}{n}$,\begin{align*}...
s = np.random.poisson(1, 1000000) count, bins, ignored = plt.hist(s, density=True, rwidth=0.8) s = np.random.poisson(10, 1000000) count, bins, ignored = plt.hist(s,50, density=True)
_____no_output_____
MIT
Machine Learning A Probabilistic Perspective/2Probability/F2.6/2.6poissonPlotDemo.ipynb
zcemycl/ProbabilisticPerspectiveMachineLearning
From Figure 2.4, we have sampled from the binomial distribution. \If $n=100$, given $\lambda=1$, then $\theta = 1/100$.
s = np.random.randint(1,101,[100,1000000]) s = np.where(s>1,0,s) countbinary = np.count_nonzero(s,axis=0) plt.hist(countbinary)
_____no_output_____
MIT
Machine Learning A Probabilistic Perspective/2Probability/F2.6/2.6poissonPlotDemo.ipynb
zcemycl/ProbabilisticPerspectiveMachineLearning
GIven $\lambda=10$, then $\theta=1/10$
s = np.random.randint(1,11,[100,1000000]) s = np.where(s>1,0,s) countbinary = np.count_nonzero(s,axis=0) plt.hist(countbinary)
_____no_output_____
MIT
Machine Learning A Probabilistic Perspective/2Probability/F2.6/2.6poissonPlotDemo.ipynb
zcemycl/ProbabilisticPerspectiveMachineLearning
![terrainbento logo](../../../../media/terrainbento_logo.png) terrainbento model BasicVs steady-state solution This model shows example usage of the BasicVs model from the TerrainBento package.The BasicVs model implements modifies Basic to use variable source area runoff using the ""effective area"" approach:$\frac{\pa...
from terrainbento import BasicVs # import required modules import os import numpy as np import matplotlib.pyplot as plt import matplotlib from landlab import imshow_grid from landlab.io.netcdf import write_netcdf np.random.seed(4897) #Ignore warnings import warnings warnings.filterwarnings('ignore') # create the ...
_____no_output_____
CC-BY-4.0
lessons/landlab/landlab-terrainbento/coupled_process_elements/model_basicVs_steady_solution.ipynb
josh-wolpert/espin
Machine Translation: Word-based SMT using IBM1 In this notebook we'll be looking at the IBM Model 1 word alignment method. This will be used to demonstrate the process of training, using expectation maximisation, over a toy dataset. Note that this dataset and presentation closely follows JM2 Chapter 25. The optimised ...
from collections import defaultdict import itertools
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Our dataset will consist of two very short sentence pairs.
bitext = [] bitext.append(("green house".split(), "casa verde".split())) bitext.append(("the house".split(), "la casa".split()))
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Based on the vocabulary items in Spanish and English, we initialise our translation table, *t*, to a uniform distribution. That is, for each word type in English, we set all translations in Spanish to have 1/3.
t0 = defaultdict(dict) for en_type in "the green house".split(): for es_type in "la casa verde".split(): t0[en_type][es_type] = 1.0 / 3 t0
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Now for the algorithm itself. Although we tend to merge the expectation and maximisation steps (to save storing big data structures for the expected counts), here we'll do the two separately for clarity. Also, following JM: - we won't apply the optimisation for IBM1 which allows us to deal with each position *j* indepe...
def expectation_step(bitext, translation_probs): expectations = [] for E, F in bitext: I = len(E) J = len(F) # store the unnormalised alignment probabilities align = [] # track the sum of unnormalised alignment probabilities Z = 0 for A in itertools.produc...
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Let's try running this and see what the expected alignments are
e0 = expectation_step(bitext, t0) e0
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
We can also view this graphically. You need to have Graphviz - Graph Visualization Software installed and the path to its bin folder e.g. C:\Program Files (x86)\Graphviz2.38\bin added to PATH.
from IPython.display import SVG, display from nltk.translate import AlignedSent, Alignment def display_expect(expectations): stuff = [] for A, E, F, prob in expectations: if prob > 0.01: stuff.append('Prob = %.4f' % prob) asent = AlignedSent(F, E, Alignment(list(enumerate(A)))) ...
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Note the uniform probabilities for each option (is this a surprise, given our initialisation?) Next up we need to learn the model parameters *t* from these expectations. This is simply a matter of counting occurrences of translation pairs, weighted by their probability.
def maximization_step(expectations): counts = defaultdict(dict) for A, E, F, prob in expectations: for j, aj in enumerate(A): counts[E[aj]].setdefault(F[j], 0.0) counts[E[aj]][F[j]] += prob translations = defaultdict(dict) for e, fcounts in counts.items(): td...
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Now we can test this over our expectations. Do you expect this to be uniform like *t0*?
t1 = maximization_step(e0) t1
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
With working E and M steps, we can now iterate!
t = t0 for step in range(10): e = expectation_step(bitext, t) t = maximization_step(e) t display_expect(e)
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Great, we've learned sensible translations as we hoped. Try viewing the expectations using *display_expect*, and vary the number of iterations. What happens to the learned parameters? Speeding things up Recall that the E-step above uses a naive enumeration over all possible alignments, which is going to be woefully ...
def fast_em(bitext, translation_probs): # E-step, computing counts as we go counts = defaultdict(dict) for E, F in bitext: I = len(E) J = len(F) # each j can be considered independently of the others for j in range(J): # get the translation probabilities (unnormal...
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
We can test that the parameters learned in each step match what we computed before. What's the time complexity of this algorithm?
t1p = fast_em(bitext, t0) t1p t2p = fast_em(bitext, t1) t2p
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Alignment models in NLTK NLTK has a range of translation tools, including the IBM models 1 - 5. These are implemented in their full glory, including the null alignment, and complex optimisation algorithms for models 3 and up. Note that model 4 requires a clustering of the vocabulary, see the [documentation](http://www...
from nltk.translate import IBMModel3 bt = [AlignedSent(E,F) for E,F in bitext] m = IBMModel3(bt, 5) m.translation_table
_____no_output_____
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
NLTK also includes a small section of the Europarl corpus (about 20K sentence pairs). You might want to apply the alignment models to this larger dataset, although be aware that you will first need to do sentence alignment to discard any sentences that aren't aligned 1:1, e.g., using [nltk.translate.gale_church](http:...
import nltk nltk.download('europarl_raw') from nltk.corpus.europarl_raw import english, spanish print(english.sents()[0]) print(spanish.sents()[0])
[nltk_data] Downloading package europarl_raw to [nltk_data] /Users/tcohn/nltk_data... [nltk_data] Package europarl_raw is already up-to-date! ['Resumption', 'of', 'the', 'session', 'I', 'declare', 'resumed', 'the', 'session', 'of', 'the', 'European', 'Parliament', 'adjourned', 'on', 'Friday', '17', 'December', '1...
BSD-4-Clause-UC
notebooks/WSTA_N21_machine_translation.ipynb
trevorcohn/comp90042
Bernstein-Vazirani Algorithm In this section, we first introduce the Bernstein-Vazirani problem, and classical and quantum algorithms to solve it. We then implement the quantum algorithm using Qiskit, and run on a simulator and device. Contents1. [Introduction](introduction) - [Bernstein-Vazirani Problem](bvproblem)...
# initialization import matplotlib.pyplot as plt %matplotlib inline import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.tools.visualizat...
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
We first set the number of qubits used in the experiment, and the hidden integer $s$ to be found by the algorithm. The hidden integer $s$ determines the circuit for the quantum oracle.
nQubits = 2 # number of physical qubits used to represent s s = 3 # the hidden integer # make sure that a can be represented with nqubits s = s % 2**(nQubits)
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
We then use Qiskit to program the Bernstein-Vazirani algorithm.
# Creating registers # qubits for querying the oracle and finding the hidden integer qr = QuantumRegister(nQubits) # bits for recording the measurement on qr cr = ClassicalRegister(nQubits) bvCircuit = QuantumCircuit(qr, cr) barriers = True # Apply Hadamard gates before querying the oracle for i in range(nQubits): ...
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
3a. Experiment with Simulators We can run the above circuit on the simulator.
# use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(bvCircuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
We can see that the result of the measurement is the binary representation of the hidden integer $3$ $(11)$. 3b. Experiment with Real Devices We can run the circuit on the real device as below.
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and not ...
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
As we can see, most of the results are $11$. The other results are due to errors in the quantum computation. 4. Problems 1. The above [implementation](implementation) of Bernstein-Vazirani is for a secret bit string of $s = 11$. Modify the implementation for a secret string os $s = 1011$. Are the results what you exp...
import qiskit qiskit.__qiskit_version__
_____no_output_____
Apache-2.0
content/ch-algorithms/bernstein-vazirani.ipynb
ibmamnt/qiskit-textbook
Human Activity Recognition (97.98 %) The above accuracy achieved is better than the research paper itself which was based on LSTM but my work includes ANN on the same dataset. **Original approach using LSTM -Testing Accuracy: 91.652% , Precision: 91.762% , Recall: 91.652% , f1_score: 91.643%** **My appro...
import numpy as np import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt print(os.listdir("../input")) df = pd.read_csv("../input/train.csv") test = pd.read_csv("../input/test.csv") df.T print(df.Activity.unique()) print("----------------------------------------") print(df.Activity.value...
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
Now some visualizations for feature distribution in space.
sns.set(rc={'figure.figsize':(15,7)}) colours = ["maroon","coral","darkorchid","goldenrod","purple","darkgreen","darkviolet","saddlebrown","aqua","olive"] index = -1 for i in df.columns[0:10]: index = index + 1 fig = sns.kdeplot(df[i] , shade=True, color=colours[index]) plt.xlabel("Features") plt.ylabel("Value"...
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
**Feature Scaling** **Pre-processing and data preparation to feed data into Artificial Neural Network.**
from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaler.fit(df.iloc[:,0:562]) mat_train = scaler.transform(df.iloc[:,0:562]) print(mat_train) scaler = MinMaxScaler() scaler.fit(test.iloc[:,0:562]) mat_test = scaler.transform(test.iloc[:,0:562]) print(mat_test) temp = [] for i in df.Activity: i...
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
**Though it is a 562 feature vector which is large enough and might cause overfitting while training.** **Also gone for feature selection using extra tree classifier and l1 selection , but the results were slightly better with all features only when I tune the hyperparameters of the model to its almost utmost level whi...
print(X_train.shape , y_train.shape) print(X_test.shape , y_test.shape)
(7352, 562) (7352, 6) (2947, 562) (2947, 6)
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
**Taking necessary callbacks of checkpointing and learning rate reducer.**
filepath="HAR_weights.hdf5" from keras.callbacks import ReduceLROnPlateau , ModelCheckpoint lr_reduce = ReduceLROnPlateau(monitor='val_acc', factor=0.1, epsilon=0.0001, patience=1, verbose=1) checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max') from keras.models import ...
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
**The below model architecture is the best I could come up with after repeated tuning and changes in network architecture.** **At last, the BatchNormalization layer did some good to slightly boost the accuracy.** **Taken special care of learning rate and batch_size to which the model is very sensitive and have to repe...
model = Sequential() model.add(Dense(64, input_dim=X_train.shape[1] , activation='relu')) model.add(Dense(64, activation='relu')) model.add(BatchNormalization()) model.add(Dense(128, activation='relu')) model.add(Dense(196, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(6, activation='sigm...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_109 (Dense) (None, 64) 36032 ________________________________________________________...
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
Finally, the best model was checkpointed and got a validation loss of 0.0562 and a validation accuracy of 97.98% or ~98%.
history = model.fit(X_train, y_train , epochs=22 , batch_size = 256 , validation_data=(X_test, y_test) , callbacks=[checkpoint,lr_reduce]) from pylab import rcParams rcParams['figure.figsize'] = 10, 4 plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy'...
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
The confusion matrix is plotted to get better insight of model performance using mlxted to refrain from extra code via scikit. The model performance is evident from the diagonal concentration of the values.**
CM = confusion_matrix(y_true, pred) from mlxtend.plotting import plot_confusion_matrix fig, ax = plot_confusion_matrix(conf_mat=CM , figsize=(10, 5)) plt.show()
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
Precision - 95% , Recall - 94% and f1-score of 94%.
from sklearn.metrics import classification_report , accuracy_score print(classification_report(y_true, pred))
precision recall f1-score support 0 0.99 0.91 0.95 496 1 0.98 0.89 0.93 471 2 0.82 0.99 0.90 420 3 0.94 0.90 0.92 491 4 0.94 0.95 0.94 532 ...
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
**Exporting predictions.**
d = { "Index":np.arange(2947) , "Activity":pred } final = pd.DataFrame(d) final.to_csv( 'human_activity_predictions.csv' , index = False)
_____no_output_____
Apache-2.0
Human Activity Recognition (97.98 %).ipynb
parisa1/Human-Activity-Recognition-with-Neural-Network-using-Gyroscopic-and-Accelerometer-variables
Supplemental InformationThis notebook is intended to serve as a supplement to the manuscript "High-throughput workflows for determining adsorption energies on solid surfaces." It outlines basic use of the code and workflow software that has been developed for processing surface slabs and placing adsorbates according ...
# Import statements from pymatgen import Structure, Lattice, MPRester, Molecule from pymatgen.analysis.adsorption import * from pymatgen.core.surface import generate_all_slabs from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from matplotlib import pyplot as plt %matplotlib inline # Note that you must provide y...
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
We create a simple fcc structure, generate it's distinct slabs, and select the slab with a miller index of (1, 1, 1).
fcc_ni = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.5), ["Ni"], [[0, 0, 0]]) slabs = generate_all_slabs(fcc_ni, max_index=1, min_slab_size=8.0, min_vacuum_size=10.0) ni_111 = [slab for slab in slabs if slab.miller_index==(1,1,1)][0]
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
We make an instance of the AdsorbateSiteFinder and use it to find the relevant adsorption sites.
asf_ni_111 = AdsorbateSiteFinder(ni_111) ads_sites = asf_ni_111.find_adsorption_sites() print(ads_sites) assert len(ads_sites) == 4
{'ontop': [array([1.23743687, 0.71443451, 9.0725408 ])], 'bridge': [array([-0.61871843, 1.78608627, 9.0725408 ])], 'hollow': [array([4.27067681e-16, 7.39702921e-16, 9.07254080e+00]), array([8.80455477e-16, 1.42886902e+00, 9.07254080e+00])], 'all': [array([1.23743687, 0.71443451, 9.0725408 ]), array([-0.61871843, 1.7...
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
We visualize the sites using a tool from pymatgen.
fig = plt.figure() ax = fig.add_subplot(111) plot_slab(ni_111, ax, adsorption_sites=True)
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Use the `AdsorbateSiteFinder.generate_adsorption_structures` method to generate structures of adsorbates.
fig = plt.figure() ax = fig.add_subplot(111) adsorbate = Molecule("H", [[0, 0, 0]]) ads_structs = asf_ni_111.generate_adsorption_structures(adsorbate, repeat=[1, 1, 1]) plot_slab(ads_structs[0], ax, adsorption_sites=False, decay=0.09)
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Example 2: AdsorbateSiteFinder for various surfacesIn this example, the AdsorbateSiteFinder is used to find adsorption sites on different structures and miller indices.
fig = plt.figure() axes = [fig.add_subplot(2, 3, i) for i in range(1, 7)] mats = {"mp-23":(1, 0, 0), # FCC Ni "mp-2":(1, 1, 0), # FCC Au "mp-13":(1, 1, 0), # BCC Fe "mp-33":(0, 0, 1), # HCP Ru "mp-30": (2, 1, 1), "mp-5229":(1, 0, 0), } # Cubic SrTiO3 #"mp-21...
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Example 3: Generating a workflow from atomateIn this example, we demonstrate how MatMethods may be used to generate a full workflow for the determination of DFT-energies from which adsorption energies may be calculated. Note that this requires a working instance of [FireWorks](https://pythonhosted.org/FireWorks/inde...
from fireworks import LaunchPad lpad = LaunchPad() lpad.reset('', require_password=False)
2018-07-24 09:56:31,982 INFO Performing db tune-up 2018-07-24 09:56:31,995 INFO LaunchPad was RESET.
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Import the necessary workflow-generating function from atomate:
from atomate.vasp.workflows.base.adsorption import get_wf_surface, get_wf_surface_all_slabs
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Adsorption configurations take the form of a dictionary with the miller index as a string key and a list of pymatgen Molecule instances as the values.
co = Molecule("CO", [[0, 0, 0], [0, 0, 1.23]]) h = Molecule("H", [[0, 0, 0]])
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Workflows are generated using the a slab a list of molecules.
struct = mpr.get_structure_by_material_id("mp-23") # fcc Ni struct = SpacegroupAnalyzer(struct).get_conventional_standard_structure() slabs = generate_all_slabs(struct, 1, 5.0, 2.0, center_slab=True) slab_dict = {slab.miller_index:slab for slab in slabs} ni_slab_111 = slab_dict[(1, 1, 1)] wf = get_wf_surface([ni_slab_...
2018-07-24 09:56:33,057 INFO Added a workflow. id_map: {-9: 1, -8: 2, -7: 3, -6: 4, -5: 5, -4: 6, -3: 7, -2: 8, -1: 9}
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
The workflow may be inspected as below. Note that there are 9 optimization tasks correponding the slab, and 4 distinct adsorption configurations for each of the 2 adsorbates. Details on running FireWorks, including [singleshot launching](https://pythonhosted.org/FireWorks/worker_tutorial.htmllaunch-a-rocket-on-a-work...
lpad.get_wf_summary_dict(1)
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Note also that running FireWorks via atomate may require system specific tuning (e. g. for VASP parameters). More information is available in the [atomate documentation](http://pythonhosted.org/atomate/). Example 4 - Screening of oxygen evolution electrocatalysts on binary oxides This final example is intended to dem...
from pymatgen.core.periodic_table import * from pymatgen.core.surface import get_symmetrically_distinct_miller_indices import tqdm lpad.reset('', require_password=False)
2018-07-24 09:56:33,079 INFO Performing db tune-up 2018-07-24 09:56:33,088 INFO LaunchPad was RESET.
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
For oxygen evolution, a common metric for the catalytic activity of a given catalyst is the theoretical overpotential corresponding to the mechanism that proceeds through OH\*, O\*, and OOH\*. So we can define our adsorbates:
OH = Molecule("OH", [[0, 0, 0], [-0.793, 0.384, 0.422]]) O = Molecule("O", [[0, 0, 0]]) OOH = Molecule("OOH", [[0, 0, 0], [-1.067, -0.403, 0.796], [-0.696, -0.272, 1.706]]) adsorbates = [OH, O, OOH]
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
Then we can retrieve the structures using the MP rest interface, and write a simple for loop which creates all of the workflows corresponding to every slab and every adsorption site for each material. The code below will take ~15 minutes. This could be parallelized to be more efficient, but is not for simplicity in t...
elements = [Element.from_Z(i) for i in range(1, 103)] trans_metals = [el for el in elements if el.is_transition_metal] # tqdm adds a progress bar so we can see the progress of the for loop for metal in tqdm.tqdm_notebook(trans_metals): # Get relatively stable structures with small unit cells data = mpr.get_data...
_____no_output_____
BSD-3-Clause
notebooks/2018-07-24-2018-Adsorption on solid surfaces.ipynb
utf/matgenb
PinSage MovieRecommendationThis notebook has code that can be used to use PinSage for an "implicit recommender task." In this case, the data are Movie Rating, so you are data are users and ratings for some set of movies. The data are split into a training and test set, and the goal is to learn representations of user...
!pip install dgl-cu101 --upgrade !python -m pip install dask[dataframe] --upgrade !pip install madgrad !wget -c http://files.grouplens.org/datasets/movielens/ml-1m.zip !unzip ml-1m.zip !rm ml-1m.zip !wget -c https://www.dropbox.com/s/4blru88qafx1i4l/ml_25m_tmdb_plot_paraphrase-distilroberta-base-v1.pth.tar !wget --quie...
_____no_output_____
MIT
2021/pinsage_movielens_robert_output_disabled.ipynb
harvard-visionlab/psy1406