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 |
|---|---|---|---|---|---|
Simulating From the Null HypothesisLoad in the data below, and follow the questions to assist with answering the quiz questions below. | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(42)
full_data = pd.read_csv('../data/coffee_dataset.csv')
sample_data = full_data.sample(200) | _____no_output_____ | MIT | hypothesis_testing/10_HypothesisTesting/13_Simulating From the Null Hypothesis.ipynb | Zabamund/datasci-nano |
`1.` If you were interested in if the average height for coffee drinkers is the same as for non-coffee drinkers, what would the null and alternative be? Place them in the cell below, and use your answer to answer the first quiz question below. **Since there is no directional component associated with this statement, a... | nocoff_means, coff_means, diffs = [], [], []
for _ in range(10000):
bootsamp = sample_data.sample(200, replace = True)
coff_mean = bootsamp[bootsamp['drinks_coffee'] == True]['height'].mean()
nocoff_mean = bootsamp[bootsamp['drinks_coffee'] == False]['height'].mean()
# append the info
coff_means.a... | _____no_output_____ | MIT | hypothesis_testing/10_HypothesisTesting/13_Simulating From the Null Hypothesis.ipynb | Zabamund/datasci-nano |
`4.` Now, use your sampling distribution for the difference in means and [the docs](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html) to simulate what you would expect if your sampling distribution were centered on zero. Also, calculate the observed sample mean difference in `sample... | null_vals = np.random.normal(0, np.std(diffs), 10000) # Here are 10000 draws from the sampling distribution under the null
plt.hist(null_vals); #Here is the sampling distribution of the difference under the null | _____no_output_____ | MIT | hypothesis_testing/10_HypothesisTesting/13_Simulating From the Null Hypothesis.ipynb | Zabamund/datasci-nano |
Iterators, Generators, and Uncertainty Suppose you are working on a Python API that provides access to a real-time data stream (perhaps from an array of sensors or from a web service that handles user requests). You would like to deliver to the consumers of your API a simple but flexible abstraction that allows them t... | class skips:
def __init__(self):
self.integer = 0
def __next__(self):
self.integer += 2
return self.integer | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Now it is possible to use the built-in [`next`](https://docs.python.org/3/library/functions.htmlnext) function to retrieve each item one at a time from an instance of the `skips` data structure. | ns = skips()
[next(ns), next(ns), next(ns)] | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
The number of items over which the data structure will iterate can be limited by raising the `StopIteration` exception when more items can not (or should not) be returned. | class skips:
def __init__(self, start, end):
self.integer = start-2
self.end = end
def __next__(self):
self.integer += 2
if self.integer > self.end:
raise StopIteration
return self.integer | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
It is then the responsibility of any code that uses an instance of this iterator to catch this exception and handle it appropriately. It is worth acknowledging that this is a somewhat unusual use of a language feature normally associated with catching errors (because an iterator being exhausted is not always an error c... | ns = skips(0, 10)
while True:
try:
print(next(ns))
except StopIteration:
break | 0
2
4
6
8
10
| MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Iterables In Python, there is a distinction between an *iterator* and an *iterable data structure*. This distinction is useful to maintain for a variety of reasons, including the ones below.* You may not want to clutter a data structure (as it may represent a spreadsheet, a database table, a large graph, and so on) wi... | class interval:
def __init__(self, lower, upper):
self.lower = lower
self.upper = upper
def evens(self):
return skips(
self.lower + (0 if (self.lower % 2) == 0 else 1),
self.upper
)
def odds(self):
return skips(
self.lower + (... | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
The example below illustrates how an iterator returned by one of the methods in the definition of `interval` can be used. | ns = interval(0, 10).odds()
while True: # Keep iterating and printing until exhaustion.
try:
print(next(ns))
except StopIteration:
break | 1
3
5
7
9
| MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
So far in this article, the distinction between *iterators* and *iterable data structures* has been explicit for clarity. However, the convention that is supported (and sometimes expected) throughout Python is that an iterable data structure has a *single* iterator that can be used to iterate over it. This iterator is ... | class every:
def __init__(self, start, end):
self.integer = start - 1
self.end = end
def __next__(self):
self.integer += 1
if self.integer > self.end:
raise StopIteration
return self.integer
class interval:
def __init__(self, lower, upper):
self.... | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Python's built-in [`iter`](https://docs.python.org/3/library/functions.htmliter) function can be used to invoke `__iter__` for an instance of this data structure. | ns = iter(interval(1, 3))
while True: # Keep iterating and printing until exhaustion.
try:
print(next(ns))
except StopIteration:
break | 1
2
3
| MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Including a definition for an `__iter__` method also makes it possible to use many of Python's built-in functions and language constructs that expect an iterable data structure. This includes functions such as [`list`](https://docs.python.org/3/library/functions.htmlfunc-list) and [`set`](https://docs.python.org/3/libr... | list(interval(0, 10)), set(interval(0, 10)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
This also includes comprehensions and `for` loops. | for n in interval(1, 4):
print([k for k in interval(1, n)]) | [1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
| MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
There is nothing stopping you from making the iterator itself an iterable by having it return itself, as in the variant below. | class every:
def __init__(self, start, end):
self.integer = start - 1
self.end = end
def __next__(self):
self.integer += 1
if self.integer > self.end:
raise StopIteration
return self.integer
def __iter__(self):
return self | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
This approach ensures that there is no ambiguity (from a programmer's perspective) about what will happen when built-in functions such as `list` are applied to an instance of the data structure. | list(every(0, 10)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
This practice is common and is the cause of some of the confusion and conflation that occurs between iterators and iterables. In addition to the potential for confusion, users of such a data structure must be careful to use the iterator as an iterable only once (or, alternatively, the object must reset its internal sta... | ns = every(0, 10)
list(ns), list(ns) # Only returns contents the first time. | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Nevertheless, this can also be a useful practice. Going back to the example with `evens` and `odds`, ensuring the iterators returned by these methods are also iterable means they can be fed directly into contexts that expect an iterable. | class skips:
def __init__(self, start, end):
self.integer = start - 2
self.end = end
def __next__(self):
self.integer += 2
if self.integer > self.end:
raise StopIteration
return self.integer
def __iter__(self):
return self
class interval:
de... | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
The example below illustrates how this kind of interface can be used. | i = interval(0, 10)
list(i.evens()), set(i.odds()) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Generators Generators are data structures defined using either the `yield` statement or comprehension notation (also known as a [generator expression](https://docs.python.org/3/glossary.htmlterm-generator-expression)). The example below defines a generator `skips` using both approaches. | def skips(start, end):
integer = start
while integer <= end:
yield integer
integer += 2
def skips(start, end):
return (
integer
for integer in range(start, end)
if (integer - start) % 2 == 0
) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
When it is evaluated, a generator returns an iterator (more precisely called a [generator iterator](https://docs.python.org/3/glossary.htmlterm-generator-iterator)). These are technically both iterators and iterables. For example, as with any iterator, `next` can be applied directly to instances of this data structure. | ns = skips(0, 10)
next(ns), next(ns), next(ns) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
As with any iterator, exhaustion can be detected by catching the `StopIteration` exception. | ns = skips(0, 2)
try:
next(ns), next(ns), next(ns)
except StopIteration:
print("Exhausted generator iterator.") | Exhausted generator iterator.
| MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Finally, an instance of the data structure can be used in any context that expects an iterable. | list(skips(0, 10)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
It is possible to confirm that the result of evaluating `skips` is indeed a generator by checking its type. | import types
isinstance(skips(0, 10), types.GeneratorType) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
It is also possible to inspect its type to confirm that `skips` indeed evaluates to an iterator. | import collections
isinstance(skips(0, 10), collections.abc.Iterator) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Data Structures of Infinite or Unknown Size Among the use cases that demonstrate how iterators/generators serve as a powerful language feature are scenarios involving data structures whose size is unknown or unbounded/infinite (such as streams, very large files, databases, and so on). You have already seen that you ca... | def concatenate(xs, ys):
for x in xs:
yield x
for y in ys:
yield y | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Concatenating two instances of an iterable data structure is now straightforward. | list(concatenate(skips(0,5), skips(6,11))) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Notice that if the first iterable is never exhausted, the second one will never be used. To address the second requirement, first consider a simpler scenario. What if you would like to "line up" or "pair up" entries in two or more iterables? You can use the built-in [`zip`](https://docs.python.org/3/library/functions.h... | list(zip(skips(0,5), skips(6,11))) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Notice that the result of evaluating `zip` is indeed an iterator. | import collections
isinstance(
zip(skips(0,5), skips(6,11)),
collections.abc.Iterator
) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Combining `zip` with comprehension syntax, you can now define a generator that *interleaves* two iterables (switching back and forth between emitting an item from one and then the other). | def interleave(xs, ys):
return (
z
for (x, y) in zip(xs, ys)
for z in (x, y)
) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
As with concatenation, interleaving is now concise and straightforward. | list(interleave(skips(0,5), skips(6,11))) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Finally, how can you help users process items from a stream in parallel? Because you are already using iterables, users have some options available to them from the built-in [`itertools`](https://docs.python.org/3/library/itertools.html) library. One option is [`islice`](https://docs.python.org/3/library/itertools.html... | from itertools import islice
def batch(xs, size):
ys = list(islice(xs, 0, size))
while len(ys) > 0:
yield ys
ys = list(islice(xs, 0, size)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Notice that this method inherits the graceful behavior of slice notation when the boundaries of the slices do not line up exactly with the number entries in the data structure instance. | list(batch(skips(0,21), 3)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
Can you define a generator that returns batches of batches (*e.g.*, at most `n` batches each of size at most `k`)? Another option is to use the [`tee`](https://docs.python.org/3/library/itertools.htmlitertools.tee) function, which can duplicate a single iterable into multiple iterables. However, this function is really... | from itertools import tee
(a, b) = tee(skips(0,11), 2)
(list(a), list(b)) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
The example above is arguably implemented in a more clear and familiar way by simply wrapping the iterables using `list`. | ns = list(skips(0,11))
(ns, ns) | _____no_output_____ | MIT | iterators-generators-and-uncertainty.ipynb | python-supply/iterators-generators-and-uncertainty |
TAREA GRAVEDAD | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
m = 1
x_0 = .5
x_0_dot = .1
t = np.linspace(0, 50, 300)
gravedad=np.array([9.81,2.78,8.87,3.72,22.88])
gravedad
plt.figure(figsize = (7, 4))
for indx, g in enumerate (gravedad):
omega_0 = np.sqrt(g/m)
x_t = x_0 *np.cos(omega_0 *t) + (x_0_dot... | C:\Users\MaríaEsther\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py:545: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots.
warnings.warn("No labelled objects found. "
| MIT | Gravedad.ipynb | Urakami97/Gravedad-Tarea- |
Modeling and Simulation in Python-Project 1Dhara Patel and Corinne Wilklow Copyright 2018 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) | # Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim library
from modsim import *
from pandas import read_html
print('don... | population
Censusyear
1910.0 92228496.0
1920.0 106021537.0
1930.0 123202624.0
1940.0 132164569.0
1950.0 151325798.0
1960.0 179323175.0
1970.0 203211926.0
1980.0 226545805.0
1990.0 248709873.0
2000.0 281421906.0
2010.0 308745538.0
| MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
The state: initial child population, initial United States populationThe system: birth rates, child mortality rates, mature rates(birth rates 18 years prior)Metrics: annual child population | def plot_results(population, childseries, title):
"""Plot the estimates and the model.
population: TimeSeries of historical population data
childseries: TimeSeries of child population estimates
title: string
"""
plot(population, ':', label='US Population')
if len(childseries):
p... | _____no_output_____ | MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
Why is the proportion of children in the United States decreasing? Over the past two decades, the United States population grew by about 20%. During the same time frame, the nation’s child population grew by only 5%. The population all around the world is aging, and children represent a smaller and smaller share of... | #sweeping both the mortality rate and the birth rate will make the model more accurate
birthrate = [29.06, 25.03, 19.22, 22.63, 24.86, 20.33, 15.57, 15.83, 15.08, 13.97]
deathrate = linspace(0.0065, 0.0031, 10)
maturerate = [31.5, 29.06, 25.03, 19.22, 22.63, 24.86, 20.33, 15.57, 15.83, 15.08]
print(birthrate)
print(de... | _____no_output_____ | MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
Parameters: | system = System(birthrate = birthrate,
maturerate = maturerate,
deathrate = deathrate,
t_0 = 1910.0,
t_end = 2010.0,
state=state) | _____no_output_____ | MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
Our update function computes the updated state of these parameters at the end of each ten year increment. | def update_func1(state, t, system):
t_pop=151325798.0
if t == 1910:
i = int((t-1910)/10)
else:
i = int((t-1910)/10 - 1)
mrate = system.maturerate
brate = system.birthrate
drate = system.deathrate
births = brate[i]/100 * state.children #metric
maturings = mra... | _____no_output_____ | MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
To test our update function, we'll input the initial condition: | update_func1(state,system.t_0,system)
def run_simulation(state, system, update_func):
"""Simulate the system using any update function.
state: initial State object
system: System object
update_func: function that computes the population next year
returns: TimeSeries of Ratios
"""
#... | _____no_output_____ | MIT | code/Project_1_US_Children_9-30_final2.ipynb | cwilklow/ModSimPy |
Jupyter (iPython) Notebookを使って技術ノート環境を構築する方法myenigma.hatenablog.com | from sympy import *
x=Symbol('x')
%matplotlib inline
init_printing()
expand((x - 3)**5) | _____no_output_____ | MIT | .ipynb_checkpoints/learnJupyter-checkpoint.ipynb | kalz2q/files |
Linear Regression Multiple Outputs Table of ContentsIn this lab, you will create a model the PyTroch way. This will help you more complicated models. Make Some Data Create the Model and Cost Function the PyTorch way Train the Model: Batch Gradient DescentEstimated Time Needed: 20 min Preparation We'll ... | # Import the libraries we need for this lab
from torch import nn,optim
import torch
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from torch.utils.data import Dataset, DataLoader | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Set the random seed: | # Set the random seed to 1.
torch.manual_seed(1) | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Use this function for plotting: | # The function for plotting 2D
def Plot_2D_Plane(model, dataset, n=0):
w1 = model.state_dict()['linear.weight'].numpy()[0][0]
w2 = model.state_dict()['linear.weight'].numpy()[0][1]
b = model.state_dict()['linear.bias'].numpy()
# Data
x1 = data_set.x[:, 0].view(-1, 1).numpy()
x2 = data_set.x[:,... | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Make Some Data Create a dataset class with two-dimensional features: | # Create a 2D dataset
class Data2D(Dataset):
# Constructor
def __init__(self):
self.x = torch.zeros(20, 2)
self.x[:, 0] = torch.arange(-1, 1, 0.1)
self.x[:, 1] = torch.arange(-1, 1, 0.1)
self.w = torch.tensor([[1.0], [1.0]])
self.b = 1
self.f = torch.mm(self... | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create a dataset object: | # Create the dataset object
data_set = Data2D() | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create the Model, Optimizer, and Total Loss Function (Cost) Create a customized linear regression module: | # Create a customized linear
class linear_regression(nn.Module):
# Constructor
def __init__(self, input_size, output_size):
super(linear_regression, self).__init__()
self.linear = nn.Linear(input_size, output_size)
# Prediction
def forward(self, x):
yhat = self.lin... | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create a model. Use two features: make the input size 2 and the output size 1: | # Create the linear regression model and print the parameters
model = linear_regression(2,1)
print("The parameters: ", list(model.parameters())) | The parameters: [Parameter containing:
tensor([[ 0.6209, -0.1178]], requires_grad=True), Parameter containing:
tensor([0.3026], requires_grad=True)]
| MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create an optimizer object. Set the learning rate to 0.1. Don't forget to enter the model parameters in the constructor. | # Create the optimizer
optimizer = optim.SGD(model.parameters(), lr=0.1) | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create the criterion function that calculates the total loss or cost: | # Create the cost function
criterion = nn.MSELoss() | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Create a data loader object. Set the batch_size equal to 2: | # Create the data loader
train_loader = DataLoader(dataset=data_set, batch_size=2) | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Train the Model via Mini-Batch Gradient Descent Run 100 epochs of Mini-Batch Gradient Descent and store the total loss or cost for every iteration. Remember that this is an approximation of the true total loss or cost: | # Train the model
LOSS = []
print("Before Training: ")
Plot_2D_Plane(model, data_set)
epochs = 100
def train_model(epochs):
for epoch in range(epochs):
for x,y in train_loader:
yhat = model(x)
loss = criterion(yhat, y)
LOSS.append(loss.item())
opti... | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Practice Create a new model1. Train the model with a batch size 30 and learning rate 0.1, store the loss or total cost in a list LOSS1, and plot the results. | # Practice create model1. Train the model with batch size 30 and learning rate 0.1, store the loss in a list <code>LOSS1</code>. Plot the results.
data_set = Data2D() | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Double-click here for the solution.<!-- Your answer is below:train_loader = DataLoader(dataset = data_set, batch_size = 30)model1 = linear_regression(2, 1)optimizer = optim.SGD(model1.parameters(), lr = 0.1)LOSS1 = []epochs = 100def train_model(epochs): for epoch in range(epochs): for x,y in train_loader:... | torch.manual_seed(2)
validation_data = Data2D()
Y = validation_data.y
X = validation_data.x | _____no_output_____ | MIT | IBM_AI/4_Pytorch/4.2.multiple_linear_regression_training_v2.ipynb | merula89/cousera_notebooks |
Creating groupsWe are going to create a simple group. | group = Group.objects.create(name='My First Group')
group.pk | _____no_output_____ | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Now lets create a group that is a child of the first group. | group_child = Group.objects.create(name='Child of (My First Group)', parent_group=group)
group_child.parent_group.name | _____no_output_____ | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Creating jobsNow that we have a few groups lets create some jobs to add to the groups. | job_1 = Job.objects.create(title='Job 1')
job_2 = Job.objects.create(title='Job 2') | _____no_output_____ | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Adding jobs to a group | group.jobs.add(job_1)
group_child.jobs.add(job_2) | _____no_output_____ | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Ok now lets add some saved candidates to a new group | candidate_1 = SavedCandidate.objects.create(name='Candidate 1')
candidate_2 = SavedCandidate.objects.create(name='Candidate 2')
group_2 = Group.objects.create(name='Group 2')
group_2_child = Group.objects.create(name='Group 2 Child', parent_group=group_2)
group_2_child.saved_candidates.add(candidate_1)
group_2_child.sa... | _____no_output_____ | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Lets loop all the groups and display there names, jobs and saved candiates for each. | for group in Group.objects.all():
print("Group: {}".format(group.name))
print("jobs: {}".format(group.jobs.count()))
for job in group.jobs.all():
print(job.title)
print("saved candidates: {}".format(group.saved_candidates.count()))
for candidate in group.saved_candidates.all():
... | Group: My First Group
jobs: 1
Job 1
saved candidates: 0
Group: Child of (My First Group)
jobs: 1
Job 2
saved candidates: 0
Group: Group 2
jobs: 0
saved candidates: 0
Group: Group 2 Child
jobs: 0
saved candidates: 2
Candidate 1
Candidate 2
Group: My First Group
jobs: 1
Job 1
saved candidates: 0
Group: Child of... | MIT | notebooks/Django Models.ipynb | warplydesigned/django_jupyter |
Title: Alert Investigation (Windows Process Alerts)**Notebook Version:** 1.0**Python Version:** Python 3.6 (including Python 3.6 - AzureML)**Required Packages**: kqlmagic, msticpy, pandas, numpy, matplotlib, networkx, ipywidgets, ipython, scikit_learn**Platforms Supported**:- Azure Notebooks Free Compute- Azure Notebo... | import sys
import warnings
warnings.filterwarnings("ignore",category=DeprecationWarning)
MIN_REQ_PYTHON = (3,6)
if sys.version_info < MIN_REQ_PYTHON:
print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')
print('or later is selected as the active kernel.')
sys.exit("Python %s.%s or later... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Import Python Packages Get WorkspaceIdTo find your Workspace Id go to [Log Analytics](https://ms.portal.azure.com/blade/HubsExtension/Resources/resourceType/Microsoft.OperationalInsights%2Fworkspaces). Look at the workspace properties to find the ID. | # Imports
import sys
MIN_REQ_PYTHON = (3,6)
if sys.version_info < MIN_REQ_PYTHON:
print('Check the Kernel->Change Kernel menu and ensure that Python 3.6')
print('or later is selected as the active kernel.')
sys.exit("Python %s.%s or later is required.\n" % MIN_REQ_PYTHON)
import numpy as np
from IPython im... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Authenticate to Log AnalyticsIf you are using user/device authentication, run the following cell. - Click the 'Copy code to clipboard and authenticate' button.- This will pop up an Azure Active Directory authentication dialog (in a new tab or browser window). The device code will have been copied to the clipboard. - S... | if not WORKSPACE_ID or not TENANT_ID:
try:
WORKSPACE_ID = ws_id.value
TENANT_ID = ten_id.value
except NameError:
raise ValueError('No workspace or Tenant Id.')
mas.kql.load_kql_magic()
%kql loganalytics://code().tenant(TENANT_ID).workspace(WORKSPACE_ID) | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Get Alerts ListSpecify a time range to search for alerts. One this is set run the following cell to retrieve any alerts in that time window.You can change the time range and re-run the queries until you find the alerts that you want. | alert_q_times = mas.QueryTime(units='day', max_before=20, before=5, max_after=1)
alert_q_times.display()
alert_counts = qry.list_alerts_counts(provs=[alert_q_times])
alert_list = qry.list_alerts(provs=[alert_q_times])
print(len(alert_counts), ' distinct alert types')
print(len(alert_list), ' distinct alerts')
display(H... | 12 distinct alert types
51 distinct alerts
| MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Choose Alert to InvestigateEither pick an alert from a list of retrieved alerts or paste the SystemAlertId into the text box in the following section. Select alert from listAs you select an alert, the main properties will be shown below the list.Use the filter box to narrow down your search to any subs... | alert_select = mas.AlertSelector(alerts=alert_list, action=nbdisp.display_alert)
alert_select.display() | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Or paste in an alert ID and fetch it**Skip this if you selected from the above list** | # Allow alert to be selected
# Allow subscription to be selected
get_alert = mas.GetSingleAlert(action=nbdisp.display_alert)
get_alert.display() | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Extract properties and entities from AlertThis section extracts the alert information and entities into a SecurityAlert object allowing us to query the properties more reliably. In particular, we use the alert to automatically provide parameters for queries and UI elements.Subsequent queries will use pr... | # Extract entities and properties into a SecurityAlert class
if alert_select.selected_alert is None and get_alert.selected_alert is None:
sys.exit("Please select an alert before executing remaining cells.")
if get_alert.selected_alert is not None:
security_alert = mas.SecurityAlert(get_alert.selected_alert)
el... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Entity GraphDepending on the type of alert there may be one or more entities attached as properties. Entities are things like Host, Account, IpAddress, Process, etc. - essentially the 'nouns' of security investigation. Events and alerts are the things that link them in actions so can be thought of as th... | # Draw the graph using Networkx/Matplotlib
%matplotlib inline
alertentity_graph = mas.create_alert_graph(security_alert)
nbdisp.draw_alert_entity_graph(alertentity_graph, width=15) | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Related AlertsFor a subset of entities in the alert we can search for any alerts that have that entity in common. Currently this query looks for alerts that share the same Host, Account or Process and lists them below. **Notes:**- Some alert types do not include all of these entity types.- The original ... | # set the origin time to the time of our alert
query_times = mas.QueryTime(units='day', origin_time=security_alert.TimeGenerated,
max_before=28, max_after=1, before=5)
query_times.display()
related_alerts = qry.list_related_alerts(provs=[query_times, security_alert])
if related_alerts is n... | Found 8 different alert types related to this host ('msticalertswin1')
Detected potentially suspicious use of Telegram tool, Count of alerts: 2
Detected the disabling of critical services, Count of alerts: 2
Digital currency mining related behavior detected, Count of alerts: 2
Potential attempt to bypas... | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Show these related alerts on a graphThis should indicate which entities the other alerts are related to.This can be unreadable with a lot of alerts. Use the matplotlib interactive zoom control to zoom in to part of the graph. | # Draw a graph of this (add to entity graph)
%matplotlib notebook
%matplotlib inline
if related_alerts is not None and not related_alerts.empty:
rel_alert_graph = mas.add_related_alerts(related_alerts=related_alerts,
alertgraph=alertentity_graph)
nbdisp.draw_alert_e... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Browse List of Related AlertsSelect an Alert to view details. If you want to investigate that alert - copy its *SystemAlertId* property and open a new instance of this notebook to investigate this alert. |
def disp_full_alert(alert):
global related_alert
related_alert = mas.SecurityAlert(alert)
nbdisp.display_alert(related_alert, show_entities=True)
if related_alerts is not None and not related_alerts.empty:
related_alerts['CompromisedEntity'] = related_alerts['Computer']
print('Selected alert is av... | Selected alert is available as 'related_alert' variable.
| MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Get Process TreeIf the alert has a process entity this section tries to retrieve the entire process tree to which that process belongs.Notes:- The alert must have a process entity- Only processes started within the query time boundary will be included- Ancestor and descented processes are retrieved to t... | # set the origin time to the time of our alert
query_times = mas.QueryTime(units='minute', origin_time=security_alert.origin_time)
query_times.display()
from msticpy.nbtools.query_defns import DataFamily
if security_alert.data_family != DataFamily.WindowsSecurity:
raise ValueError('The remainder of this notebook c... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Process TimeLineThis shows each process in the process tree on a timeline view.Labelling of individual process is very performance intensive and often results in nothing being displayed at all! Besides, for large numbers of processes it would likely result in an unreadable mess. Your main tools for nego... | # Show timeline of events
if process_tree is not None and not process_tree.empty:
nbdisp.display_timeline(data=process_tree, alert=security_alert,
title='Alert Process Session', height=250) | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Other Processes on Host - ClusteringSometimes you don't have a source process to work with. Other times it's just useful to see what else is going on on the host. This section retrieves all processes on the host within the time boundsset in the query times widget.You can display the raw output of this b... | from msticpy.sectools.eventcluster import dbcluster_events, add_process_features
processes_on_host = qry.list_processes(provs=[query_times, security_alert])
if processes_on_host is not None and not processes_on_host.empty:
feature_procs = add_process_features(input_frame=processes_on_host,
... | Number of input events: 190
Number of clustered events: 24
| MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Variability in Command Lines and Process NamesThe top chart shows the variability of command line content for a give process name. The wider the box, the more instances were found with different command line structure Note, the 'structure' in this case is measured by the number of tokens or delimiters in the command l... | # Looking at the variability of commandlines and process image paths
import seaborn as sns
sns.set(style="darkgrid")
if processes_on_host is not None and not processes_on_host.empty:
proc_plot = sns.catplot(y="processName", x="commandlineTokensFull",
data=feature_procs.sort_values('pro... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
The top graph shows that, for a given process, some have a wide variability in their command line content while the majority have little or none. Looking at a couple of examples - like cmd.exe, powershell.exe, reg.exe, net.exe - we can recognize several common command line tools.The second graph shows processes by full... | if not clus_events.empty:
resp = input('View the clustered data? y/n')
if resp == 'y':
display(clus_events.sort_values('TimeGenerated')[['TimeGenerated', 'LastEventTime',
'NewProcessName', 'CommandLine',
... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Time showing clustered vs. original data | # Show timeline of events - clustered events
if not clus_events.empty:
nbdisp.display_timeline(data=clus_events,
overlay_data=processes_on_host,
alert=security_alert,
title='Distinct Host Processes (top) and All Proceses (bottom)... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Base64 Decode and Check for IOCsThis section looks for Indicators of Compromise (IoC) within the data sets passed to it.The first section looks at the commandline for the alert process (if any). It also looks for base64 encoded strings within the data - this is a common way of hiding attacker intent. It... | process = security_alert.primary_process
ioc_extractor = sectools.IoCExtract()
if process:
# if nothing is decoded this just returns the input string unchanged
base64_dec_str, _ = sectools.b64.unpack_items(input_string=process["CommandLine"])
if base64_dec_str and '<decoded' in base64_dec_str:
prin... |
Potential IoCs found in alert process:
| MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
If we have a process tree, look for IoCs in the whole data setYou can replace the data=process_tree parameter to ioc_extractor.extract() to pass other data frames.use the columns parameter to specify which column or columns that you want to search. | ioc_extractor = sectools.IoCExtract()
try:
if not process_tree.empty:
source_processes = process_tree
else:
source_processes = clus_events
except NameError:
source_processes = None
if source_processes is not None:
ioc_df = ioc_extractor.extract(data=source_processes,
... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
If any Base64 encoded strings, decode and search for IoCs in the results.For simple strings the Base64 decoded output is straightforward. However for nested encodings this can get a little complex and difficult to represent in a tabular format.**Columns** - reference - The index of the row item in dotted notation in d... | if source_processes is not None:
dec_df = sectools.b64.unpack_items(data=source_processes, column='CommandLine')
if source_processes is not None and not dec_df.empty:
display(HTML("<h3>Decoded base 64 command lines</h3>"))
display(HTML("Warning - some binary patterns may be decodable as unicode strings... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Virus Total LookupThis section uses the popular Virus Total service to check any recovered IoCs against VTs database.To use this you need an API key from virus total, which you can obtain here: https://www.virustotal.com/.Note that VT throttles requests for free API keys to 4/minute. If you are unable t... | vt_key = mas.GetEnvironmentKey(env_var='VT_API_KEY',
help_str='To obtain an API key sign up here https://www.virustotal.com/',
prompt='Virus Total API key:')
vt_key.display()
if vt_key.value and ioc_df is not None and not ioc_df.empty:
vt_lookup = sectools.VTLoo... | 5 items in input frame
Items in each category to be submitted to VirusTotal
(Note: items have pre-filtering to remove obvious erroneous data and false positives, such as private IPaddresses)
{'ipv4': 0, 'dns': 2, 'url': 2, 'md5_hash': 0, 'sha1_hash': 0, 'sh256_hash': 0}
-------------------------------------------------... | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
To view the raw response for a specific row.```import jsonrow_idx = 0 The row number from one of the above dataframesraw_response = json.loads(pos_vt_results['RawResponse'].loc[row_idx])raw_response``` [Contents](toc) Alert command line - Occurrence on other hosts in workspaceTo get a sense of whether the alert proces... | # set the origin time to the time of our alert
query_times = mas.QueryTime(units='day', before=5, max_before=20,
after=1, max_after=10,
origin_time=security_alert.origin_time)
query_times.display()
# API ILLUSTRATION - Find the query to use
qry.list_queries()
# AP... | No proceses with matching commandline found in on other hosts in workspace
between 2019-02-08 22:04:16 and 2019-02-14 22:04:16
| MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Host LogonsThis section retrieves the logon events on the host in the alert.You may want to use the query times to search over a broader range than the default. | # set the origin time to the time of our alert
query_times = mas.QueryTime(units='day', origin_time=security_alert.origin_time,
before=1, after=0, max_before=20, max_after=1)
query_times.display() | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Alert Logon AccountThe logon associated with the process in the alert. | logon_id = security_alert.get_logon_id()
if logon_id:
if logon_id in ['0x3e7', '0X3E7', '-1', -1]:
print('Cannot retrieve single logon event for system logon id '
'- please continue with All Host Logons below.')
else:
logon_event = qry.get_host_logon(provs=[query_times, security_a... | ### Account Logon
Account: MSTICAdmin
Account Domain: MSTICAlertsWin1
Logon Time: 2019-02-13 22:03:42.283000
Logon type: 4 (Batch)
User Id/SID: S-1-5-21-996632719-2361334927-4038480536-500
SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator
SID S-1-5-21-996632719-2361334927-4038480536-500 is l... | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
All Host LogonsSince the number of logon events may be large and, in the case of system logons, very repetitive, we use clustering to try to identity logons with unique characteristics.In this case we use the numeric score of the account name and the logon type (i.e. interactive, service, etc.). The results of the clu... | from msticpy.sectools.eventcluster import dbcluster_events, add_process_features, _string_score
host_logons = qry.list_host_logons(provs=[query_times, security_alert])
if host_logons is not None and not host_logons.empty:
logon_features = host_logons.copy()
logon_features['AccountNum'] = host_logons.apply(lamb... | ### Account Logon
Account: MSTICAdmin
Account Domain: MSTICAlertsWin1
Logon Time: 2019-02-13 22:03:42.283000
Logon type: 4 (Batch)
User Id/SID: S-1-5-21-996632719-2361334927-4038480536-500
SID S-1-5-21-996632719-2361334927-4038480536-500 is administrator
SID S-1-5-21-996632719-2361334927-4038480536-500 is l... | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Comparing All Logons with Clustered results relative to Alert time line | # Show timeline of events - all logons + clustered logons
if host_logons is not None and not host_logons.empty:
nbdisp.display_timeline(data=host_logons, overlay_data=clus_logons,
alert=security_alert,
source_columns=['Account', 'LogonType'],
... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
View Process Session and Logon Events in TimelinesThis shows the timeline of the clustered logon events with the process tree obtained earlier. This allows you to get a sense of which logon was responsible for the process tree session whether any additional logons (e.g. creating a process as another user) might be ass... | # Show timeline of events - all events
if host_logons is not None and not host_logons.empty:
nbdisp.display_timeline(data=clus_logons, source_columns=['Account', 'LogonType'],
alert=security_alert,
title='Clustered Host Logons', height=200)
try:
... | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Failed Logons | failedLogons = qry.list_host_logon_failures(provs=[query_times, security_alert])
if failedLogons.shape[0] == 0:
display(print('No logon failures recorded for this host between {security_alert.start} and {security_alert.start}'))
failedLogons | _____no_output_____ | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
[Contents](toc) Appendices Available DataFrames | print('List of current DataFrames in Notebook')
print('-' * 50)
current_vars = list(locals().keys())
for var_name in current_vars:
if isinstance(locals()[var_name], pd.DataFrame) and not var_name.startswith('_'):
print(var_name) | List of current DataFrames in Notebook
--------------------------------------------------
mydf
alert_counts
alert_list
related_alerts
process_tree
processes_on_host
feature_procs
clus_events
source_processes
ioc_df
dec_df
ioc_dec_df
vt_results
pos_vt_results
proc_match_in_ws
logon_event
host_logons
logon_features
clus_... | MIT | Notebooks/Sample-Notebooks/Example - Guided Investigation - Process-Alerts.ipynb | h0tp0ck3t/Sentinel |
Compose and send emails> Compose and send html emails through an SMTP server using TLS. | #hide
from nbdev.showdoc import *
#export
import smtplib
from email.message import EmailMessage
import mimetypes
from pathlib2 import Path
import re | _____no_output_____ | Apache-2.0 | 03_email.ipynb | eandreas/secretsanta |
Complose a message | #export
def create_html_message(from_address, to_addresses, subject, html, text = None, image_path = Path.cwd()):
msg = EmailMessage()
msg['From'] = from_address
msg['To'] = to_addresses
msg['Subject'] = subject
if text is not None:
msg.set_content(text)
msg.add_alternative(html, subtype... | _____no_output_____ | Apache-2.0 | 03_email.ipynb | eandreas/secretsanta |
Add an attachment to a message | #export
def add_attachmet(msg, path):
"Add an attachment with location `path` to the cunnet message `msg`."
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype, encoding = mimetypes.g... | _____no_output_____ | Apache-2.0 | 03_email.ipynb | eandreas/secretsanta |
Send a message using SMTP and TLS | #export
def send_smtp_email(server, tls_port, user, pw, msg):
"Send the message `msg` using the specified `server` and `port` - login using `user` and `pw`."
# Create a secure SSL context
try:
smtp = smtplib.SMTP(server, tls_port)
smtp.starttls()
smtp.login(user, pw)
smtp.sen... | _____no_output_____ | Apache-2.0 | 03_email.ipynb | eandreas/secretsanta |
Examples The following is an example on how to compose and send a html-email message. | ## set user and password of the smtp server
#user = ''
#pw = ''
#
## send email from and to myself
#from_email = user
#to_email = ''
#
#html = """
#Hello, this is a test message!
#<h1>Hello 22!</h1>
#<img src="cid:email.jpg">
#<h1>Hello 23!</h1>
#<img src="cid:iceberg.jpg">
#"""
#
#msg = create_html_message(from_email,... | _____no_output_____ | Apache-2.0 | 03_email.ipynb | eandreas/secretsanta |
DQN With Prioritized Replay BufferUse prioritized replay buffer to train a DQN agent. | import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
import gym
import numpy as np
from gym.core import ObservationWrapper
from gym.spaces import Box
import cv2
import os
import atari_wrappers # adjust env
from framebuffer import FrameBuffer # stack 4 cons... | _____no_output_____ | Unlicense | week04_approx_rl/prioritized_replay_dqn.ipynb | hsl89/Practical_RL |
PreprocessingCrop the important part of the image, then resize to 64 x 64 | class PreprocessAtariObs(ObservationWrapper):
def __init__(self, env):
"""A gym wrapper that crops, scales image into the desired shapes and grayscales it."""
ObservationWrapper.__init__(self, env)
self.image_size = (1, 64, 64)
self.observation_space = Box(0.0, 1.0, self.image_size)... | adjusted env with 4 consec images stacked can be created
| Unlicense | week04_approx_rl/prioritized_replay_dqn.ipynb | hsl89/Practical_RL |
Model | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def conv2d_size_out(size, kernel_size, stride):
"""
common use case:
cur_layer_img_w = conv2d_size_out(cur_layer_img_w, kernel_size, stride)
cur_layer_img_h = conv2d_size_out(cur_layer_img_h, kernel_size, stride)
to understand th... | _____no_output_____ | Unlicense | week04_approx_rl/prioritized_replay_dqn.ipynb | hsl89/Practical_RL |
Compute TD loss | def compute_td_loss(states, actions, rewards, next_states, is_done,
agent, target_network,
gamma=0.99,
device=device, check_shapes=False):
""" Compute td loss using torch operations only. Use the formulae above. '''
objective of agent is
\hat... | _____no_output_____ | Unlicense | week04_approx_rl/prioritized_replay_dqn.ipynb | hsl89/Practical_RL |
Test the memory need of the replay buffer Init DQN agent and play a total 10^4 time steps | def play_and_record(initial_state, agent, env, exp_replay, n_steps=1):
"""
Play the game for exactly n steps, record every (s,a,r,s', done) to replay buffer.
Whenever game ends, add record with done=True and reset the game.
It is guaranteed that env has done=False when passed to this function.
PLE... | Starts training on cpu
buffer size = 129, epsilon: 1.00000
checkpointing ...
| Unlicense | week04_approx_rl/prioritized_replay_dqn.ipynb | hsl89/Practical_RL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.