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 |
|---|---|---|---|---|---|
Basic Functions**Hint** Be sure to `return` values from your function definitions. The assert statements will call your function(s) for you. | # Run this cell in order to generate some numbers to use in our functions after this.
import random
positive_even_number = random.randrange(2, 101, 2)
negative_even_number = random.randrange(-100, -1, 2)
positive_odd_number = random.randrange(1, 100, 2)
negative_odd_number = random.randrange(-101, 0, 2)
print("We... | Exercise 42 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Functions working with stringsIf you need some guidance working with the next few problems, recommend reading through [this example code](https://gist.github.com/ryanorsinger/f758599c886549e7615ec43488ae514c) | # Exercise 43
# Write a function definition named is_vowel that takes in value and returns True if the value is a, e, i, o, u in upper or lower case.
def is_vowel(x):
return x.lower() in "aeiou"
assert is_vowel("a") == True
assert is_vowel("U") == True
assert is_vowel("banana") == False
assert is_vowel("Q") == Fals... | Exercise 49 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Accessing List Elements | # Exercise 50
# Write a function definition named first that takes in sequence and returns the first value of that sequence.
def first(x):
return x[0]
assert first("ubuntu") == "u"
assert first([1, 2, 3]) == 1
assert first(["python", "is", "awesome"]) == "python"
print("Exercise 50 is correct.")
# Exercise 51
# Wri... | Exercise 59 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Functions to describe data | # Exercise 60
# Write a function definition named sum_all that takes in sequence of numbers and returns all the numbers added together.
def sum_all(numbers):
return sum(numbers)
assert sum_all([1, 2, 3, 4]) == 10
assert sum_all([3, 3, 3]) == 9
assert sum_all([0, 5, 6]) == 11
print("Exercise 60 is correct.")
# Exe... | Exercise 64 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Applying functions to lists | # Run this cell in order to use the following list of numbers for the next exercises
numbers = [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]
# Exercise 65
# Write a function definition named get_highest_number that takes in sequence of numbers and returns the largest number.
def get_highest_number(x):
return max(x)
assert g... | Exercise 82 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Working with sets**Hint** Take a look at the `set` function in Python, the `set` data type, and built-in `set` methods. | # Example set function usage
print(set("kiwi"))
print(set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]))
# Exercise 83
# Write a function definition named get_unique_values that takes in a list and returns a set with only the unique values from that list.
def get_unique_values(x):
return set(x)
assert get_unique_values(["ant", "... | Exercise 86 is correct.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Working with Dictionaries | # Run this cell in order to have these two dictionary variables defined.
tukey_paper = {
"title": "The Future of Data Analysis",
"author": "John W. Tukey",
"link": "https://projecteuclid.org/euclid.aoms/1177704711",
"year_published": 1962
}
thomas_paper = {
"title": "A mathematical model of glutath... | Exercise 90 is complete.
| MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Working with Lists of Dictionaries**Hint** If you need an example of lists of dictionaries, see [https://gist.github.com/ryanorsinger/fce8154028a924c1073eac24c7c3f409](https://gist.github.com/ryanorsinger/fce8154028a924c1073eac24c7c3f409) | # Run this cell in order to have some setup data for the next exercises
books = [
{
"title": "Genetic Algorithms and Machine Learning for Programmers",
"price": 36.99,
"author": "Frances Buontempo"
},
{
"title": "The Visual Display of Quantitative Information",
"price... | _____no_output_____ | MIT | 101_exercises.ipynb | barbmarques/python-exercises |
Data Analysis for Inverse Observation Data Assimilation of Kolmogorov FlowThis notebook analyzes the paper's data and reproduces the plots. | import os
os.environ["CUDA_VISIBLE_DEVICES"]="0" # system integration faster on GPU
import warnings
warnings.filterwarnings('ignore')
from functools import partial
import numpy as np
import scipy
import jax
import jax.numpy as jnp
from jax import random, jit
import argparse
from datetime import datetime
import xarray a... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Copy data from Google cloudThis requires [gsutil](https://cloud.google.com/storage/docs/gsutil). | !gsutil cp -r gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/ /tmp | Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_baselineinit_hybridopt.nc...
Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-results/kolmogorov_baselineinit_obsopt.nc...
Copying gs://gresearch/jax-cfd/projects/invobs-data-assimilation/invobs-da-re... | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Load data | path = '/tmp/invobs-da-results'
filenames = [
'kolmogorov_baselineinit_obsopt.nc',
'kolmogorov_baselineinit_hybridopt.nc',
'kolmogorov_invobsinit_obsopt.nc',
'kolmogorov_invobsinit_hybridopt.nc',
]
retained_variables = [
'f_vals',
'eval_vals',
'X0_ground_truth',
'X0_opt',
'X0_init',... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Instantiate dynamical system | kolmogorov_flow = KolmogorovFlow(
grid_size=ds.attrs['grid_size'],
num_inner_steps=ds.attrs['num_inner_steps'],
viscosity=ds.attrs['viscosity'],
observe_every=ds.attrs['observe_every'],
wavenumber=ds.attrs['peak_wavenumber'],
) | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Data assimilation initialization samplesComparison of initialization schemes. | da_init = xr.concat(
[
ds['X0_init'].sel(init=['invobs', 'baseline']),
ds['X0_ground_truth'].sel(init='baseline'),
],
dim='init',
) \
.assign_coords(init=['invobs', 'baseline', 'ground_truth']) \
.sel(opt_space='observation')
vort_init = compute_vorticity(da_init, kolmogorov_flow.grid)
#... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Optimization curvesPlot value of observation space objective function during optimization normalized by the first-step value of the observation space objective function. | sns.set(font_scale=1.5)
sns.set_style('white')
to_plot = ds['eval_vals'].sel(n=[6, 9])
to_plot_relative_mean = (
to_plot / to_plot.sel(opt_step=0, opt_space='observation')
)
to_plot_relative_mean = to_plot_relative_mean.sel(
init=['invobs', 'baseline'],
opt_space=['hybrid', 'observation'],
)
df_opt_curves... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Forecast quality | X0_da = ds[['X0_ground_truth', 'X0_init', 'X0_opt']].to_array('data_type') \
.assign_coords({'data_type': ['gt', 'init', 'opt']})
X_da = integrate_kolmogorov_xr(kolmogorov_flow, X0_da, 20)
vorticity = compute_vorticity(X_da, kolmogorov_flow.grid)
relative_scale = 14533 # average L1 norm over independent samples
l1_erro... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Summary statsCompare forecast performance on the first forecast state relative to baseline init and optimization method. | summary_stats = l1_error.sel(data_type='opt', t=11).mean(dim='n') / l1_error.sel(data_type='opt', t=11, init='baseline', opt_space='observation').mean(dim='n')
print(
summary_stats.sel(opt_space='observation', init='baseline').values,
summary_stats.sel(opt_space='hybrid', init='baseline').values,
summary_st... | 1.0 0.8789517 0.19961545 0.22848208
| Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Significance test between trajectoriesPerform a Z-test to evaluate significance level between optimization methods for the two initialization schemes. Inverse observation initialization | time_step = 11 # beginning of forecast window
num_samples = l1_error.sizes['n']
l1_error_inv = l1_error.sel(init='invobs', data_type='opt')
diff_l1_error = (
l1_error_inv.sel(opt_space='observation')
- l1_error_inv.sel(opt_space='hybrid')
)
m = diff_l1_error.sel(t=time_step).mean(dim='n')
s = diff_l1_error.sel(t... | Z-value -5.658017083581407
p-value 7.656594807321588e-09
| Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Baseline initialization | time_step = 11 # beginning of forecast window
num_samples = l1_error.sizes['n']
l1_error_inv = l1_error.sel(init='baseline', data_type='opt')
diff_l1_error = (
l1_error_inv.sel(opt_space='observation')
- l1_error_inv.sel(opt_space='hybrid')
)
m = diff_l1_error.sel(t=time_step).mean(dim='n')
s = diff_l1_error.sel... | Z-value 6.508546551414507
p-value 3.7940697809822585e-11
| Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Assimilated trajectories | gt = vorticity.sel(data_type='gt', opt_space='observation', init='baseline')
baseline = vorticity.sel(
data_type='opt',
opt_space='observation',
init='baseline',
)
invobs = vorticity.sel(data_type='opt', opt_space='hybrid', init='invobs')
forecast_comparison = (
xr.concat([invobs, baseline, gt], dim=... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Summary figure | sns.set(font_scale=3)
plt.rc('font', **{'family': 'Times New Roman'})
g = forecast_comparison.isel(n=1, t=11) \
.plot.imshow(
x='x',
y='y',
col='da_method',
size=5,
add_colorbar=False,
cmap=sns.cm.icefire,
vmin=-8,
vmax=8,
)
col_labels = ['ground truth', 'proposed', 'baseline'] ... | _____no_output_____ | Apache-2.0 | Analysis_KolmogorovFlow.ipynb | googleinterns/invobs-data-assimilation |
Индивидуальное задание: Изобразить эмблему Бэтмена для его призыва к спасению города от противников бабы Нины Задача: Существуют хейтеры бабы Нины и перед Бэтменом была поставлена задача спасти её от них Решение: V = 1 Бэтмен, p хейтеры = 100 штук P = pV P = 100 * 1 = 100 штук Q = V : P Q = 1 : 100= 0,01 H Ответ: Q =... | %load_ext autoreload
%autoreload 2
import jupyter_lesson
%matplotlib inline
jupyter_lesson.plot_batman()
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Path = mpath.Path
path_data = [
(Path.MOVETO, (1.58, -2.57)),
(Path.CURVE4,... | _____no_output_____ | MIT | ind.ipynb | A1zak/cross6 |
Definitions of Python:1. Primitive types, basic operations2. Composed types: lists, tuples, dictionaries3. Everything is an object4. Control structures: blocks, branching, loops Primitive typesThe basic types build into Python include:* `int`: variable length integers,* `float`: double precision floating point number... | ##### -1234567890 # an integer
2.0 # a floating point number
6.02e23 # a floating point number with scientific notation
complex(1, 5) # a complex
True or False # the two possible boolean values
'This is a string'
"It's another string"
print("""Triple quotes (also with '''), allow strings to break ove... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Primary operations| Symbol | Task Performed ||----|---|| + | Addition || - | Subtraction || * | Multiplication || / | Floating point division || // | Floor division || % | Modulus or rest || ** or pow(a, b) | Power || abs(a) | absolute value || round(a) | Banker's rounding |Some examples: | #divisions
print(3 / 2, 3 // 2)
print(3. / 2, 3. // 2)
#operation with complex
print((5. + 4.0j - 3.5) * 2.1) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Relational Operators | Symbol | Task Performed ||---|---|| == | True if it is equal || != | True if not equal to || < | less than || > | greater than || <= | less than or equal to || >= | greater than or equal to || || not | negate a `bool` value || is | True if both are the same || and | True if both are True || ... | # grouping comparison
print(1 >= 0.5 and (2 > 3 or 5 % 2 == 1)) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Strings* Basic operations on strings: `+` or `*`* Formating using `%s` or `.format`* Slicing using the [start: stop: step] | s = "a is equal to"
a = 5
print(s+str(a))
print(s, a)
#/!\
s+a
# String muliplied by int works !
"*--*" * 5 | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
String formating | # %s will convert anything to an int. %i, %d, %f works like in C or spec.
print("a is equal to %s" % a)
print("%s %05i" % (s,a))
#new style formating
'{2} {1} {2} {0}'.format('a','b','c')
'{0:.2} {1:.1%}'.format(0.3698, 9.6/100) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
String access and slicing* Access a single element with `[index]`* Extract a sub part of a string using `[start:stop:step]` → **slicing**.* Works the same on lists, tuples, arrays, ... | letters = "abcdefghijklmnopqrstuvwxyz"
print(letters)
len(letters)
# remind you that python is 0-based indexing
print(letters[0], letters[4], letters[25])
#/!\
letters[56]
#slicing from beginging
letters[0:4]
#from the end
letters[-5:]
# two by two using a stepsize of 2
letters[::2]
# inverted using a stepsize of -1:
l... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Useful string methods```pythonmy_str = 'toto'```* `len(my_str)`: returns the length of the string* `my_str.find('to')`, `my_str.index('to')`: returns the starting index. Find returns ``-1`` if not found, index fails.* `my_str.replace(str1, str2)`: replaces `str1` with `str2` in string* `my_str.split()` splits the stri... | print([1, 2, 3])
digits = list(range(10))
print(digits)
print(list(letters))
print(digits + list(letters))
#but
digits + letters
# lists can contain anything
a = ['my string', True, 5+7]
print(len(a))
a.append(3.141592)
print(a, len(a))
list(range(5, 12, 2)) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Useful methods for lists```pythonlst = [1, 2, 3, 'a', 'b', 'c']```* `lst.append(a)`: adds *a* at the end of lst* `lst.insert(idx, a)`: inserts one element at a given index* `lst.index(a)`: finds first index containing a value* `lst.count(a)`: counts the number of occurences of *a* in the list * `lst.pop(idx)`: removes... | lst = ['eggs', 'sausages']
print(len(lst))
lst.append("spam")
print(lst, len(lst))
lst.insert(0, "spam")
print(lst)
print(lst.index("spam"), lst.index("sausages"))
#but:
lst.index(5)
lst.count("spam")
print(lst.pop(), lst.pop(2))
# lists are mutable:
print(lst)
lst[0] = 1
print(lst)
lst.remove("eggs")
print(lst)
# but ... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Tuple* Tuples are defined by the `tuple(iter)` or by a ``,`` separated list in parenthesis ``()`` * Tuples are like lists, but not mutable ! | mytuple = ('spam', 'eggs', 5, 3.141592, 'sausages')
print(mytuple[0], mytuple[-1])
# /!\ tuples are not mutable
mytuple[3] = "ham"
# Single element tuple: mind the comma
t = 5,
print(t) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
List comprehension and generatorsVery *pythonic* and convenient way of creating lists or tuples from an iterator: ` [ f(i) for i in iterable if condition(i) ]`The content of the `[]` is called a *generator*.A *generator* generates elements on demand, which is *fast* and *low-memory usage*. It is the base of the asynch... | [2*x+1 for x in range(5)]
tuple(x**(1/2.) for x in range(5))
(x**(1/2.) for x in range(5))
[x for x in range(10) if x**3 - 15*x**2 + 71*x == 105]
print([l.upper() for l in letters]) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Mapping Types: DictionariesDictionaries associate a key to a value using curly braces `{key1: value1, key2:value2}`: * Keys must be *hashable*, i.e. any object that is unmutable, also known as *hash table* in other languages* Dictionaries were not ordered before Python 3.7 (`OrderedDict` are) | help(dict)
periodic_table = {
"H": 1,
"He": 2,
"Li": 3,
"Be": 4,
"B": 5,
"C": 6,
"N": 7,
"O": 8,
"F": 9,
"Ne": 10,
}
print(periodic_table)
print(periodic_table['He'])
print(periodic_table.keys())
print(periodic_table.values())
#search for a key in a dict:
'F' in periodic_tab... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
In Python, everything is object* In Python everything is object (inherits from ``object``)* Names are just labels, references, attached to an object* Memory is freed when the number of references drops to 0- `dir(obj)`: lists the attributes of an object- `help(obj)`: prints the help of the object- `type(obj)`: gets th... | a = object()
print(dir(a))
print(type(True), type(a), id(a))
b = 5
c = 5
print(id(b), id(c), id(b) == id(c), b is c)
# == vs `is`
a, b = 5, 5.0
print(a == b)
print(type(a), type(b))
# int are unique
print(a, bin(a), a is 0b0101)
print(a == 5.0, a is 5.0)
print(1 is None, None is None) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Warning: in Python, everything is object ... | list1 = [3, 2, 1]
print("list1=", list1)
list2 = list1
list2[1] = 10
print("list2=", list2)
# Did you expect ?
print("list1= ", list1) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
      | print("indeed: id(list1)=", id(list1)," and id(list2):", id(list2), "so list2 is list1:", list2 is list1)
#How to avoid this: make copies of mutable objects:
list1 = [3, 2, 1]
print("list1=", list1)
list3 = list1 [:] # copy the content !
list3[1] = 10
print("As expected: list3= ", list3)
print("And now: list1= ", l... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
**Warning:** This is very error prone when manipulating **any** mutable objects. | # Generic solution: use the copy module
import copy
list3 = copy.copy(list1) # same, more explicit
print(id(list1) == id(list3)) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Control structures: blocks Code structurePython uses a colon `:` at the end of the line and 4 white-spaces indentationto establish code block structure.Many other programming languages use braces { }, not python. ``` Block 1 ... Header making new block: Block 2 ... Header making new block... | a = -1
b = 2
c = 1
q2 = b * b - 4.0 * a * c
print("Determinant is ", q2)
import math
if q2 < 0:
print("No real solution")
elif q2 > 0:
x1 = (-b + math.sqrt(q2)) / (2.0 * a)
x2 = (-b - math.sqrt(q2)) / (2.0 * a)
print("Two solutions %.2f and %.2f" % (x1, x2))
else:
x = -b / (2.0 * a)
print("One s... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
For loop- iterate over a sequence (list, tuple, char in string, keys in dict, any iterator)- no indexes, uses directly the object in the sequence- when the index is really needed, use `enumerate`- One can use multiple sequences in parallel using `zip` | ingredients = ["spam", "eggs", "ham", "spam", "sausages"]
for food in ingredients:
print("I like %s" % food)
for idx, food in enumerate(ingredients[-1::-1]):
print("%s is number %d in my top 5 of foods" % (food, len(ingredients)- idx))
subjects = ["Roses", "Violets", "Sugar"]
verbs = ["are", "are", "is"]
adjec... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
While loop- Iterate while a condition is fulfilled- Make sure the condition becomes unfulfilled, else it could result in infinite loops ... | a, b = 175, 3650
stop = False
possible_divisor = max(a, b) // 2
while possible_divisor >= 1 and not stop:
if a % possible_divisor == 0 and b % possible_divisor == 0:
print("Found greatest common divisor: %d" % possible_divisor)
stop = True
possible_divisor = possible_divisor - 1
while True:
... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Useful commands in loops- `continue`: go directly to the next iteration of the most inner loop- `break`: quit the most inner loop- `pass`: a block cannot be empty; ``pass`` is a command that does nothing- `else`: block executed after the normal exit of the loop. | for i in range(10):
if not i % 7 == 0:
print("%d is *not* a multiple of 7" % i)
continue
print("%d is a multiple of 7" % i)
n = 112
# divide n by 2 until this does no longer return an integer
while True:
if n % 2 != 0:
print("%d is not a multiple of 2" % n)
break
print("%... | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
Exercise: Fibonacci series- Fibonacci: - Each element is the sum of the previous two elements - The first two elements are 0 and 1- Calculate all elements in this series up to 1000, put them in a list, then print the list.``[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]``prepend the cell with... | # One possible solution
res = [0, 1]
next_el = 1
while next_el < 1000:
res.append(next_el)
next_el = res[-2] + res[-1]
print(res) | _____no_output_____ | CC-BY-4.0 | python/python/1_Definitions.ipynb | t20100/silx-training |
RNNs for Timeseries Analysis Timeseries Bruno Gonçalves www.data4sci.com @bgoncalves, @data4sci | import pandas as pd
from pandas.plotting import autocorrelation_plot
import numpy as np
np.random.seed(123)
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import watermark
%load_ext watermark
%matplotlib inline
%watermark -n -v -m -p numpy,matplotlib,pandas,sklearn | Wed Sep 25 2019
CPython 3.7.3
IPython 6.2.1
numpy 1.16.2
matplotlib 3.1.0
pandas 0.24.2
sklearn 0.20.3
compiler : Clang 4.0.1 (tags/RELEASE_401/final)
system : Darwin
release : 18.7.0
machine : x86_64
processor : i386
CPU cores : 8
interpreter: 64bit
| MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Load the datasetGDP data from the Federal Reserve Bank [website](https://fred.stlouisfed.org/series/GDP) | series = pd.read_csv('data/GDP.csv', header=0, parse_dates=[0], index_col=0)
plt.plot(series)
plt.xlabel('Date')
plt.ylabel('GDP (B$)');
plt.gcf().set_size_inches(11,8)
series['GDP'].pct_change().plot()
plt.gca().plot([series.index.min(), series.index.max()], [0, 0], 'r-')
plt.xlabel('Date')
plt.ylabel('GDP QoQ Growth'... | _____no_output_____ | MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Autocorrelation function | autocorrelation_plot(series, label='DJIA')
autocorrelation_plot(series.pct_change().dropna(), ax=plt.gca(), label='DoD')
plt.gcf().set_size_inches(11,8)
values = series.pct_change().dropna().values.reshape(-1, 1)
X = values[:-1]
y = values[1:]
plt.plot(X.flatten(), y, '*')
plt.xlabel('x_t')
plt.ylabel('x_t+1')
lm = Lin... | _____no_output_____ | MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Fit comparison | plt.plot(series.index[2:], series.values[2:], )
plt.plot(series.index[2:], (1+y_pred).cumprod()*series.values[0])
plt.xlabel('Date')
plt.ylabel('GDP (B$)')
plt.gcf().set_size_inches(11, 8) | _____no_output_____ | MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Now without looking into the future | n_points = len(series)
train_points = int(2/3*n_points)+1
X_train = X[:train_points]
y_train = y[:train_points]
X_test = X[train_points:]
y_test = y[train_points:]
lm.fit(X_train, y_train)
y_train_pred = lm.predict(X_train)
y_test_pred = lm.predict(X_test)
plt.plot(series.index[:train_points], y_train, label='data')
pl... | _____no_output_____ | MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Comparison plot | plt.plot(series.index[:train_points], (1+y_train).cumprod()*series.values[0], label='train')
plt.plot(series.index[train_points+2:], (1+y_test).cumprod()*series.values[train_points], label='test')
plt.plot(series.index[:train_points], (1+y_train_pred).cumprod()*series.values[0], label='train_pred')
plt.plot(series.inde... | _____no_output_____ | MIT | Timeseries.ipynb | k-rajmani2k/RNN |
Parallel simulations using mpi4py | import os,sys
Nthread = 1
os.environ["OMP_NUM_THREADS"] = str(Nthread) # export OMP_NUM_THREADS=1
os.environ["OPENBLAS_NUM_THREADS"] = str(Nthread) # export OPENBLAS_NUM_THREADS=1
os.environ["MKL_NUM_THREADS"] = str(Nthread) # export MKL_NUM_THREADS=1
os.environ["VECLIB_MAXIMUM_THREADS"] = str(Nthread) # export VECLIB_... | _____no_output_____ | MIT | notebooks/parallel_simulations.ipynb | zhaonat/py-maxwell-fd3d |
Playing TextWorld generated games with OpenAI GymThis tutorial shows how to play a text-based adventure game **generated by TextWorld** using OpenAI's Gym API. Generate a new TextWorld game | !tw-make custom --world-size 2 --quest-length 3 --nb-objects 10 --output tw_games/game.ulx -f -v --seed 1234 | Global seed: 1234
Game generated: tw_games/game.ulx
Welcome to another fast paced game of TextWorld! Here is your task for today. First, it would be great if you could try to go east. With that accomplished, take the shoe that's in the attic. With the shoe, place the shoe on the shelf. Alright, thanks!
| MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Register the game with GymIn order to call to `gym.make`, we need to create a valid `env_id` for our game. | import textworld.gym
env_id = textworld.gym.register_game('tw_games/game.ulx') | _____no_output_____ | MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Make the gym environmentWith our `env_id` we are ready to use gym to start the new environment. | import gym
env = gym.make(env_id) | _____no_output_____ | MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Start the gameLike for other Gym environments, we start a new game by calling the `env.reset` method. It returns the initial observation text string as well as a dictionary for additional informations (more on that later). | obs, infos = env.reset()
print(obs) |
________ ________ __ __ ________
| \| \| \ | \| \
\$$$$$$$$| $$$$$$$$| $$ | $$ \$$$$$$$$
| $$ | $$__ \$$\/ $$ | $$
| $$ | $$ \ >$$ $$ ... | MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Interact with the gameThe `env.step` method is used to send text command to the game. This method returns the observation for the new state, the current game score, whether the game is done, and dictionary for additional informations (more on that later). | obs, score, done, infos = env.step("open box")
print(obs) | You have to unlock the Canadian style box with the Canadian style key first.
| MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Make a simple play loopWe now have everything we need in order to interactively play a text-based game. | try:
done = False
obs, _ = env.reset()
print(obs)
nb_moves = 0
while not done:
command = input("> ")
obs, score, done, _ = env.step(command)
print(obs)
nb_moves += 1
except KeyboardInterrupt:
pass # Press the stop button in the toolbar to quit the game.
print("... |
________ ________ __ __ ________
| \| \| \ | \| \
\$$$$$$$$| $$$$$$$$| $$ | $$ \$$$$$$$$
| $$ | $$__ \$$\/ $$ | $$
| $$ | $$ \ >$$ $$ ... | MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
Request additional information_*Only available for games generated with TextWorld._To ease the learning process of AI agents, TextWorld offers control over what information should be available alongside the game's narrative (i.e. the observation).Let's request the list of __admissible__ commands (i.e. commands that ar... | import textworld
request_infos = textworld.EnvInfos(admissible_commands=True, entities=True)
# Requesting additional information should be done when registering the game.
env_id = textworld.gym.register_game('tw_games/game.ulx', request_infos)
env = gym.make(env_id)
obs, infos = env.reset()
print("Entities: {}".forma... | Entities: ['safe', 'Canadian style box', 'shoe', 'cane', 'shelf', 'workbench', 'board', 'bowl', 'Canadian style key', 'book', 'fork', 'pair of pants', 'north', 'south', 'east', 'west']
Admissible commands:
drop Canadian style key
drop book
drop fork
examine Canadian style box
examine Canadian style key
exam... | MIT | notebooks/Playing TextWorld generated games with OpenAI Gym.ipynb | zhaozj89/TextWorld |
* Problem 2 - Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, f... | if __name__ == "__main__":
assert fibonacci(10) == 89
"""Let's start with the 10th fibonacci term"""
def fibonacci(n):
return 89
if __name__ == "__main__":
assert fibonacci(10) == 89
#assert fibonacci(9) == 55
def fibonacci(n):
if n == 9:
return 55
return 89
if __name__ == "__main__":
... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
But if I do this way, I probabilly having a problem to apply the fibonacci algorithm,so, let's begin with the ascending order | def fibonacci(n):
return 1
if __name__ == '__main__':
assert fibonacci(1) == 1
def fibonacci(n):
return 1
if __name__ == '__main__':
assert fibonacci(1) == 1
assert fibonacci(2) == 2
def fibonacci(n):
if n == 2:
return 2
return 1
if __name__ == '__main__':
assert fibonacci(1) ... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
What the code is doing is: n = (5 - 2) + (5 - 1).Therefore we must to apply a repetition. | def fibonacci(n):
a = 1
b = 2
c = 0
i = 0
if n > 2:
while i < n:
c = a + b
a = b
b = c
i = i + 1
return c
if n == 2:
return n
return 1
if __name__ == '__main__':
assert fibonacci(1) == 1
assert fibonacci(2) == 2
... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
* Now, I must to find the list (the second step)As I am using the TDD, I can do this without a problem. | def fibonacci(n):
a = 1
b = 2
c = 0
i = 2
if n > 2:
while i < n:
c = a + b
a = b
b = c
i = i + 1
return c
if n == 2:
return n
return 1
if __name__ == '__main__':
assert fibonacci(1) == 1
assert fibonacci(2) == 2
... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
The repetition of the first term occurs because I don't set what the function should to do if n < 2. | def fibonacci_list(l):
lista = []
i = 1
while i < l:
a = fibonacci(i)
lista.append(a)
i = i + 1
return lista
def fibonacci(n):
a = 1
b = 2
c = 0
i = 2
if n > 2:
while i < n:
c = a + b
a = b
b = c
i = i + ... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
Now, I must to apply the condition that I miss. To append in the list only the even terms. | def fibonacci_list(l):
lista = []
i = 1
while i < l:
a = fibonacci(i)
if a % 2 == 0:
lista.append(a)
i = i + 1
else:
i = i + 1
return lista
def fibonacci(n):
a = 1
b = 2
c = 0
i = 2
if n > 2:
while i < n:
... | _____no_output_____ | MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
Now, for the next step, I must to set a interval condition. In the statement, the condition is "the values not exced 4 milions". | def fibonacci_list_interval(m):
lista = []
i = 1
while True:
a = fibonacci(i)
if a > m:
print('The last term is: ' + str(a))
break
if a % 2 == 0:
lista.append(a)
i = i + 1
else:
i = i + 1
return lista
def fibon... | The last term is: 5702887
| MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
I don't know how can I make first a test in this case, but how the code was developed, I see no one problem to do this way. Whatever, the new function is just the previous function with same changes. To return the sum of even numbers of the fibonacci list, I must to do only this: | def fibonacci_list_interval(m):
lista = []
i = 1
while True:
a = fibonacci(i)
if a > m:
print('The last term is: ' + str(a))
break
if a % 2 == 0:
lista.append(a)
i = i + 1
else:
i = i + 1
return sum(lista)
def ... | The last term is: 5702887
| MIT | 2-Even Fibonacci numbers(right).ipynb | vss-py/TDD-ProjectEuler |
Chapter 3 - Regression Models Segment 2 - Multiple linear regression | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import scale
%matplotlib inline
rcParams['figure.figsize'] = 5, 4
import seaborn as sb
sb.set_style('whitegrid')
from collection... | _____no_output_____ | MIT | modules/module_12/part3/03_02_begin/03_02_begin.ipynb | ryanjmccall/sb_ml_eng_capstone |
(Multiple) linear regression on the enrollment data | address = 'C:/Users/Lillian/Desktop/ExerciseFiles/Data/enrollment_forecast.csv'
enroll = pd.read_csv(address)
enroll.columns = ['year', 'roll', 'unem', 'hgrad', 'inc']
enroll.head()
sb.pairplot(enroll)
print(enroll.corr())
enroll_data = enroll[['unem', 'hgrad']].values
enroll_target = enroll[['roll']].values
enroll_... | _____no_output_____ | MIT | modules/module_12/part3/03_02_begin/03_02_begin.ipynb | ryanjmccall/sb_ml_eng_capstone |
Checking for missing values | missing_values = X==np.NAN
X[missing_values == True]
LinReg = LinearRegression(normalize=True)
LinReg.fit(X, y)
print(LinReg.score(X, y)) | 0.8488812666133723
| MIT | modules/module_12/part3/03_02_begin/03_02_begin.ipynb | ryanjmccall/sb_ml_eng_capstone |
Discrete Models Task 1) Data Preparation Installing 'tslearn' - only run if not installed previously (if necessary, for more information see documentation of the package at https://tslearn.readthedocs.io/en/latest/index.html?highlight=install | ##!pip install tslearn | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Importing packages | import datetime
import pandas as pd
from pandas import Series
from pandas import DataFrame
from pandas import concat
import numpy as np
import time, datetime
import matplotlib.pyplot as plt
import sys
from tslearn.generators import random_walks
from tslearn.preprocessing import TimeSeriesScalerMeanVariance
from tslearn... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Reading the data, converting the time to timestamp and indexing the date to use it as a time series | #Data Paths
DATA_PATH = sys.path[0]+"\\data\\"
filename_train1="BATADAL_dataset03.csv"
filename_train2="BATADAL_dataset04.csv"
filename_test="BATADAL_test_dataset.csv"
#Reading the data
dftrain1 = pd.read_csv(DATA_PATH + filename_train1)
dftrain2 = pd.read_csv(DATA_PATH + filename_train2)
dftest = pd.read_csv(DATA_PAT... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Scaling the data to normal distribution with mean zero and standard deviation | #Obs: some values will be converted to float
dftrain1_original=dftrain1
dftrain2_original=dftrain2
dftest_original=dftest
#Dftrain1
dftrain1.iloc[:,range(0,31)]=preprocessing.scale(dftrain1.iloc[:,range(0,31)])
#Dftrain2
dftrain2.iloc[:,range(0,31)]=preprocessing.scale(dftrain2.iloc[:,range(0,31)])
#Dftest
dftest.iloc[... | C:\Users\pvbia\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by the scale function.
C:\Users\pvbia\Anaconda3\lib\site-packages\ipykernel_launcher.py:10: DataConversionWarning: Data with input dtype int64, float64 were al... | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Labeling the attacks on dftrain2 according to the information below For L_T713/09/2016 23 - 16/09/2016 00 |26/09/2016 11 - 27/09/2016 10 For F_PU10 and F_PU1126/09/2016 11 - 27/09/2016 10 For L_T109/10/2016 9 - 11/10/2016 20 |29/10/2016 19 - 02/11/2016 16 |14/12/2016 15 - 19/12/2016 04 For F_PU1 and F_PU229/10/2016 19... | #L_T7
dftrain2_L_T7=dftrain2.loc[:,[' L_T7',' ATT_FLAG']]
dftrain2_L_T7.loc[:,' ATT_FLAG']=0
dftrain2_L_T7.loc['2016-09-13 23':'2016-09-16 00',' ATT_FLAG']=1
dftrain2_L_T7.loc['2016-09-26 11':'2016-09-27 10',' ATT_FLAG']=1
#F_PU10 and F_PU11
dftrain2_F_PU10=dftrain2.loc[:,[' F_PU10',' ATT_FLAG']]
dftrain2_F_PU10.loc[:,... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Labling the attacks on dftest according to the batadal dataset | ###Labling zero in the test set for all anomalies
dftest[" ATT_FLAG"]=0
###Creating one dataset for each dimension
#Attack 1
dftest_L_T3=dftest.loc[:,['L_T3',' ATT_FLAG']]
dftest_P_U4=dftest.loc[:,['F_PU4', ' ATT_FLAG']]
dftest_P_U5=dftest.loc[:,['F_PU5', ' ATT_FLAG']]
#Attack 2
dftest_L_T2=dftest.loc[:,['L_T2', ' ATT_... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Labling all the attacks in one dataset to compute performance | dftest.loc['2017-01-16 09':'2017-01-19 06',' ATT_FLAG']=1
dftest.loc['2017-01-30 08':'2017-02-02 00',' ATT_FLAG']=1
dftest.loc['2017-02-09 03':'2017-02-10 09',' ATT_FLAG']=1
dftest.loc['2017-02-12 01':'2017-02-13 07',' ATT_FLAG']=1
dftest.loc['2017-02-24 05':'2017-02-28 08',' ATT_FLAG']=1
dftest.loc['2017-03-10 14':'20... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Adding the anomaly type column to be used in the detection | dftest["anomalytype"]=0 | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 1 | plt.plot(dftest_L_T3.loc['2017-01-16 09':'2017-01-19 06', 'L_T3'],color="red")
plt.plot(dftest_L_T3.loc['2017-01-12 09':'2017-01-16 09', 'L_T3'],color="blue")
plt.plot(dftest_L_T3.loc['2017-01-19 06':'2017-01-23 06', 'L_T3'],color="blue")
plt.plot(dftest_P_U4.loc['2017-01-16 09':'2017-01-19 06', 'F_PU4'],color="red")
... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 1 generated a contextual anomaly in L_T3 | dftest.loc['2017-01-16 09':'2017-01-19 06', 'anomalytype']="contextual" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 2 | plt.plot(dftest_L_T2.loc['2017-01-30 08':'2017-02-02 00', 'L_T2'],color="red")
plt.plot(dftest_L_T2.loc['2017-01-26 08':'2017-01-30 08', 'L_T2'],color="blue")
plt.plot(dftest_L_T2.loc['2017-02-02 00':'2017-02-06 00', 'L_T2'],color="blue") | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 2 generated a collective anomaly in L_T2 | dftest.loc['2017-01-30 08':'2017-02-02 00', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 3 | plt.plot(dftest_P_U3.loc['2017-02-09 02':'2017-02-10 09', 'F_PU3'],color="red")
plt.plot(dftest_P_U3.loc['2017-02-05 03':'2017-02-09 02', 'F_PU3'],color="blue")
plt.plot(dftest_P_U3.loc['2017-02-10 09':'2017-02-14 09', 'F_PU3'],color="blue")
| _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 3 generated a collective anomaly in F_PU3 | dftest.loc['2017-02-09 02':'2017-02-10 09', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 4 | plt.plot(dftest_P_U3.loc['2017-02-12 00':'2017-02-13 07', 'F_PU3'],color="red")
plt.plot(dftest_P_U3.loc['2017-02-08 01':'2017-02-12 00', 'F_PU3'],color="blue")
plt.plot(dftest_P_U3.loc['2017-02-13 07':'2017-02-17 07', 'F_PU3'],color="blue") | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 4 generated a collective anomaly in F_PU3 | dftest.loc['2017-02-12 00':'2017-02-13 07', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 5 | plt.plot(dftest_L_T2.loc['2017-02-24 05':'2017-02-28 08', 'L_T2'],color="red")
plt.plot(dftest_L_T2.loc['2017-02-20 05':'2017-02-24 05', 'L_T2'],color="blue")
plt.plot(dftest_L_T2.loc['2017-02-28 08':'2017-03-03 08', 'L_T2'],color="blue")
plt.plot(dftest_V2.loc['2017-02-24 05':'2017-02-28 08', 'F_V2'],color="red")
pl... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 5 generated a collective anomaly in L_T2, F_V2, P_J14 and P_J422 | dftest.loc['2017-02-24 05':'2017-02-28 08', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 6 | plt.plot(dftest_L_T7.loc['2017-03-10 14':'2017-03-13 21', 'L_T7'],color="red")
plt.plot(dftest_L_T7.loc['2017-03-06 14':'2017-03-10 14', 'L_T7'],color="blue")
plt.plot(dftest_L_T7.loc['2017-03-13 21':'2017-03-17 21', 'L_T7'],color="blue")
plt.plot(dftest_P_U10.loc['2017-03-10 14':'2017-03-13 21', 'F_PU10'],color="red"... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 6 generated collective anomalies | dftest.loc['2017-03-10 14':'2017-03-13 21', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Attack 7 | plt.plot(dftest_L_T4.loc['2017-03-25 20':'2017-03-27 01', 'L_T4'],color="red")
plt.plot(dftest_L_T4.loc['2017-03-21 20':'2017-03-25 20', 'L_T4'],color="blue")
plt.plot(dftest_L_T4.loc['2017-03-27 01':'2017-03-31 01', 'L_T4'],color="blue")
plt.plot(dftest_L_T6.loc['2017-03-25 20':'2017-03-27 01', 'L_T6'],color="red")
... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Thus attack 6 generated a collective anomaly in L_T4 and L_T6 | dftest.loc['2017-03-25 20':'2017-03-27 01', 'anomalytype']="collective" | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
2) Discretization Creating a dataset to test the sax | dataset_scale=dftrain1['L_T7'] | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Creating the Symbolic Aggregate Approximation (SAX) function and testing in the above mentioned dataset | ### Creting a function that creates the sax
def tosax(n_paa_segments,n_sax_symbols,dataset_scale):
#Creating the SAX using 'n_paa_segments' as number of segments and 'n_sax_symbols' as number of symbols
sax = SymbolicAggregateApproximation(n_segments=n_paa_segments, alphabet_size_avg=n_sax_symbols)
# Comput... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Plotting the scaled time series, PAA and SAX representations for the sake of validation of the code | #Plotting - only 100 first values to test the code isworking as expected
# Plotting the scaled data set
plt.subplot(2, 2, 2) # First, raw time series
plt.plot(dataset_scale.ravel()[0:300], "b-")
plt.title("Original Time Series")
#Plotting the SAX
plt.subplot(2, 2, 1) # Then SAX
plt.plot(sax_dataset_inv[0].ravel()[0... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
3) N-Grams Representations Creating a function that returns its n-gram representation. | #'a' will be used just to test the functions below.
a=sax_dataset_inv[0].ravel() | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
We need function(s) to convert numeric values generated from the sax to a string to perform N-grams as a it was a NLP problem. For this purpose two functions were created: the first just put all the values of a list in a string and the second convert numerical values of the sax to letters | # First function convert a list of numeric values to a string
def convert(list):
# Converting integer list to string list
s = [str(i) for i in list]
# Join list items using join()
res = ("".join(s))
return(res)
# Second function to convert a sax numeric representation into strings
def saxtostr... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Now to generate Ngrams we need a function that gather from the data the possible grams and their possible next values. | #Function that creates the Ngrams representation by creating a dictionary that has as keys the representations and as values
#the number elements generated after the n-gram
def tongrams(tokens,n):
#Creates a dictionary with the Ngrams representation and the next element (that is to be predicted by the ngrams)
D... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Now we create a Markov Chain that calculates the prior and the posterior given the dictionary generated by the previous function. | #Function that calcualte the likelihood given a ngram
def tomarkovchain(ngram):
#Create dictionary to be filled with the probability of conditional events (likelihood)
l_probs=dict()
#Create the dictionaries to be filled with the counting for each gram
c1=dict()
#Loop through keys to calculate the l... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Lastly, we create a function that loop through the dataframe and return the index that are below a certain threshold | def prediction(markovchain_model,n_sax_symbols,string_sax, threshold):
#Calculating number of ngrams used
n=len(random.choice(list(markovchain_model[0].keys())))
#Calculationg the number of times a observation should be reproduced so the data set has the same size as the original
#Creating the list to ... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
And a function that merge the predictions into the original dataframe considering the possible rounding differences that may lead to difference in length when creating SAX | def smartmerge(df,predictions):
df=pd.Series.to_frame(df)
if len(predictions)==len(df):
df.insert(1, "predictions", predictions)
df.reset_index(inplace=True)
if len(predictions)>len(df):
predictions=predictions[:-(len(predictions)-len(df))]
df.insert(1, "predictions... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
4) Predictions Attacks Using N-grams _In this subchapter we are going to try to predict the attacks on the training dataset 2_ Creating functions that aid the prediction Creating a function that make predicitons and calculate performance indicators. | def model_to_predict(trainset,testset,results,n_sax_symbols,n_paa_segments,n_grams,threshold):
###Generating the model for the train set###
#Sax
sax_train=tosax(n_paa_segments,n_sax_symbols,trainset).ravel()
#Sax to string
sax_string_train=saxtostring(sax_train)
#Ngrams
ngrams=tongrams(s... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Creating a function that plot the confusion matrix in a nice format! | def ploting_cm(cm):
#Plot
ax= plt.subplot()
sns.heatmap(cm, annot=True,fmt='g', ax = ax); #annot=True to annotate cells
# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['normal', 'anom... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Creating a function that loop over the parameters and select the best set of parameters based the F-score | def parameterselection(trainset,testset,results):
#Genereting one first model to have a starting value for the loop with selected parameters
parameters={"sax":5,"paa":1,"ngram":3,"threshold":0.10}
best_MODEL=model_to_predict(trainset,testset,results,5,int(len(trainset)/1),3,0.1)
#Looping
for sax in ... | _____no_output_____ | MIT | batadal/Task3_Discrete.ipynb | imchengh/Cyber-Data-Analytics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.