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 |
|---|---|---|---|---|---|
**Optional:** Search for the combination of length and spring constant that yields minimum height 0 while minimizing peak acceleration. | # Solution
ks = np.linspace(1, 31, 11) * N / m
for k in ks:
guess = 250 * m
params = Params(params, k=k)
solution = fsolve(error_func, guess, params)
L = solution[0] * m
params = Params(params, L=L)
system = make_system(params)
results, details = run_ode_solver(system, slope_func, t_eval=t... | 1.0 newton / meter -483.1429396908503 meter 0.17584604083333497 dimensionless
4.0 newton / meter 70.54780511680855 meter 0.6912121734141764 dimensionless
7.0 newton / meter 161.1541432460714 meter 1.0914235802924046 dimensionless
10.0 newton / meter 202.17405449658656 meter 1.435864054193015 dimensionless
13.0 newton /... | MIT | code/soln/chap21soln.ipynb | rsmxingu/ModSimPy |
**Optional exercise:** This model neglects the weight of the bungee cord, which might be non-negligible. Implement the [model described here](http://iopscience.iop.org/article/10.1088/0031-9120/45/1/007) and see how different it is from our simplified model. Under the hoodThe gradient function in `modsim.py` adapts ... | %psource gradient | _____no_output_____ | MIT | code/soln/chap21soln.ipynb | rsmxingu/ModSimPy |
**Important**: This notebook is different from the other as it directly calls **ImageJ Kappa plugin** using the [`scyjava` ImageJ brige](https://github.com/scijava/scyjava).Since Kappa uses ImageJ1 features, you might not be able to run this notebook on an headless machine (need to be tested). | from pathlib import Path
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
import sys; sys.path.append("../../")
import pykappa
# Init ImageJ with Fiji plugins
# It can take a while if Java artifacts are not yet cached.
import imagej
java_deps = []
java_deps.append('org.scijava:Kappa:1.7.1')
ij = imag... | _____no_output_____ | MIT | Analysis/Notebooks/Spiral Dataset/2_Measure_Curvature.ipynb | brouhardlab/kappa |
turtleview You need to run the following code for viewing the simulator output in the notebook: | %matplotlib inline
import nbturtle
nbturtle.plot() | _____no_output_____ | Apache-2.0 | Concepts/Fundamentals/turtleview.ipynb | RobInLabUJI/ROSIN-Tutorials |
Tutorial 1: PyTorch**Week 1, Day 1: Basics and PyTorch****By Neuromatch Academy**__Content creators:__ Shubh Pachchigar, Vladimir Haltakov, Matthew Sargent, Konrad Kording__Content reviewers:__ Deepak Raya, Siwei Bai, Kelson Shilling-Scrivo__Content editors:__ Anoop Kulkarni, Spiros Chavlis__Production editors:__ Aru... | # @title Tutorial slides
# @markdown These are the slides for the videos in this tutorial today
from IPython.display import IFrame
IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/wcjrv/?direct%26mode=render%26action=download%26mode=render", width=854, height=480) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
--- Setup Throughout your Neuromatch tutorials, most (probably all!) notebooks contain setup cells. These cells will import the required Python packages (e.g., PyTorch, NumPy); set global or environment variables, and load in helper functions for things like plotting. In some tutorials, you will notice that we install ... | # @title Install dependencies
!pip install pandas --quiet
!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet
from evaltools.airtable import AirtableForm
# Imports
import time
import torch
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from torch import nn
fro... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Important note: Google Colab users***Scratch Code Cells*If you want to quickly try out something or take a look at the data you can use scratch code cells. They allow you to run Python code, but will not mess up the structure of your notebook.To open a new scratch cell go to *Insert* → *Scratch code cell*. Section 1... | # @title Video 1: Welcome and History
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&pag... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
*This will be an intensive 3 week adventure. We will all learn Deep Learning. In a group. Groups need standards. Read our [Code of Conduct](https://docs.google.com/document/d/1eHKIkaNbAlbx_92tLQelXnicKXEcvFzlyzzeWjEtifM/edit?usp=sharing). | # @title Video 2: Why DL is cool
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Describe what you hope to get out of this course in about 100 words.** --- Section 2: The Basics of PyTorch*Time estimate: ~2 hours 05 mins* PyTorch is a Python-based scientific computing package targeted at two sets ofaudiences:- A replacement for NumPy to use the power of GPUs- A deep learning platform that provi... | # @title Video 3: Making Tensors
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
There are various ways of creating tensors, and when doing any real deep learning project we will usually have to do so. **Construct tensors directly:**--- | # we can construct a tensor directly from some common python iterables,
# such as list and tuple nested iterables can also be handled as long as the
# dimensions make sense
# tensor from a list
a = torch.tensor([0, 1, 2])
#tensor from a tuple of tuples
b = ((1.0, 1.1), (1.2, 1.3))
b = torch.tensor(b)
# tensor from a... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Some common tensor constructors:**--- | # the numerical arguments we pass to these constructors
# determine the shape of the output tensor
x = torch.ones(5, 3)
y = torch.zeros(2)
z = torch.empty(1, 1, 5)
print(f"Tensor x: {x}")
print(f"Tensor y: {y}")
print(f"Tensor z: {z}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Notice that ```.empty()``` does not return zeros, but seemingly random small numbers. Unlike ```.zeros()```, which initialises the elements of the tensor with zeros, ```.empty()``` just allocates the memory. It is hence a bit faster if you are looking to just create a tensor. **Creating random tensors and tensors like ... | # there are also constructors for random numbers
# uniform distribution
a = torch.rand(1, 3)
# normal distribution
b = torch.randn(3, 4)
# there are also constructors that allow us to construct
# a tensor according to the above constructors, but with
# dimensions equal to another tensor
c = torch.zeros_like(a)
d = ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
*Reproducibility*: - PyTorch random number generator: You can use `torch.manual_seed()` to seed the RNG for all devices (both CPU and CUDA)```pythonimport torchtorch.manual_seed(0)```- For custom operators, you might need to set python seed as well:```pythonimport randomrandom.seed(0)```- Random number generators in ot... | def set_seed(seed=None, seed_torch=True):
"""
Function that controls randomness. NumPy and random modules must be imported.
Args:
seed : Integer
A non-negative integer that defines the random state. Default is `None`.
seed_torch : Boolean
If `True` sets the random seed for pytorch tensors, so... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Now, let's use the `set_seed` function in the previous example. Execute the cell multiple times to verify that the numbers printed are always the same. | def simplefun(seed=True, my_seed=None):
if seed:
set_seed(seed=my_seed)
# uniform distribution
a = torch.rand(1, 3)
# normal distribution
b = torch.randn(3, 4)
print("Tensor a: ", a)
print("Tensor b: ", b)
simplefun(seed=True, my_seed=0) # Turn `seed` to `False` or change `my_seed` | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Numpy-like number ranges:**---The ```.arange()``` and ```.linspace()``` behave how you would expect them to if you are familar with numpy. | a = torch.arange(0, 10, step=1)
b = np.arange(0, 10, step=1)
c = torch.linspace(0, 5, steps=11)
d = np.linspace(0, 5, num=11)
print(f"Tensor a: {a}\n")
print(f"Numpy array b: {b}\n")
print(f"Tensor c: {c}\n")
print(f"Numpy array d: {d}\n") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Coding Exercise 2.1: Creating TensorsBelow you will find some incomplete code. Fill in the missing code to construct the specified tensors.We want the tensors: $A:$ 20 by 21 tensor consisting of ones$B:$ a tensor with elements equal to the elements of numpy array $Z$$C:$ a tensor with the same number of elements as $A... | def tensor_creation(Z):
"""A function that creates various tensors.
Args:
Z (numpy.ndarray): An array of shape
Returns:
A : 20 by 21 tensor consisting of ones
B : a tensor with elements equal to the elements of numpy array Z
C : a tensor with the same number of elements as A but with values ∼U(... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_ad4f6c0f.py) ```All correct!``` Section 2.2: Operations in PyTorch**Tensor-Tensor operations**We can perform operations on tensors using methods under ```torch.``` | # @title Video 4: Tensor Operators
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Tensor-Tensor operations**We can perform operations on tensors using methods under ```torch.``` | a = torch.ones(5, 3)
b = torch.rand(5, 3)
c = torch.empty(5, 3)
d = torch.empty(5, 3)
# this only works if c and d already exist
torch.add(a, b, out=c)
#Pointwise Multiplication of a and b
torch.multiply(a, b, out=d)
print(c)
print(d) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
However, in PyTorch most common Python operators are overridden.The common standard arithmetic operators (+, -, *, /, and **) have all been lifted to elementwise operations | x = torch.tensor([1, 2, 4, 8])
y = torch.tensor([1, 2, 3, 4])
x + y, x - y, x * y, x / y, x**y # The ** operator is exponentiation | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Tensor Methods** Tensors also have a number of common arithmetic operations built in. A full list of **all** methods can be found in the appendix (there are a lot!) All of these operations should have similar syntax to their numpy equivalents.(Feel free to skip if you already know this!) | x = torch.rand(3, 3)
print(x)
print("\n")
# sum() - note the axis is the axis you move across when summing
print(f"Sum of every element of x: {x.sum()}")
print(f"Sum of the columns of x: {x.sum(axis=0)}")
print(f"Sum of the rows of x: {x.sum(axis=1)}")
print("\n")
print(f"Mean value of all elements of x {x.mean()}")
p... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Matrix Operations**The ```@``` symbol is overridden to represent matrix multiplication. You can also use ```torch.matmul()``` to multiply tensors. For dot multiplication, you can use ```torch.dot()```, or manipulate the axes of your tensors and do matrix multiplication (we will cover that in the next section). Transp... | def simple_operations(a1: torch.Tensor, a2: torch.Tensor, a3: torch.Tensor):
################################################
## TODO for students: complete the first computation using the argument matricies
raise NotImplementedError("Student exercise: fill in the missing code to complete the operation")
#####... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_5562ea1d.py) ```tensor([[20, 24], [31, 27]])``` | def dot_product(b1: torch.Tensor, b2: torch.Tensor):
###############################################
## TODO for students: complete the first computation using the argument matricies
raise NotImplementedError("Student exercise: fill in the missing code to complete the operation")
##############################... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_00491ea4.py) ```tensor(82)``` Section 2.3 Manipulating Tensors in Pytorch | # @title Video 5: Tensor Indexing
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Indexing**Just as in numpy, elements in a tensor can be accessed by index. As in any numpy array, the first element has index 0 and ranges are specified to include the first but before the last element. We can access elements according to their relative position to the end of the list by using negative indices. Index... | x = torch.arange(0, 10)
print(x)
print(x[-1])
print(x[1:3])
print(x[:-2]) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
When we have multidimensional tensors, indexing rules work the same way as numpy. | # make a 5D tensor
x = torch.rand(1, 2, 3, 4, 5)
print(f" shape of x[0]:{x[0].shape}")
print(f" shape of x[0][0]:{x[0][0].shape}")
print(f" shape of x[0][0][0]:{x[0][0][0].shape}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Flatten and reshape**There are various methods for reshaping tensors. It is common to have to express 2D data in 1D format. Similarly, it is also common to have to reshape a 1D tensor into a 2D tensor. We can achieve this with the ```.flatten()``` and ```.reshape()``` methods. | z = torch.arange(12).reshape(6, 2)
print(f"Original z: \n {z}")
# 2D -> 1D
z = z.flatten()
print(f"Flattened z: \n {z}")
# and back to 2D
z = z.reshape(3, 4)
print(f"Reshaped (3x4) z: \n {z}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
You will also see the ```.view()``` methods used a lot to reshape tensors. There is a subtle difference between ```.view()``` and ```.reshape()```, though for now we will just use ```.reshape()```. The documentation can be found in the appendix. **Squeezing tensors**When processing batches of data, you will quite often... | x = torch.randn(1, 10)
# printing the zeroth element of the tensor will not give us the first number!
print(x.shape)
print(f"x[0]: {x[0]}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Because of that pesky singleton dimension, x[0] gave us the first row instead! | # lets get rid of that singleton dimension and see what happens now
x = x.squeeze(0)
print(x.shape)
print(f"x[0]: {x[0]}")
# adding singleton dimensions works a similar way, and is often used when tensors
# being added need same number of dimensions
y = torch.randn(5, 5)
print(f"shape of y: {y.shape}")
# lets insert ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Permutation**Sometimes our dimensions will be in the wrong order! For example, we may be dealing with RGB images with dim [3x48x64], but our pipeline expects the colour dimension to be the last dimension i.e. [48x64x3]. To get around this we can use ```.permute()``` | # `x` has dimensions [color,image_height,image_width]
x = torch.rand(3, 48, 64)
# we want to permute our tensor to be [ image_height , image_width , color ]
x = x.permute(1, 2, 0)
# permute(1,2,0) means:
# the 0th dim of my new tensor = the 1st dim of my old tensor
# the 1st dim of my new tensor = the 2nd
# the 2nd di... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
You may also see ```.transpose()``` used. This works in a similar way as permute, but can only swap two dimensions at once. **Concatenation** In this example, we concatenate two matrices along rows (axis 0, the first element of the shape) vs. columns (axis 1, the second element of the shape). We can see that the first ... | # Create two tensors of the same shape
x = torch.arange(12, dtype=torch.float32).reshape((3, 4))
y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
#concatenate them along rows
cat_rows = torch.cat((x, y), dim=0)
# concatenate along columns
cat_cols = torch.cat((x, y), dim=1)
# printing outputs
print('C... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Conversion to Other Python Objects**Converting to a NumPy tensor, or vice versa, is easy. The converted result does not share memory. This minor inconvenience is actually quite important: when you perform operations on the CPU or on GPUs, you do not want to halt computation, waiting to see whether the NumPy package o... | x = torch.randn(5)
print(f"x: {x} | x type: {x.type()}")
y = x.numpy()
print(f"y: {y} | y type: {type(y)}")
z = torch.tensor(y)
print(f"z: {z} | z type: {z.type()}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
To convert a size-1 tensor to a Python scalar, we can invoke the item function or Python’s built-in functions. | a = torch.tensor([3.5])
a, a.item(), float(a), int(a) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Coding Exercise 2.3: Manipulating TensorsUsing a combination of the methods discussed above, complete the functions below. **Function A** This function takes in two 2D tensors $A$ and $B$ and returns the column sum of A multiplied by the sum of all the elmements of $B$ i.e. a scalar, e.g.,:$ A = \begin{bmatrix}1 & 1 \... | def functionA(my_tensor1, my_tensor2):
"""
This function takes in two 2D tensors `my_tensor1` and `my_tensor2`
and returns the column sum of
`my_tensor1` multiplied by the sum of all the elmements of `my_tensor2`,
i.e., a scalar.
Args:
my_tensor1: torch.Tensor
my_tensor2: torch.Tensor
Retuns:
... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_ea1718cb.py) ```tensor([24, 24])tensor([[ 0, 2], [ 1, 3], [ 2, -1], [ 3, 10]])tensor([[ 3, 2], [-1, 5]])tensor([ 1, -1, -1, 3, 2, ... | # @title Video 6: GPU vs CPU
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".fo... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
By default, when we create a tensor it will *not* live on the GPU! | x = torch.randn(10)
print(x.device) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
When using Colab notebooks by default will not have access to a GPU. In order to start using GPUs we need to request one. We can do this by going to the runtime tab at the top of the page. By following Runtime -> Change runtime type and selecting "GPU" from the Hardware Accelerator dropdown list, we can start playing w... | print(torch.cuda.is_available()) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
CUDA is an API developed by Nvidia for interfacing with GPUs. PyTorch provides us with a layer of abstraction, and allows us to launch CUDA kernels using pure Python. *NOTE I am assuming that GPU stuff might be covered in more detail on another day but there could be a bit more detail here.*In short, we get the power o... | def set_device():
device = "cuda" if torch.cuda.is_available() else "cpu"
if device != "cuda":
print("GPU is not enabled in this notebook. \n"
"If you want to enable it, in the menu under `Runtime` -> \n"
"`Hardware accelerator.` and select `GPU` from the dropdown menu")
else:
print("G... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Let's make some CUDA tensors! | # common device agnostic way of writing code that can run on cpu OR gpu
# that we provide for you in each of the tutorials
DEVICE = set_device()
# we can specify a device when we first create our tensor
x = torch.randn(2, 2, device=DEVICE)
print(x.dtype)
print(x.device)
# we can also use the .to() method to change th... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Operations between cpu tensors and cuda tensors**Note that the type of the tensor changed after calling ```.to()```. What happens if we try and perform operations on tensors on devices? | x = torch.tensor([0, 1, 2], device=DEVICE)
y = torch.tensor([3, 4, 5], device="cpu")
# Uncomment the following line and run this cell
# z = x + y | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
We cannot combine cuda tensors and cpu tensors in this fashion. If we want to compute an operation that combines tensors on different devices, we need to move them first! We can use the `.to()` method as before, or the `.cpu()` and `.cuda()` methods. Note that using the `.cuda()` will throw an error if CUDA is not enab... | x = torch.tensor([0, 1, 2], device=DEVICE)
y = torch.tensor([3, 4, 5], device="cpu")
z = torch.tensor([6, 7, 8], device=DEVICE)
# moving to cpu
x = x.to("cpu") # alternatively, you can use x = x.cpu()
print(x + y)
# moving to gpu
y = y.to(DEVICE) # alternatively, you can use y = y.cuda()
print(y + z) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Coding Exercise 2.4: Just how much faster are GPUs?Below is a simple function `simpleFun`. Complete this function, such that it performs the operations:- elementwise multiplication- matrix multiplicationThe operations should be able to perfomed on either the CPU or GPU specified by the parameter `device`. We will use ... | dim = 10000
iterations = 1
def simpleFun(dim, device):
"""
Args:
dim: integer
device: "cpu" or "cuda"
Returns:
Nothing.
"""
###############################################
## TODO for students: recreate the function, but
## ensure all computations happens on the `device`
raise NotImplemented... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_232a94a4.py) Sample output (depends on your hardware)```time taken for 1 iterations of simpleFun(10000, cpu): 23.74070time taken for 1 iterations of simpleFun(10000,... | # @title Video 7: Getting Data
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
When training neural network models you will be working with large amounts of data. Fortunately, PyTorch offers some great tools that help you organize and manipulate your data samples. | # Import dataset and dataloaders related packages
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, Grayscale | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Datasets**The `torchvision` package gives you easy access to many of the publicly available datasets. Let's load the [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset, which contains color images of 10 different classes, like vehicles and animals.Creating an object of type `datasets.CIFAR10` will automat... | # Download and load the images from the CIFAR10 dataset
cifar10_data = datasets.CIFAR10(
root="data", # path where the images will be stored
download=True, # all images should be downloaded
transform=ToTensor() # transform the images to tensors
)
# Print the number of samples in ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
We have 50000 samples loaded. Now let's take a look at one of them in detail. Each sample consists of an image and its corresponding label. | # Choose a random sample
random.seed(2021)
image, label = cifar10_data[random.randint(0, len(cifar10_data))]
print(f"Label: {cifar10_data.classes[label]}")
print(f"Image size: {image.shape}") | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Color images are modeled as 3 dimensional tensors. The first dimension corresponds to the channels (C) of the image (in this case we have RGB images). The second dimensions is the height (H) of the image and the third is the width (W). We can denote this image format as C × H × W. Coding Exercise 2.5: Display an image... | # TODO: Uncomment the following line to see the error that arises from the current image format
# plt.imshow(image)
# TODO: Comment the above line and fix this code by reordering the tensor dimensions
# plt.imshow(image.permute(...))
# plt.show() | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_b04bd357.py)*Example output:* | #@title Video 8: Train and Test
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}"... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Training and Test Datasets**When loading a dataset, you can specify if you want to load the training or the test samples using the `train` argument. We can load the training and test datasets separately. For simplicity, today we will not use both datasets separately, but this topic will be adressed in the next days. | # Load the training samples
training_data = datasets.CIFAR10(
root="data",
train=True,
download=True,
transform=ToTensor()
)
# Load the test samples
test_data = datasets.CIFAR10(
root="data",
train=False,
download=True,
transform=ToTensor()
)
# @title Video 9: Data Augmentation ... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Dataloader**Another important concept is the `Dataloader`. It is a wrapper around the `Dataset` that splits it into minibatches (important for training the neural network) and makes the data iterable. The `shuffle` argument is used to shuffle the order of the samples across the minibatches. | # Create dataloaders with
train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)
test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
*Reproducibility:* DataLoader will reseed workers following Randomness in multi-process data loading algorithm. Use `worker_init_fn()` and a `generator` to preserve reproducibility:```pythondef seed_worker(worker_id): worker_seed = torch.initial_seed() % 2**32 numpy.random.seed(worker_seed) random.seed(worker_seed)g... | # Load the next batch
batch_images, batch_labels = next(iter(train_dataloader))
print('Batch size:', batch_images.shape)
# Display the first image from the batch
plt.imshow(batch_images[0].permute(1, 2, 0))
plt.show() | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Transformations**Another useful feature when loading a dataset is applying transformations on the data - color conversions, normalization, cropping, rotation etc. There are many predefined transformations in the `torchvision.transforms` package and you can also combine them using the `Compose` transform. Checkout the... | def my_data_load():
###############################################
## TODO for students: load the CIFAR10 data,
## but as grayscale images and not as RGB colored.
raise NotImplementedError("Student exercise: fill in the missing code to load the data")
###############################################
## TODO... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_6052d728.py)*Example output:* --- Section 3: Neural Networks*Time estimate: ~1 hour 30 mins (excluding video)* Now it's time for you to create your first neural netw... | # @title Video 10: CSV Files
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".fo... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Section 3.1: Data LoadingFirst we need some sample data to train our network on. You can use the function below to generate an example dataset consisting of 2D points along two interleaving half circles. The data will be stored in a file called `sample_data.csv`. You can inspect the file directly in Colab by going to ... | # @title Generate sample data
# @markdown we used `scikit-learn` module
from sklearn.datasets import make_moons
# Create a dataset of 256 points with a little noise
X, y = make_moons(256, noise=0.1)
# Store the data as a Pandas data frame and save it to a CSV file
df = pd.DataFrame(dict(x0=X[:,0], x1=X[:,1], y=y))
df... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Now we can load the data from the CSV file using the Pandas library. Pandas provides many functions for reading files in various formats. When loading data from a CSV file, we can reference the columns directly by their names. | # Load the data from the CSV file in a Pandas DataFrame
data = pd.read_csv("sample_data.csv")
# Create a 2D numpy array from the x0 and x1 columns
X_orig = data[["x0", "x1"]].to_numpy()
# Create a 1D numpy array from the y column
y_orig = data["y"].to_numpy()
# Print the sizes of the generated 2D points X and the co... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Prepare Data for PyTorch**Now let's prepare the data in a format suitable for PyTorch - convert everything into tensors. | # Initialize the device variable
DEVICE = set_device()
# Convert the 2D points to a float32 tensor
X = torch.tensor(X_orig, dtype=torch.float32)
# Upload the tensor to the device
X = X.to(DEVICE)
print(f"Size X:{X.shape}")
# Convert the labels to a long interger tensor
y = torch.from_numpy(y_orig).type(torch.LongTe... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Section 3.2: Create a Simple Neural Network | # @title Video 11: Generating the Neural Network
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?b... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
For this example we want to have a simple neural network consisting of 3 layers:- 1 input layer of size 2 (our points have 2 coordinates)- 1 hidden layer of size 16 (you can play with different numbers here)- 1 output layer of size 2 (we want the have the scores for the two classes)During the course you will deal with ... | # Inherit from nn.Module - the base class for neural network modules provided by Pytorch
class NaiveNet(nn.Module):
# Define the structure of your network
def __init__(self):
super(NaiveNet, self).__init__()
# The network is defined as a sequence of operations
self.layers = nn.Sequential(
nn.L... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Check that your network works**Create an instance of your model and visualize it | # Create new NaiveNet and transfer it to the device
model = NaiveNet().to(DEVICE)
# Print the structure of the network
print(model) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Coding Exercise 3.2: Classify some samplesNow let's pass some of the points of our dataset through the network and see if it works. You should not expect the network to actually classify the points correctly, because it has not been trained yet. The goal here is just to get some experience with the data structures tha... | ## Get the samples
# X_samples = ...
# print("Sample input:\n", X_samples)
## Do a forward pass of the network
# output = ...
# print("\nNetwork output:\n", output)
## Predict the label of each point
# y_predicted = ...
# print("\nPredicted labels:\n", y_predicted) | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W1D1_BasicsAndPytorch/solutions/W1D1_Tutorial1_Solution_af8ae0ff.py) ```Sample input: tensor([[ 0.9066, 0.5052], [-0.2024, 1.1226], [ 1.0685, 0.2809], [ 0.6720, 0.5097], [ 0.8548, 0.5122]]... | # @title Video 12: Train the Network
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Now it is time to train your network on your dataset. Don't worry if you don't fully understand everything yet - we will cover training in much more details in the next days. For now, the goal is just to see your network in action!You will usually implement the `train` method directly when implementing your class `Naiv... | # @title Helper function to plot the decision boundary
# Code adapted from this notebook: https://jonchar.net/notebooks/Artificial-Neural-Network-with-Keras/
from pathlib import Path
def plot_decision_boundary(model, X, y, device):
# Transfer the data to the CPU
X = X.cpu().numpy()
y = y.cpu().numpy()
# Che... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
**Plot the loss during training**Plot the loss during the training to see how it reduces and converges. | plt.plot(np.linspace(1, len(losses), len(losses)), losses)
plt.xlabel("Epoch")
plt.ylabel("Loss")
# @title Visualize the training process
# @markdown ### Execute this cell!
!pip install imageio --quiet
!pip install pathlib --quiet
import imageio
from IPython.core.interactiveshell import InteractiveShell
from IPython.d... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Exercise 3.3: Tweak your NetworkYou can now play around with the network a little bit to get a feeling of what different parameters are doing. Here are some ideas what you could try:- Increase or decrease the number of epochs for training- Increase or decrease the size of the hidden layer- Add one additional hidden la... | # @title Video 14: XOR Widget
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".f... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Exclusive OR (XOR) logical operation gives a true (`1`) output when the number of true inputs is odd. That is, a true output result if one, and only one, of the inputs to the gate is true. If both inputs are false (`0`) or both are true or false output results. Mathematically speaking, XOR represents the inequality fun... | # @markdown ###Play with the parameters to solve XOR
from IPython.display import HTML
HTML('<iframe width="1020" height="660" src="https://playground.arashash.com/#activation=relu&batchSize=10&dataset=xor®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=&seed=0.91390&showTestData=false&d... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
--- Section 4: Ethics And Course Info | # @title Video 15: Ethics
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".forma... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Meet our lecturers:Week 1: the building blocks* [Konrad Kording](https://kordinglab.com)* [Andrew Saxe](https://www.saxelab.org/)* [Surya Ganguli](https://ganguli-gang.stanford.edu/)* [Ioannis Mitliagkas](http://mitliagkas.github.io/)* [Lyle Ungar](https://www.cis.upenn.edu/~ungar/)Week 2: making things work*... | # @title Video 18: Submission info
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
This is Darryl, the Deep Learning Dapper Lion, and he's here to teach you about content submission to airtable. At the end of each tutorial there will be an Airtable Submission Cell. Run the cell to generate the airtable submission button and click on it to submit your information to airtable.if it is the last tutorial... | # @title Airtable Submission Link
from IPython import display as IPyDisplay
IPyDisplay.HTML(
f"""
<div>
<a href= "{atform.url()}" target="_blank">
<img src="https://github.com/NeuromatchAcademy/course-content-dl/blob/main/tutorials/static/SurveyButton.png?raw=1"
alt="button link to survey" style="width:... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
--- Bonus - 60 years of Machine Learning Research in one Plotby [Hendrik Strobelt](http://hendrik.strobelt.com) (MIT-IBM Watson AI Lab) with support from Benjamin Hoover.In this notebook we visualize a subset* of 3,300 articles retreived from the AllenAI [S2ORC dataset](https://github.com/allenai/s2orc). We represent e... | # @title Import `altair` and load the data
!pip install altair vega_datasets --quiet
import requests
import altair as alt # altair is defining data visualizations
# Source data files
# Position data file maps ID to x,y positions
# original link: http://gltr.io/temp/ml_regexv1_cs_ma_citation+_99perc.pos_umap_cosine_100... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
Lets look at the Visualization. Each dot represents one paper. Close dots mean that the respective papers are closer related than distant ones. The color indicates the 5-year period of when the paper was published. The dot size indicates the citation count (within S2ORC corpus) as of July 2020. The view is **interactiv... | chart | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
QuestionsBy playing around, can you find some answers to the follwing questions?1. Can you find topical clusters? What cluster might occur because of a filtering error?2. Can you see a temporal trend in the data and clusters?2. Can you determine when deep learning methods started booming ?3. Can you find the key paper... | # @title Edit the `AUTHOR_FILTER` variable to full text search for authors.
AUTHOR_FILTER = "Rush " # @param space at the end means "word border"
### Don't ignore case when searching...
FLAGS = 0
### uncomment do ignore case
# FLAGS = re.IGNORECASE
## --- FILTER CODE.. make it your own ---
import re
data['issel'] =... | _____no_output_____ | CC-BY-4.0 | tutorials/W1D1_BasicsAndPytorch/student/W1D1_Tutorial1.ipynb | tmachnitzki/course-content-dl |
1 - e-posta baten histogramaAhalik eta funtzio gehien sortuko ditugu, azpiproblema bakoitza funtzio beten bidez adierazteko. Adibidez:* e-posta batetako testua, ilara zerrenda moduan (goiburua deskartatu)* hitz batetako ertzetatik puntuazio zeinuak kendu* hitz bat soilik karaktere alfabetikoez osotua ote dagoen | def eposta(bideizena,kodifikazioa="utf-8"):
with open(bideizena,encoding=kodifikazioa) as f:
for ilara in f:
if ilara == "\n" :
break
return list(f) | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
`string` modulua erabil dezakegu puntuazio zeinu guztiak lortzeko (seguruenik batenbat ahaztuko genuke...): | import string
string.punctuation
def hitza_garbitu(w):
return ... | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Prozesatzera goazen testuak ingelesez daudenez, `string.ascii_letters` erabil dezakegu: | string.ascii_letters
def soilik_alfa(w):
return True/False | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Aurreko funtzioak erabiliz, `histograma` funtzioa askozaz errazagoa izango da: | def histograma(bideizena):
h = {}
for ilara in eposta(bideizena):
for w in ilara.split():
w = hitza_garbitu(w)
if soilik_alfa(w) :
w = w.lower()
h[w] ...
return h | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
2 - histogramen *batura*Bi histograma ditugularik, beraien batura histograma bat izango da. Histograma horretan, batutako bi histogrametako hitz guztiak agertuko dira eta balioak hi histogrametako balioen batura izango da. | def hist_batura(h1,h2):
# h1 = h1 + h2
# return h1 + h2 | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
3 - histogramen normalizazioaAgerpen kopuruetatik maiztasunetara | def hist_norm(h):
...
return hnorm
h = ...
h_norm = hist_norm(h)
sum(h_norm.values()) == 1 | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
4 - Gai baten eredua sortuGai batetako eredua (histograma normalizatua) lortzeko, gai horretako korreo guztien histogramen batura kalkulatuko dugu eta azkenik histograma hori normalizatu:$$h_{gaia} = norm \left( \sum_{posta \in gaia}{h_{posta}} \right)$$Hau lortzeko ondoko pausuak emango ditugu:* Gai batetako entrenam... | karpeta = '/home/data/'
gaia = 'alt.atheism'
bideizena = karpeta + '20news-bydate/listas_train/' + gaia + '.txt' | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Fitxategi horretan, ilara bakoitzean entrenamenduko korreo baten bideizen **erlatiboa** agertzen da:```20news-bydate-train/alt.atheism/4996020news-bydate-train/alt.atheism/5106020news-bydate-train/alt.atheism/5111920news-bydate-train/alt.atheism/5112020news-bydate-train/alt.atheism/51121...```Ondoko kodeak, esaterako, ... | karpeta = '/home/data/'
gaia = 'alt.atheism'
bideizena = karpeta + '20news-bydate/listas_train/' + gaia + '.txt'
with open(bideizena,encoding="utf8") as f:
izenak = f.readlines() | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Baina bideizen horiek ez dira absolutuak (aurretik '/home/data/20news-bydate/') gehitu behar zaie eta amaieran duten `"\n"`-a kendu behar zaie. Sortu gai baten entrenamenduko bideizen absolutuen zerrenda bueltatuko duen funtzioa: | def gaiko_entrenamendu_bideizenak(gaia):
z = []
...
return z | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Sortu gai batetako eredua, hau da, histogramen batura normalizatua lortuko duen funtzioa: | def eredua(gaia):
H = {}
for bideizena in gaiko_entrenamendu_bideizenak(gaia):
# h = histograma(...)
# joan H-n h guztiak batzen
# H normalizatu
# emaitza buetatu | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
5 - Gai guztien ereduak sortu`20news-bydate/gaiak.txt` fitxategian gai guztiak ditugu. Sortu gai guztien izen zerrenda bueltatuko duen funtzioa: | def gai_zerrenda():
... | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Azkenik sortu gai bakoitzaren eredua. | def Ereduak():
# Eredu guztiak gordetzen dituen (hiztegien) hiztegia sortu
# E[gaia] = eredua(gaia)
return E | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
6 - Histograma normalizatuen arteko distantzia Gainjartze distantzia$$d(h_{a},h_{b}) = 1 - \sum_{w \in a}{\min(h_{a}(w),h_{b}(w))}$$ Euklidesen distantzia$$d(h_{a},h_{b}) = \sqrt{ \sum_{w \in a,b}{(h_{a}(w)-h_{b}(w))^2} }$$ korrelazio distantzia$$d(h_{a},h_{b}) = 1 - \sum_{w \in a}{h_{a}(w) \cdot h_{b}(w)}$$ | def dist_gainjartze(ha,hb):
def dist_euklides(ha,hb):
def dist_korrelazio(ha,hb): | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
7 - Histograma normalizatua sailkatu | def sailkatu(h,E,dist=dist_gainjartze):
#dist()
z = [ (d,gaia) , (d,gaia) , (d,gaia), ... ]
z.sort()
return z | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
8 - Errore tasa neurtuTest-eko posta elektroniko bat sailkatzen dugunean lehenengo posizioan postari dagokion gaia ez badago, sailkapen errore bat dugu. Errore tasa, $k$ errore kopurua eta $N$ posta kopuru arteko zatidura izango da:$$errore\_tasa = \frac{k}{N}$$ test-eko fitxategiakGai bat dugularik, adibidez `alt.at... | karpeta = '/home/data/'
gaia = 'alt.atheism'
#frogak egiteko
#bideizena = karpeta + '20news-bydate/listas_minitest/' + gaia + '.txt'
bideizena = karpeta + '20news-bydate/listas_test/' + gaia + '.txt'
def gaiko_test_bideizenak(gaia):
z = []
...
return z | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Errore tasa lortu | def errore_tasa(E,dist=dist_gainjartze):
#gai bakoitza zeharkatu
for gaia in ... :
#gaiko test-eko bideizenak zeharkatu
for bideizena in ...
#histograma normalizatua lortu
#sailkatu
#lehenengo gaia zuzena ez bada, errorea kontabilizatu
return k/N | _____no_output_____ | MIT | Laborategia/.ipynb_checkpoints/Laborategia 1-checkpoint.ipynb | mpenagar/Programazioaren-Oinarriak |
Classification metricsAuthor: Geraldine KlarenbergBased on the Google Machine Learning Crash Course TresholdsIn previous lessons, we have talked about using regression models to predict values. But sometimes we are interested in **classifying** things: "spam" vs "not spam", "bark" vs "not barking", etc. Logistic regr... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import pandas as pd
iris = load_iris()
X = iris.data
y = iris.target
df = pd.DataFrame(X,
columns = ['sepal_length(cm)',
'sepal_width(cm)',
'petal_lengt... | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Now extract the data we need and create the necessary dataframes again. | X = np.c_[X[:,0], X[:,3]]
y = []
for i in range(len(X)):
if i > 99:
y.append(1)
else:
y.append(0)
y = np.array(y)
plt.scatter(X[:,0], X[:,1], c = y) | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Create our test and train data, and run a model. The default classification threshold is 0.5. If the predicted probability is > 0.5, the predicted result is 'virgnica'. If it is < 0.5, the predicted result is 'not virginica'. | random = np.random.permutation(len(X))
x_train = X[random][30:]
x_test = X[random][:30]
y_train= y[random][30:]
y_test = y[random][:30]
from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(x_train,y_train) | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Instead of looking at the probabilities and the plot, like in the last lesson, let's run some classification metrics on the training dataset. If you use ".score", you get the mean accuracy. | log_reg.score(x_train, y_train) | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Let's predict values and see what this ouput means and how we can look at other metrics. | predictions = log_reg.predict(x_train)
predictions, y_train | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
There is a way to look at the confusion matrix. The output that is generated has the same structure as the confusion matrices we showed earlier:true positives (TP) | false positives (FP) -------|--------**false negatives (FN)** | **true negatives (TN)** | from sklearn.metrics import confusion_matrix
confusion_matrix(y_train, predictions) | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Indeed, for the accuracy calculation: we predicted 81 + 33 = 114 correct (true positives and true negatives), and 114/120 (remember, our training data had 120 points) = 0.95.There is also a function to calculate recall and precision:Since we also have a testing data set, let's see what the metrics look like for that. | from sklearn.metrics import recall_score
recall_score(y_train, predictions)
from sklearn.metrics import precision_score
precision_score(y_train, predictions) | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
And, of course, there are also built-in functions to check the ROC curve and AUC! For these functions, the inputs are the labels of the original dataset and the predicted probabilities (- not the predicted labels -> **why?**). Remember what the two columns mean? | proba_virginica = log_reg.predict_proba(x_train)
proba_virginica[0:10]
from sklearn.metrics import roc_curve
fpr_model, tpr_model, thresholds_model = roc_curve(y_train, proba_virginica[:,1])
fpr_model
tpr_model
thresholds_model | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Plot the ROC curve as follows | plt.plot(fpr_model, tpr_model,label='our model')
plt.plot([0,1],[0,1],label='random')
plt.plot([0,0,1,1],[0,1,1,1],label='perfect')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()
plt.show() | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
The AUC: | from sklearn.metrics import roc_auc_score
auc_model = roc_auc_score(y_train, proba_virginica[:,1])
auc_model | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
You can use the ROC and AUC metric to evaluate competing models. Many people prefer to use these metrics to analyze each model’s performance because it does not require selecting a threshold and helps balance true positive rate and false positive rate. Now let's do the same thing for our test data (but again, this data... | log_reg.score(x_test, y_test)
predictions = log_reg.predict(x_test)
predictions, y_test
confusion_matrix(y_test, predictions)
recall_score(y_test, predictions)
precision_score(y_test, predictions)
proba_virginica = log_reg.predict_proba(x_test)
fpr_model, tpr_model, thresholds_model = roc_curve(y_test, proba_virginica[... | _____no_output_____ | MIT | assets/nb-lessons/11_classification_metrics.ipynb | gklarenberg/ml-training-site |
Case: Impact of p_negative Situation: - 70% agent availability on weekdays and weekendsTask:- Evaluate Shift Coverage over p_negative: [.001, .0025, .005, .0075, .01, .02, .03, .05, .1, .2]- Evaluate Agent Satisfaction over p_negative: [.001, .0025, .005, .0075, .01, .02, .03, .05, .1, .2] | import abm_scheduling
from abm_scheduling import Schedule as Schedule
from abm_scheduling import Nurse as Nurse
import time
from datetime import datetime
import abm_scheduling.Log
from abm_scheduling.Log import Log as Log
import matplotlib.pylab as plt
%matplotlib inline
log = Log() | _____no_output_____ | MIT | C_Impact of p_negative.ipynb | GLopezMUZH/ABM_NurseSchedullingModel |
Define situation | num_nurses_per_shift = 5
num_nurses = 25
degree_of_agent_availability = 0.7
works_weekends = True
p_negatives = [.001, .0025, .005, .0075, .01, .02, .03, .05, .1, .2]
schedule = Schedule(num_nurses_needed=num_nurses_per_shift, is_random=True)
model = abm_scheduling.NSP_AB_Model()
nurses = model.generate_nurses(num_nur... | _____no_output_____ | MIT | C_Impact of p_negative.ipynb | GLopezMUZH/ABM_NurseSchedullingModel |
First Attemptbatch size 256 lr 1e-3 Import modules | %matplotlib inline
from __future__ import division
import sys
import os
os.environ['MKL_THREADING_LAYER']='GNU'
sys.path.append('../')
from Modules.Basics import *
from Modules.Class_Basics import * | /home/giles/anaconda2/lib/python2.7/site-packages/statsmodels/compat/pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
from pandas.core import datetools
Using Theano backend.
| MIT | Classifiers/Day1/Model_0_Basic_Features_256_1e-2_swish_mult2_200E.ipynb | GilesStrong/Kaggle_HiggsML |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.