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 |
|---|---|---|---|---|---|
Run the following cell to get the first data set from the list. This will return a DataFrame and assign it to the variable d2: | d2 = pixiedust.sampleData(1) | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Pass the sample data set (d2) into the display() API: | display(d2) | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
You can also download data from a CSV file into a DataFrame which you can use with the display() API: | d3 = pixiedust.sampleData("https://openobjectstore.mybluemix.net/misc/milliondollarhomes.csv") | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
PixieDust LogPixieDust comes complete with logging to help you troubleshoot issues. You can find more info at https://ibm-watson-data-lab.github.io/pixiedust/logging.html. To access the log run the following cell: | % pixiedustLog -l debug | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
Environment Info.The following cells will print out information related to your notebook environment. | %%scala
val __scala_version = util.Properties.versionNumberString
import platform
print('PYTHON VERSON = ' + platform.python_version())
print('SPARK VERSON = ' + sc.version)
print('SCALA VERSON = ' + __scala_version) | _____no_output_____ | Apache-2.0 | notebook/Intro to PixieDust.ipynb | jordangeorge/pixiedust |
twoDim> Code for a 2-D problem. | #hide
from nbdev.showdoc import * | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
2 dimensional case (PDE)We consider the following 2-D problem:$$\nabla\cdot\left(\kappa(x)\nabla u(x)\right)=f(x) \quad\forall x\in D=[0,1]^{2}$$$$u(x)=0\quad\forall x\in\partial D$$where here $f$ is again a random forcing term, assumed to be a GP in this work. Variational formulationThe variational formulation is gi... | #export
from dolfin import *
import numpy as np
from scipy import integrate
from scipy.spatial.distance import cdist
from scipy.linalg import sqrtm
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import spsolve
from scipy.interpolate import interp1d
from joblib import Parallel, delayed
import multiprocessi... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`mean_assembler` takes in the mesh size `h` and the mean function `f_bar` for the forcing and computes the mean of the approximate statFEM prior, returning this as a FEniCS function. > Important: `mean_assembler` requires `f_bar` to be represented as a FEniCS function/expression/constant. Let's check that this is worki... | h = 0.1
f_bar = Constant(1.0)
μ = mean_assembler(h,f_bar)
μ
# check the type of μ
assert type(μ) == function.function.Function | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
Let's plot $\mu$: | #hide_input
# use FEniCS to plot μ
plot(μ)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.title(r'Plot of statFEM mean for $h=%.2f$'%h)
plt.show() | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
statFEM prior covarianceWe will also utilise FEniCS again to obtain an approximation of our statFEM covariance function.The statFEM covariance can be approximated as follows:$$c_u^{\text{FEM}}(x,y)\approx\sum_{i,j=1}^{J}\varphi_{i}(x)Q_{ij}\varphi_{j}(y)$$where $Q=A^{-1}MC_{f}M^{T}A^{-T}$ and where the $\{\varphi_{i}\... | #export
def kernMat(k,grid,parallel=True,translation_inv=False):
"Function to compute the covariance matrix $K$ corresponding to the covariance kernel $k$ on a grid. This matrix has $ij$-th entry $K_{ij}=k(x_i,x_j)$ where $x_i$ is the $i$-th point of the grid."
# get the length of the grid
n = grid.shape[0]... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
> Note: This function takes in two optional boolean arguments `parallel` and `translation_inv`. The first of these specifies whether or not the cov matrix should be computed in parallel and the second specifies whether or not the cov kernel is translation invariant. If it is, the covariance matrix is computed more effi... | # set up the kernel function
# set up tolerance for comparison
tol = 1e-16
def k(x,y):
if (np.abs(x-y) < tol).all():
# x == y within the tolerance
return 1.0
else:
# x != y within the tolerance
return 0.0
# set up grid
n = 21
x_range = np.linspace(0,1,n)
grid = np.array([[x,y] f... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
We now create a function `BigPhiMat` to utilise FEniCS to efficiently compute the matrix $\boldsymbol{\Phi}$ defined above. | #export
def BigPhiMat(J,grid):
"Function to compute the $\Phi$ matrix."
# create the FE mesh and function space
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh,'Lagrange',1)
# get the tree for the mesh
tree = mesh.bounding_box_tree()
# set up a function to compute the ith column of Phi cor... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`BigPhiMat` takes in two arguments: `J`, which controls the FE mesh size ($h=1/J^{2}$), and `grid` which is the grid in the definition of $\boldsymbol{\Phi}$. `BigPhiMat` returns $\boldsymbol{\Phi}$ as a sparse `csr_matrix` for memory efficiency. > Note: Note that since FEniCS works with the FE functions corresponding ... | #export
# function to assemble the fem covariance
def cov_assembler(J,k_f,grid,parallel,translation_inv):
"Function to assemble the approximate FEM covariance matrix on the reference grid."
# set up mesh and function space
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh,'Lagrange',1)
# s... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`cov_assembler` takes in several arguments which are explained below:- `J`: controls the FE mesh size ($h=1/J^{2})$- `k_f`: the covariance function for the forcing $f$- `grid`: the reference grid where the FEM cov matrix should be computed on- `parallel`: boolean argument indicating whether the intermediate computation... | # set up kernel function for forcing
f_bar = Constant(1.0)
l_f = 0.4
σ_f = 0.1
def k_f(x):
return (σ_f**2)*np.exp(-(x**2)/(2*(l_f**2)))
# set up grid
n = 21
x_range = np.linspace(0,1,n)
grid = np.array([[x,y] for x in x_range for y in x_range])
# get the statFEM grid for a particular choice of J
J = 10
Σ = cov_... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
Let's plot a heatmap of the statFEM cov matrix: | #hide_input
sns.heatmap(Σ,cbar=True,
annot=False,
xticklabels=False,
yticklabels=False,
cmap=cm.viridis)
plt.title('Heat map of statFEM covariance matrix')
plt.show() | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
> Note: that the banded structure in the above statFEM covariance matrix is due to the internal ordering of the FE grid in FEniCS. statFEM posterior meanThe statFEM posterior from incorporating sensor readings has the same form as given in oneDim. We will thus require very similar code as to the 1-D case. We start by ... | #export
def m_post(x,m,c,v,Y,B):
"This function evaluates the posterior mean at the point $x$."
m_vect = np.array([m(y_i) for y_i in Y]).flatten()
c_vect = c(x).flatten()
# compute the update term
update = c_vect @ np.linalg.solve(B,m_vect-v)
# return m_post
return (m(x) - update) | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`m_post` takes in several arguments which are explained below:- `x`: point where the posterior mean will be evaluated- `m`: function which computes the prior mean at a given point y- `c`: function which returns the vector (c(x,y)) for y in Y (note: c is the prior covariance function)- `v`: vector of noisy sensor readin... | #export
def sample_gp(n_sim,m,k,grid,par,trans,tol=1e-9):
"Function to sample a GP with mean $m$ and cov $k$ on a grid."
# get length of grid
d = len(grid)
# construct mean vector
μ = np.array([m(x) for x in grid]).reshape(d,1)
# construct covariance matrix
Σ = kernMat(k,grid,... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`sample_gp` takes in several arguments which are explained below:- `n_sim`: number of trajectories to be sampled- `m`: mean function for the GP- `k`: cov function for the GP- `grid`: grid of points on which to sample the GP- `par`: boolean argument indicating whether the computation of the cov matrix should be done in ... | #hide_input
n = 41
x_range = np.linspace(0,1,n)
grid = np.array([[x,y] for x in x_range for y in x_range])
# set up mean
def m(x):
return 0.0
np.random.seed(23534)
samples = sample_gp(2,m,k,grid,True,False)
sample_1 = samples[:,0].flatten()
sample_2 = samples[:,1].flatten()
vmin = min(sample_1.min(),sample_2.mi... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
Let's also quickly generate 2 realisations for the kernel `k_f` above: | #hide_input
np.random.seed(534)
samples = sample_gp(2,m,k_f,grid,False,True)
sample_1 = samples[:,0].flatten()
sample_2 = samples[:,1].flatten()
vmin = min(sample_1.min(),sample_2.min())
vmax = max(sample_1.max(),sample_2.max())
cmap = cm.jet
norm = colors.Normalize(vmin=vmin,vmax=vmax)
x = grid[:,0].flatten()
y = g... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
The next bit of code we require is code to generate noisy sensor readings from our system. We write the function `gen_sensor` for this purpose. | #export
def gen_sensor(ϵ,m,k,Y,J,par,trans,tol=1e-9,require=False):
"Function to generate noisy sensor readings of the solution u on a sensor grid Y."
# get number of sensors from the sensor grid Y
s = len(Y)
# create FEM space and grid
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`gen_sensor` takes in several arguments which are explained below:- `ϵ`: controls the amount of sensor noise- `m`: mean function for the forcing f- `k`: cov function for the forcing f- `Y`: vector of sensor locations- `J`: controls the FE mesh size ($h=1/J^{2}$)- `par`: boolean argument indicating whether the computati... | # set up mean function for forcing
def m_f(x):
return 1.0
# set up sensor grid and sensor noise level
ϵ = 0.2
s = 25
s_sqrt = int(np.round(np.sqrt(s)))
Y_range = np.linspace(0.01,0.99,s_sqrt)
Y = np.array([[x,y] for x in Y_range for y in Y_range])
J_fine = 100 # FE mesh size to compute solution on
# generate the ... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
We now require code which will create the matrix $C_Y,h$ and the function $\mathbf{c}^{(h)}$ required for the statFEM posterior mean. We will create the function `fem_cov_assembler_post` for this purpose. | #export
def fem_cov_assembler_post(J,k_f,Y,parallel,translation_inv):
"Function to create the matrix $C_{Y,h}$ and the vector function $c^{(h)}$ required for the statFEM posterior mean."
# set up mesh and function space
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh,'Lagrange',1)
tree = mesh... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`fem_cov_assembler_post` takes in several arguments which are explained below:- `J`: controls the FE mesh size ($h=1/J^2$)- `k_f`: the covariance function for the forcing $f$- `Y`: vector of sensor locations- `parallel`: boolean argument indicating whether the computation of the forcing cov mat should be done in parall... | #export
def m_post_fem_assembler(J,f_bar,k_f,ϵ,Y,v_dat,par=False,trans=True):
"Function to assemble the statFEM posterior mean function."
# get number of sensors
s = len(Y)
# set up mesh and function space
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh,'Lagrange',1)
# set u... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`m_post_fem_assembler` takes in several arguments which are explained below:- `J`: controls the FE mesh size ($h=1/J^{2}$)- `f_bar`: the mean function for the forcing $f$- `k_f`: the covariance function for the forcing $f$- `ϵ`: controls the amount of sensor noise- `Y`: vector of sensor locations- `v_dat`: vector of no... | J = 20
f_bar = Constant(1.0)
m_post_fem = m_post_fem_assembler(J,f_bar,k_f,ϵ,Y,v_dat)
# compute posterior mean at a location x in D
x = np.array([0.3,0.1])
m_post_fem(x) | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
statFEM posterior covarianceThe form of the statFEM posterior covariance remains the same as given in oneDim. Thus, we require very similar code as to the 1-D case. We start by creating a function `c_post` which evaluates the posterior covariance at a given point. | #export
def c_post(x,y,c,Y,B):
"This function evaluates the posterior covariance at $(x,y)$"
# compute vectors c_x and c_y:
c_x = np.array([c(x,y_i) for y_i in Y])
c_y = np.array([c(y_i,y) for y_i in Y])
# compute update term
update = c_x @ np.linalg.solve(B,c_y)
# return c_po... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`c_post` takes in several arguments which are explained below:- `x`,`y`: points to evaluate the covariance at- `c`: function which returns the prior covariance at any given pair $(x,y)$- `Y`: vector of sensor locations- `B`: the matrix $\epsilon^{2}I+C_{Y}$ to be inverted in order to obtain the posterior To compare the... | #export
def post_fem_cov_assembler(J,k_f,grid,Y,parallel,translation_inv):
"Function which assembles the matrices $Σ_X$ ,$Σ_{XY}$, and $Σ_Y$ required for the statFEM posterior covariance."
# set up mesh and function space
mesh = UnitSquareMesh(J,J)
V = FunctionSpace(mesh,'Lagrange',1)
# set up... | _____no_output_____ | Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
`post_fem_cov_assembler` takes in several arguments which are explained below:- `J`: controls the FE mesh size ($h=1/J^2$)- `k_f`: the covariance function for the forcing $f$- `grid`: the fixed reference grid $\{x_{i}\}_{i=1}^{N}$ on which to assemble the posterior cov mat- `Y`: vector of sensor locations.- `parallel`:... | #export
def c_post_fem_assembler(J,k_f,grid,Y,ϵ,par,trans):
"Function to assemble the statFEM posterior cov mat on a reference grid specified by grid."
# use post_fem_cov_assembler to get the sigma matrices needed for posterior cov mat
Σ_Y, Σ_X, Σ_XY = post_fem_cov_assembler(J,k_f,grid,Y,parallel=par,transl... | Converted 00_oneDim.ipynb.
Converted 01_twoDim.ipynb.
Converted index.ipynb.
Converted oneDim_prior_results.ipynb.
| Apache-2.0 | 01_twoDim.ipynb | YanniPapandreou/statFEM |
Regresión lineal**Temas Selectos de Modelación Numérica** Facultad de Ciencias, UNAM Semestre 2021-2En este notebook aprenderemos como hacer una regresión lineal por el método de mínimos cuadrados y por el método matricial. No olvides resolver los ejercicios de tarea al final del notebook. Entrega tu solución en un no... | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | Apache-2.0 | otros/06_reg_lineal.ipynb | anakarinarm/TallerModNum |
1. Mínimos cuadrados Ajuste de rectas de la forma $y=mx+b$ por mínimos cuadrados. La idea detrás de este método es que queremos encontrar la pendiente $m$ y la ordenada al origen $b$ que nos dan la recta que minimiza la suma de los cuadrados de las distancias entre los puntos (digamos, datos) y la recta ajustada:) También podemos hacer regresiones lineales usando el método matricial. Recordemos que en una regresión lineal queremos ajustar n... | X_mat = np.vstack((np.ones(len(X)), X)).T # en este caso usamos la función vstack
# y el método T (transponer) para obtener las dimensiones
# adecuadas | _____no_output_____ | Apache-2.0 | otros/06_reg_lineal.ipynb | anakarinarm/TallerModNum |
Con un poco de álgebra lineal y el objetivo de minimizar el error cuadrático medio del sistema de ecuaciones lineales llegamos a que podemos calcular el valor de los parámetros $\hat{\beta}=(\beta_0, \beta_1)$ de la forma:$$\hat{\beta}=(X^T. X)^{-1}. X^T. Y$$ Podemos implementar esta ecuación usando las funciones para ... | beta = np.linalg.inv(X_mat.T.dot(X_mat)).dot(X_mat.T).dot(Y)
print('La pendiente beta_1 es %f y la ordenada beta_0 es %f' %(beta[1], beta[0])) | La pendiente beta_1 es 2.000000 y la ordenada beta_0 es 2.756253
| Apache-2.0 | otros/06_reg_lineal.ipynb | anakarinarm/TallerModNum |
que son los mismos valores para la pendiente y ordenada al origen que encontramos usando la función `reg_lineal`. Ahora usemos estos parámetros para estimar los valores de Y: | Y_mat = X_mat.dot(beta)
plt.plot(X,Y,'o', label='Y')
plt.plot(X,Y_mat,'-',label='regresión método matricial' )
plt.xlabel('x')
plt.ylabel('y=f(x)')
plt.legend()
plt.show() | _____no_output_____ | Apache-2.0 | otros/06_reg_lineal.ipynb | anakarinarm/TallerModNum |
3. Ejemplo usando ambos métodos | X = np.linspace(1,10)
Y = 1 + 2*X + 3*X**2 + 20*np.random.randn(1)
# Método matricial - ahora tenemos otro término, Xˆ2
X_mat = np.vstack((np.ones(len(X)), X, X**2)).T
beta = np.linalg.inv(X_mat.T.dot(X_mat)).dot(X_mat.T).dot(Y)
Y_mat = X_mat.dot(beta)
# Función reg_lineal
m, b = reg_lineal(X,Y)
Y2 = m*X+b
plt.plot(... | _____no_output_____ | Apache-2.0 | otros/06_reg_lineal.ipynb | anakarinarm/TallerModNum |
Neuromatch Academy: Week 3, Day 4, Tutorial 1 Deep Learning: Decoding Neural Responses**Content creators**: Jorge A. Menendez, Carsen Stringer**Content reviewers**: Roozbeh Farhoodi, Madineh Sarvestani, Kshitij Dwivedi, Spiros Chavlis, Ella Batty, Michael Waskom --- Tutorial ObjectivesIn this tutorial, we'll use dee... | #@title Video 1: Decoding from neural data using feed-forward networks in pytorch
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="SlrbMvvBOzM", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
--- Setup | import os
import numpy as np
import torch
from torch import nn
from torch import optim
import matplotlib as mpl
from matplotlib import pyplot as plt
#@title Data retrieval and loading
import hashlib
import requests
fname = "W3D4_stringer_oribinned1.npz"
url = "https://osf.io/683xc/download"
expected_md5 = "436599dfd... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
--- Section 1: Load and visualize dataIn the next cell, we have provided code to load the data and plot the matrix of neural responses.Next to it, we plot the tuning curves of three randomly selected neurons. | #@title
#@markdown Execute this cell to load and visualize data
# Load data
resp_all, stimuli_all = load_data() # argument to this function specifies bin width
n_stimuli, n_neurons = resp_all.shape
print(f'{n_neurons} neurons in response to {n_stimuli} stimuli')
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(2 * 6,... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
We will split our data into a training set and test set. In particular, we will have a training set of orientations (`stimuli_train`) and the corresponding responses (`resp_train`). Our testing set will have held-out orientations (`stimuli_test`) and the corresponding responses (`resp_test`). | #@title
#@markdown Execute this cell to split into training and test sets
# Set random seeds for reproducibility
np.random.seed(4)
torch.manual_seed(4)
# Split data into training set and testing set
n_train = int(0.6 * n_stimuli) # use 60% of all data for training set
ishuffle = torch.randperm(n_stimuli)
itrain = is... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
--- Section 2: Deep feed-forward networks in *pytorch* We'll now build a simple deep neural network that takes as input a vector of neural responses and outputs a single number representing the decoded stimulus orientation.To keep things simple, we'll build a deep network with **one** hidden layer. See the appendix for... | class DeepNet(nn.Module):
"""Deep Network with one hidden layer
Args:
n_inputs (int): number of input units
n_hidden (int): number of units in hidden layer
Attributes:
in_layer (nn.Linear): weights and biases of input layer
out_layer (nn.Linear): weights and biases of output layer
"""
def ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
The next cell contains code for initializing and running this network. We use it to decode stimulus orientation from a vector of neural responses to the very first stimulus. Note that when the initialized network class is called as a function on an input (e.g. `net(r)`), its `.forward()` method is called. This is a spe... | # Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)
# Initialize a deep network with M=200 hidden units
net = DeepNet(n_neurons, 200)
# Get neural responses (r) to and orientation (ori) to one stimulus in dataset
r, ori = get_data(1, resp_train, stimuli_train) # using helper function get_da... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
--- Section 2.2: Activation functions | #@title Video 2: Nonlinear activation functions
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="JAdukDCQALA", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
Note that the deep network we constructed above comprises solely **linear** operations on each layer: each layer is just a weighted sum of the elements in the previous layer. It turns out that linear hidden layers like this aren't particularly useful, since a sequence of linear transformations is actually essentially t... | class DeepNetReLU(nn.Module):
def __init__(self, n_inputs, n_hidden):
super().__init__() # needed to invoke the properties of the parent class nn.Module
self.in_layer = nn.Linear(n_inputs, n_hidden) # neural activity --> hidden units
self.out_layer = nn.Linear(n_hidden, 1) # hidden units --> output
d... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_5bdc2033.py) You should see that the decoded orientation is 0.13 $^{\circ}$ while the true orientation is 139.00 $^{\circ}$. --- Section 3: Loss functions and gradient d... | #@title Video 3: Loss functions & gradient descent
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="aEtKpzEuviw", width=854, height=480, fs=1)
print("Video available at https://youtu.be/" + video.id)
video | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
Section 3.1: Loss functionsBecause the weights of the network are currently randomly chosen, the outputs of the network are nonsense: the decoded stimulus orientation is nowhere close to the true stimulus orientation. We'll shortly write some code to change these weights so that the network does a better job of decodi... | # Set random seeds for reproducibility
np.random.seed(1)
torch.manual_seed(1)
# Initialize a deep network with M=20 hidden units
net = DeepNetReLU(n_neurons, 20)
# Get neural responses to first 20 stimuli in the data set
r, ori = get_data(20, resp_train, stimuli_train)
# Decode orientation from these neural response... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_0e539ef5.py) You should see a mean squared error of 42943.75. --- Section 3.2: Optimization with gradient descentOur goal is now to modify the weights to make the mean s... | def train(net, loss_fn, train_data, train_labels, n_iter=50, learning_rate=1e-4):
"""Run gradient descent to opimize parameters of a given network
Args:
net (nn.Module): PyTorch network whose parameters to optimize
loss_fn: built-in PyTorch loss function to minimize
train_data (torch.Tensor): n_train x... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial1_Solution_8f827dbe.py)*Example output:* --- Section 4: Evaluating model performance Section 4.1: Generalization performance with test dataNote that gradient descent is essentiall... | #@title
#@markdown Execute this cell to evaluate and plot test error
out = net(resp_test) # decode stimulus orientation for neural responses in testing set
ori = stimuli_test # true stimulus orientations
test_loss = loss_fn(out, ori) # MSE on testing set (Hint: use loss_fn initialized in previous exercise)
plt.plo... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
**PyTorch Note**:An important thing to note in the code snippet for plotting the decoded orientations is the `.detach()` method. The PyTorch `nn.Module` class is special in that, behind the scenes, each of the variables inside it are linked to each other in a computational graph, for the purposes of automatic different... | #@title
#@markdown Execute this cell to plot decoding error
out = net(resp_test) # decode stimulus orientation for neural responses in testing set
ori = stimuli_test # true stimulus orientations
error = out - ori # decoding error
plt.plot(ori, error.detach(), '.') # plot decoding error as a function of true ori... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
Think In the cell below, we will plot the *decoding error* for each neural response in the testing set. The decoding error is defined as the decoded stimulus orientation minus true stimulus orientation\begin{equation} \text{decoding error} = y^{(n)} - \tilde{y}^{(n)}\end{equation}In particular, we plot decoding error... | # Deep network for classification
class DeepNetSoftmax(nn.Module):
"""Deep Network with one hidden layer, for classification
Args:
n_inputs (int): number of input units
n_hidden (int): number of units in hidden layer
n_classes (int): number of outputs, i.e. number of classes to output
probabiliti... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
What should our loss function now be? Ideally, we want the probabilities outputted by our network to be such that the probability of the true stimulus class is high. One way to formalize this is to say that we want to maximize the *log* probability of the true stimulus class $\tilde{y}^{(n)}$ under the class probabilit... | def decode_orientation(n_classes, train_data, train_labels, test_data, test_labels):
""" Initialize, train, and test deep network to decode binned orientation from neural responses
Args:
n_classes (scalar): number of classes in which to bin orientation
train_data (torch.Tensor): n_train x n_neurons tensor ... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D4_DeepLearning1/student/W3D4_Tutorial1.ipynb | florgf88/course-content |
Load data | from sensor import create_raw_data_file
create_raw_data_file()
# Read all data from parquet file
data = pd.read_parquet("raw_data_all.parquet")
# For simplicity, select sensor 3
data = data[data["sensor"] == "node_03"]
# Replace 0-measurements with missing
data.loc[data["Leq"] == 0, "Leq"] = None
# For simplicity, d... | _____no_output_____ | CC-BY-4.0 | martin/TimeSeriesModelling.ipynb | marhoy/Koopen |
Linear model | model_formula = "C(dow) + C(hour):C(dow)" # week"
# model_formula = "C(workday) + C(workhour):C(workday)"
linmodel = smf.ols(formula=f"Leq ~ {model_formula}", data=train).fit()
linmodel_resid = train_test["Leq"] - linmodel.predict(train_test)
linmodel.summary()
fig = make_subplots(rows=2, cols=1, shared_xaxes=True)
fi... | _____no_output_____ | CC-BY-4.0 | martin/TimeSeriesModelling.ipynb | marhoy/Koopen |
ARX model | fig, ax = plt.subplots(2, 1, figsize=(10, 10))
fig = sm.graphics.tsa.plot_acf(linmodel.resid, lags=30, ax=ax[0])
fig = sm.graphics.tsa.plot_pacf(linmodel.resid, lags=30, ax=ax[1])
exog_train = patsy.dmatrix(model_formula, train)
exog_test = patsy.dmatrix(model_formula, test)
lags = math.ceil(pd.Timedelta("4min") / trai... | _____no_output_____ | CC-BY-4.0 | martin/TimeSeriesModelling.ipynb | marhoy/Koopen |
Model comparison | fig = make_subplots(rows=1, cols=1, shared_xaxes=True)
fig.add_trace(go.Scatter(x=train_test.index, y=train_test["Leq"], name="Measured"), row=1, col=1)
fig.add_trace(go.Scatter(x=train_test.index, y=linmodel.predict(train_test), name="LinModel"), row=1, col=1)
fig.add_trace(go.Scatter(x=train_test.index, y=arxmodel_pr... | _____no_output_____ | CC-BY-4.0 | martin/TimeSeriesModelling.ipynb | marhoy/Koopen |
ARX with dynamic forecasting | exog = patsy.dmatrix(model_formula, train_test)
model = AutoReg(endog=train_test["Leq"], lags=lags, exog=exog).fit()
forecast_period = pd.Timedelta("3hour")
t = train_test.index[0] + forecast_period
preds = pd.Series(dtype=float)
while t < train_test.index[-1] - forecast_period:
preds = preds.append(model.predict(... | _____no_output_____ | CC-BY-4.0 | martin/TimeSeriesModelling.ipynb | marhoy/Koopen |
Python - Writing Your First Python Code! Welcome! This notebook will teach you the basics of the Python programming language. Although the information presented here is quite basic, it is an important foundation that will help you read and write Python code. By the end of this notebook, you'll kn... | # Try your first Python output
print('Hello, Python!') | Hello, Python!
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
After executing the cell above, you should see that Python prints Hello, Python!. Congratulations on running your first Python code! [Tip:] print() is a function. You passed the string 'Hello, Python!' as an argument to instruct Python on what to print. What version of Python are we using? There are two popular... | # Check the Python Version
import sys
print(sys.version) | 3.6.6 | packaged by conda-forge | (default, Oct 12 2018, 14:43:46)
[GCC 7.3.0]
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
[Tip:] sys is a built-in module that contains many system-specific parameters and functions, including the Python version in use. Before using it, we must explictly import it. Writing comments in Python In addition to writing code, note that it's always a good idea to add comments to your code. It will help oth... | # Practice on writing comments
print('Hello, Python!') # This line prints a string
# print('Hi') | Hello, Python!
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
After executing the cell above, you should notice that This line prints a string did not appear in the output, because it was a comment (and thus ignored by Python). The second line was also not executed because print('Hi') was preceded by the number sign () as well! Since this isn't an explanatory comment from ... | # Print string as error message
frint("Hello, Python!") | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
The error message tells you: where the error occurred (more useful in large notebook cells or scripts), and what kind of error it was (NameError) Here, Python attempted to run the function frint, but could not determine what frint is since it's not a built-in function and it has not been previously defined by u... | # Try to see build in error message
print("Hello, Python!) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Does Python know about your error before it runs your code? Python is what is called an interpreted language. Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution. In contrast, Python interprets your script line by line as it executes ... | # Print string and error to see the running order
print("This will be printed")
frint("This will cause an error")
print("This will NOT be printed") | This will be printed
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Exercise: Your First Program Generations of programmers have started their coding careers by simply printing "Hello, world!". You will be following in their footsteps.In the code cell below, use the print() function to print out the phrase: Hello, world! | # Write your code below and press Shift+Enter to execute
print("Hello, world!") | Hello, world!
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!")--> Now, let's enhance your code with a comment. In the code cell below, print out the phrase: Hello, world! and comment it with the phrase Print the traditional hello world all in one line of code. | # Write your code below and press Shift+Enter to execute
print("Hello, world!") # Print the traditional hello world | Hello, world!
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!") Print the traditional hello world--> Types of objects in Python Python is an object-oriented language. There are many different types of objects in Python. Let's start with the most common object types: strings, integers and float... | # Integer
11
# Float
2.14
# String
"Hello, Python 101!" | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
You can get Python to tell you the type of an expression by using the built-in type() function. You'll notice that Python refers to integers as int, floats as float, and character strings as str. | # Type of 12
type(12)
# Type of 2.14
type(2.14)
# Type of "Hello, Python 101!"
type("Hello, Python 101!") | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
In the code cell below, use the type() function to check the object type of 12.0. | # Write your code below. Don't forget to press Shift+Enter to execute the cell
type(12.0) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:type(12.0)--> Integers Here are some examples of integers. Integers can be negative or positive numbers: We can verify this is the case by using, you guessed it, the type() function: | # Print the type of -1
type(-1)
# Print the type of 4
type(4)
# Print the type of 0
type(0) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Floats Floats represent real numbers; they are a superset of integer numbers but also include "numbers with decimals". There are some limitations when it comes to machines representing real numbers, but floating point numbers are a good representation in most cases. You can learn more about the specifics of floats for... | # Print the type of 1.0
type(1.0) # Notice that 1 is an int, and 1.0 is a float
# Print the type of 0.5
type(0.5)
# Print the type of 0.56
type(0.56)
# System settings about float type
sys.float_info | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Converting from one object type to a different object type You can change the type of the object in Python; this is called typecasting. For example, you can convert an integer into a float (e.g. 2 to 2.0).Let's try it: | # Verify that this is an integer
type(2) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Converting integers to floatsLet's cast integer 2 to float: | # Convert 2 to a float
float(2)
# Convert integer 2 to a float and check its type
type(float(2)) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
When we convert an integer into a float, we don't really change the value (i.e., the significand) of the number. However, if we cast a float into an integer, we could potentially lose some information. For example, if we cast the float 1.1 to integer we will get 1 and lose the decimal information (i.e., 0.1): | # Casting 1.1 to integer will result in loss of information
int(1.1) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Converting from strings to integers or floats Sometimes, we can have a string that contains a number within it. If this is the case, we can cast that string that represents a number into an integer using int(): | # Convert a string into an integer
int('1') | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
But if you try to do so with a string that is not a perfect match for a number, you'll get an error. Try the following: | # Convert a string into an integer with error
int('1 or 2 people') | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
You can also convert strings containing floating point numbers into float objects: | # Convert the string "1.2" into a float
float('1.2') | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
[Tip:] Note that strings can be represented with single quotes ('1.2') or double quotes ("1.2"), but you can't mix both (e.g., "1.2'). Converting numbers to strings If we can convert strings to numbers, it is only natural to assume that we can convert numbers to strings, right? | # Convert an integer to a string
str(1) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
And there is no reason why we shouldn't be able to make floats into strings as well: | # Convert a float to a string
str(1.2) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Boolean data type Boolean is another important type in Python. An object of type Boolean can take on one of two values: True or False: | # Value true
True | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Notice that the value True has an uppercase "T". The same is true for False (i.e. you must use the uppercase "F"). | # Value false
False | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
When you ask Python to display the type of a boolean object it will show bool which stands for boolean: | # Type of True
type(True)
# Type of False
type(False) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
We can cast boolean objects to other data types. If we cast a boolean with a value of True to an integer or float we will get a one. If we cast a boolean with a value of False to an integer or float we will get a zero. Similarly, if we cast a 1 to a Boolean, you get a True. And if we cast a 0 to a Boolean we will get a... | # Convert True to int
int(True)
# Convert 1 to boolean
bool(1)
# Convert 0 to boolean
bool(0)
# Convert True to float
float(True) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Exercise: Types What is the data type of the result of: 6 / 2? | # Write your code below. Don't forget to press Shift+Enter to execute the cell
type(6/2) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:type(6/2) float--> What is the type of the result of: 6 // 2? (Note the double slash //.) | # Write your code below. Don't forget to press Shift+Enter to execute the cell
type(6//2) | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:type(6//2) int, as the double slashes stand for integer division --> Expression and Variables Expressions Expressions in Python can include operations among compatible types (e.g., integers and floats). For example, basic arithmetic operations like addi... | # Addition operation expression
43 + 60 + 16 + 41 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
We can perform subtraction operations using the minus operator. In this case the result is a negative number: | # Subtraction operation expression
50 - 60 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
We can do multiplication using an asterisk: | # Multiplication operation expression
5 * 5 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
We can also perform division with the forward slash: | # Division operation expression
25 / 5
# Division operation expression
25 / 6 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
As seen in the quiz above, we can use the double slash for integer division, where the result is rounded to the nearest integer: | # Integer division operation expression
25 // 5
# Integer division operation expression
25 // 6 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Exercise: Expression Let's write an expression that calculates how many hours there are in 160 minutes: | # Write your code below. Don't forget to press Shift+Enter to execute the cell
hours= 160/60 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:160/60 Or 160//60--> Python follows well accepted mathematical conventions when evaluating mathematical expressions. In the following example, Python adds 30 to the result of the multiplication (i.e., 120). | # Mathematical expression
30 + 2 * 60 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
And just like mathematics, expressions enclosed in parentheses have priority. So the following multiplies 32 by 60. | # Mathematical expression
(30 + 2) * 60 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Variables Just like with most programming languages, we can store values in variables, so we can use them later on. For example: | # Store value into variable
x = 43 + 60 + 16 + 41 | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
To see the value of x in a Notebook, we can simply place it on the last line of a cell: | # Print out the value in variable
x | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
We can also perform operations on x and save the result to a new variable: | # Use another variable to store the result of the operation between variable and value
y = x / 60
y | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
If we save a value to an existing variable, the new value will overwrite the previous value: | # Overwrite variable with new value
x = x / 60
x | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
It's a good practice to use meaningful variable names, so you and others can read the code and understand it more easily: | # Name the variables meaningfully
total_min = 43 + 42 + 57 # Total length of albums in minutes
total_min
# Name the variables meaningfully
total_hours = total_min / 60 # Total length of albums in hours
total_hours | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
In the cells above we added the length of three albums in minutes and stored it in total_min. We then divided it by 60 to calculate total length total_hours in hours. You can also do it all at once in a single expression, as long as you use parenthesis to add the albums length before you divide, as shown below. | # Complicate expression
total_hours = (43 + 42 + 57) / 60 # Total hours in a single expression
total_hours | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
If you'd rather have total hours as an integer, you can of course replace the floating point division with integer division (i.e., //). Exercise: Expression and Variables in Python What is the value of x where x = 3 + 2 * 2 | # Write your code below. Don't forget to press Shift+Enter to execute the cell
x = 3 + 2 * 2
print(x)
x:8
print(x) | 7
7
| MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:7--> What is the value of y where y = (3 + 2) * 2? | # Write your code below. Don't forget to press Shift+Enter to execute the cell
y = (3 + 2) * 2
y | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Double-click __here__ for the solution.<!-- Your answer is below:10--> What is the value of z where z = x + y? | # Write your code below. Don't forget to press Shift+Enter to execute the cell
z = x + y
z | _____no_output_____ | MIT | Notebooks/PY0101EN-1-1-Types.ipynb | tibonobo/Coursera_IBM_DataScience |
Lambda School Data Science, Unit 2: Predictive Modeling Applied Modeling, Module 2You will use your portfolio project dataset for all assignments this sprint. AssignmentComplete these tasks for your project, and document your work.- [ ] Plot the distribution of your target. - Regression problem: Is your target ske... | import pandas as pd
import seaborn as sns
#import plotly.express as px
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_absolute_error,r2_score,mean_squared_error
from sklearn.model_selection import train_test_split
#import category_encoders ... | _____no_output_____ | MIT | assignment_applied_modeling_2.ipynb | justin-hsieh/DS-Unit-2-Applied-Modeling |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.