markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Creating the device will signal to the computer that a monitor is connected. Starting the frontend will wait attempt to detect the video mode, blocking until a lock can be achieved. Once the frontend is started the video mode will be available. | hdmiin_frontend.start()
hdmiin_frontend.mode | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
The HDMI output frontend can be accessed in a similar way. | hdmiout_frontend = base.video.hdmi_out.frontend | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
and the mode must be set prior to starting the output. In this case we are just going to use the same mode as the input. | hdmiout_frontend.mode = hdmiin_frontend.mode
hdmiout_frontend.start() | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Note that nothing will be displayed on the screen as no video data is currently being send.
Colorspace conversion
The colorspace converter operates on each pixel independently using a 3x4 matrix to transform the pixels. The converter is programmed with a list of twelve coefficients in the folling order:
| |in1 |in2... | colorspace_in = base.video.hdmi_in.color_convert
colorspace_out = base.video.hdmi_out.color_convert
bgr2rgb = [0, 0, 1,
0, 1, 0,
1, 0, 0,
0, 0, 0]
colorspace_in.colorspace = bgr2rgb
colorspace_out.colorspace = bgr2rgb
colorspace_in.colorspace | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Pixel format conversion
The pixel format converters convert between the 24-bit signal used by the HDMI frontends and the colorspace converters to either an 8, 24, or 32 bit signal. 24-bit mode passes the input straight through, 32-bit pads the additional pixel with 0 and 8-bit mode selects the first channel in the pixe... | pixel_in = base.video.hdmi_in.pixel_pack
pixel_out = base.video.hdmi_out.pixel_unpack
pixel_in.bits_per_pixel = 8
pixel_out.bits_per_pixel = 8
pixel_in.bits_per_pixel | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Video DMA
The final element in the pipeline is the video DMA which transfers video frames to and from memory. The VDMA consists of two channels, one for each direction which operate completely independently. To use a channel its mode must be set prior to start being called. After the DMA is started readframe and writef... | inputmode = hdmiin_frontend.mode
framemode = VideoMode(inputmode.width, inputmode.height, 8)
vdma = base.video.axi_vdma
vdma.readchannel.mode = framemode
vdma.readchannel.start()
vdma.writechannel.mode = framemode
vdma.writechannel.start()
frame = vdma.readchannel.readframe()
vdma.writechannel.writeframe(frame) | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
In this case, because we are only using 8 bits per pixel, only the red channel is read and displayed.
The two channels can be tied together which will ensure that the input is always mirrored to the output | vdma.readchannel.tie(vdma.writechannel) | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Frame Ownership
The VDMA driver has a strict method of frame ownership. Any frames returned by readframe or newframe are owned by the user and should be destroyed by the user when no longer needed by calling frame.freebuffer(). Frames handed back to the VDMA with writeframe are no longer owned by the user and should no... | vdma.readchannel.stop()
vdma.writechannel.stop() | boards/Pynq-Z1/base/notebooks/video/hdmi_video_pipeline.ipynb | cathalmccabe/PYNQ | bsd-3-clause |
Exercise 1: Reading various forms of JSON Data
In the /data/ folder, you will find a series of .json files called dataN.json, numbered 1-4. Each file contains the following data:
| |birthday | first_name |last_name |
|--|-----------|------------|----------|
|0 |5\/3\/67 |Robert |Hernandez |
|1 |8\/4\/84 |Steve ... | #Your code here...
file1 = pd.read_json('../../data/data1.json')
file2 = pd.read_json('../../data/data2.json')
file2 = pd.read_json('../../data/data2.json')
file3 = pd.read_json('../../data/data3.json') # add orient=columns
file4 = pd.read_json('../../data/data4.json', orient='split')
combined = pd.concat([file1, file2... | 1m_ML_Security/notebooks/day_1/Worksheet 2 - Exploring Two Dimensional Data.ipynb | yevheniyc/Python | mit |
Exercise 2:
In the data file, there is a webserver file called hackers-access.httpd. For this exercise, you will use this file to answer the following questions:
1. Which browsers are the top 10 most used browsers in this data?
2. Which are the top 10 most used operating systems?
In order to accomplish this task, do... | import apache_log_parser
from user_agents import parse
def parse_ua(line):
parsed_data = parse(line)
return str(parsed_data).split('/')[1]
def parse_ua_2(line):
parsed_data = parse(line)
return str(parsed_data).split('/')[2]
#Read in the log file
line_parser = apache_log_parser.make_parser("%h %l %u... | 1m_ML_Security/notebooks/day_1/Worksheet 2 - Exploring Two Dimensional Data.ipynb | yevheniyc/Python | mit |
Exercise 3:
Using the dailybots.csv film, read the file into a DataFrame and perform the following operations:
1. Filter the DataFrame to include bots from the Government/Politics Industry.
2. Calculate the ratio of hosts to orgs and add this as a column to the DataFrame and output the result
3. Calculate the total ... | #Your code here...
bots = pd.read_csv('../../data/dailybots.csv')
gov_bots = bots[['botfam', 'hosts']][bots['industry'] == 'Government/Politics']
gov_bots.groupby(['botfam']).size() | 1m_ML_Security/notebooks/day_1/Worksheet 2 - Exploring Two Dimensional Data.ipynb | yevheniyc/Python | mit |
$
\newcommand{\cur}{i}
\newcommand{\prev}{j}
\newcommand{\prevcur}{{\cur\prev}}
\newcommand{\next}{k}
\newcommand{\curnext}{{\next\cur}}
\newcommand{\ex}{\eta}
\newcommand{\pot}{\rho}
\newcommand{\feature}{x}
\newcommand{\weight}{w}
\newcommand{\wcur}{{\weight_{\cur\prev}}}
\newcommand{\activthres}{\theta}
\newcommand{... | # Notations :
# - $\cur$: couche courante
# - $\prev$: couche immédiatement en amont de la courche courrante (i.e. vers la couche d'entrée du réseau)
# - $\next$: couche immédiatement en aval de la courche courrante (i.e. vers la couche de sortie du réseau)
# - $\ex$: exemple (*sample* ou *feature*) courant (i.e. le ve... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Introduction
Qu'est-ce qu'un réseau de neurones ?
Une grosse fonction parametrique.
Pour peu qu'on donne suffisamment de paramètres à cette fonction, elle est capable d'approximer n'importe quelle fonction continue.
Représentation schématique d'une fonction paramètrique avec 3 paramètres avec une entrée en une sortie à... | STR_CUR = r"i" # Couche courante
STR_PREV = r"j" # Couche immédiatement en amont de la courche courrante (i.e. vers la couche d'entrée du réseau)
STR_NEXT = r"k" # Couche immédiatement en aval de la courche courrante (i.e. vers la couche de sortie du réseau)
STR_EX = r"\eta" # Exemple (*sample* ou *... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
$$
\sigout = \activfunc \left( \sum_i \weight_i \feature_i \right)
$$
$$
\pot_\cur = \sum_\prev \wcur \sigout_{\prev}
$$
$$
\sigout_{\cur} = \activfunc(\pot_\cur)
$$
$$
\weights = \begin{pmatrix}
\weight_{11} & \cdots & \weight_{1m} \
\vdots & \ddots & \vdots \
\weight_{n1} & \cdots & \weight_{n... | def sigmoid(x, _lambda=1.):
y = 1. / (1. + np.exp(-_lambda * x))
return y
%matplotlib inline
x = np.linspace(-5, 5, 300)
y1 = sigmoid(x, 1.)
y2 = sigmoid(x, 5.)
y3 = sigmoid(x, 0.5)
plt.plot(x, y1, label=r"$\lambda=1$")
plt.plot(x, y2, label=r"$\lambda=5$")
plt.plot(x, y3, label=r"$\lambda=0.5$")
plt.hline... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Fonction logistique
Fonctions ayant pour expression
$$
f(t) = K \frac{1}{1+ae^{-\lambda t}}
$$
où $K$ et $\lambda$ sont des réels positifs et $a$ un réel quelconque.
Les fonctions sigmoïdes sont un cas particulier de fonctions logistique avec $a > 0$. | def logistique(x, a=1., k=1., _lambda=1.):
y = k / (1. + a * np.exp(-_lambda * x))
return y
%matplotlib inline
x = np.linspace(-5, 5, 300)
y1 = logistique(x, a=1.)
y2 = logistique(x, a=2.)
y3 = logistique(x, a=0.5)
plt.plot(x, y1, label=r"$a=1$")
plt.plot(x, y2, label=r"$a=2$")
plt.plot(x, y3, label=r"$a=0.... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Le terme de biais
TODO | fig, ax = nnfig.init_figure(size_x=8, size_y=6)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
#nnfig.draw_synapse(ax, (0,2*VSPACE), (HSPACE, 0), label=tex(STR_WEIGHT + "_0"), label_position=0.3)
nnfig.draw_synapse(ax, (0, VSPACE), (HSPACE, 0), label=tex(STR_WEIGHT + "_1"), label_position=0.3... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Exemple | fig, ax = nnfig.init_figure(size_x=8, size_y=6)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
nnfig.draw_synapse(ax, (0,2*VSPACE), (HSPACE, 0), label=tex(STR_WEIGHT + "_0"), label_position=0.3)
nnfig.draw_synapse(ax, (0, VSPACE), (HSPACE, 0), label=tex(STR_WEIGHT + "_1"), label_position=0.3)... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Pour vecteur d'entrée = ... et un vecteur de poids arbitrairement fixé à ...
et un neurone défini avec la fonction sigmoïde,
on peut calculer la valeur de sortie du neurone :
On a:
$$
\sum_i \weight_i \feature_i = \dots
$$
donc
$$
y = \frac{1}{1 + e^{-\dots}}
$$ | @interact(w1=(-10., 10., 0.5), w2=(-10., 10., 0.5))
def nn1(wb1=0., w1=10.):
x = np.linspace(-10., 10., 100)
xb = np.ones(x.shape)
s1 = wb1 * xb + w1 * x
y = sigmoid(s1)
plt.plot(x, y) | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Définition d'un réseau de neurones
Disposition des neurones en couches et couches cachées
TODO
Exemple : réseau de neurones à 1 couche "cachée" | fig, ax = nnfig.init_figure(size_x=8, size_y=4)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
# Layer 1-2
nnfig.draw_synapse(ax, (0, VSPACE), (HSPACE, VSPACE), label=tex(STR_WEIGHT + "_1"), label_position=0.4)
nnfig.draw_synapse(ax, (0, -VSPACE), (HSPACE, VSPACE), label=tex(STR_WEIGHT + "_... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
TODO: il manque les biais...
$$
\sigout =
\activfunc \left(
\weight_5 ~ \underbrace{\activfunc \left(\weight_1 \feature_1 + \weight_3 \feature_2 \right)}{\sigout_1}
+
\weight_6 ~ \underbrace{\activfunc \left(\weight_2 \feature_1 + \weight_4 \feature_2 \right)}{\sigout_2}
\right)
$$ | @interact(wb1=(-10., 10., 0.5), w1=(-10., 10., 0.5), wb2=(-10., 10., 0.5), w2=(-10., 10., 0.5))
def nn1(wb1=0.1, w1=0.1, wb2=0.1, w2=0.1):
x = np.linspace(-10., 10., 100)
xb = np.ones(x.shape)
s1 = wb1 * xb + w1 * x
y1 = sigmoid(s1)
s2 = wb2 * xb + w2 * x
y2 = sigmoid(s2)
s = wb2 ... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Exemple : réseau de neurones à 2 couches "cachée" | fig, ax = nnfig.init_figure(size_x=8, size_y=4)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
# Layer 1-2
nnfig.draw_synapse(ax, (0, VSPACE), (HSPACE, VSPACE), label=tex(STR_WEIGHT + "_1"), label_position=0.4)
nnfig.draw_synapse(ax, (0, -VSPACE), (HSPACE, VSPACE), label=tex(STR_WEIGHT + "_... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
TODO: il manque le biais...
$
\newcommand{\yone}{\underbrace{\activfunc \left(\weight_1 \feature_1 + \weight_3 \feature_2 \right)}{\sigout_1}}
\newcommand{\ytwo}{\underbrace{\activfunc \left(\weight_2 \feature_1 + \weight_4 \feature_2 \right)}{\sigout_2}}
\newcommand{\ythree}{\underbrace{\activfunc \left(\weight_5 \yon... | fig, ax = nnfig.init_figure(size_x=8, size_y=4)
nnfig.draw_synapse(ax, (0, -6), (10, 0))
nnfig.draw_synapse(ax, (0, -2), (10, 0))
nnfig.draw_synapse(ax, (0, 2), (10, 0))
nnfig.draw_synapse(ax, (0, 6), (10, 0))
nnfig.draw_synapse(ax, (0, -6), (10, -4))
nnfig.draw_synapse(ax, (0, -2), (10, -4))
nnfig.draw_synapse(ax,... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Mise à jours des poids
$$
\weights_{\learnit + 1} = \weights_{\learnit} - \underbrace{\learnrate \nabla_{\weights} \errfunc \left( \weights_{\learnit} \right)}
$$
$- \learnrate \nabla_{\weights} \errfunc \left( \weights_{\learnit} \right)$: descend dans la direction opposée au gradient (plus forte pente)
avec $\nabla_{... | def d_sigmoid(x, _lambda=1.):
e = np.exp(-_lambda * x)
y = _lambda * e / np.power(1 + e, 2)
return y
%matplotlib inline
x = np.linspace(-5, 5, 300)
y1 = d_sigmoid(x, 1.)
y2 = d_sigmoid(x, 5.)
y3 = d_sigmoid(x, 0.5)
plt.plot(x, y1, label=r"$\lambda=1$")
plt.plot(x, y2, label=r"$\lambda=5$")
plt.plot(x, y... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Tangente hyperbolique
Dérivée :
$$
\tanh '= \frac{1}{\cosh^{2}} = 1-\tanh^{2}
$$ | def d_tanh(x):
y = 1. - np.power(np.tanh(x), 2)
return y
x = np.linspace(-5, 5, 300)
y = d_tanh(x)
plt.plot(x, y)
plt.hlines(y=0, xmin=-5, xmax=5, color='gray', linestyles='dotted')
plt.vlines(x=0, ymin=-2, ymax=2, color='gray', linestyles='dotted')
plt.title("Fonction dérivée de la tangente hyperbolique")
... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Apprentissage incrémentiel (ou partiel) (ang. incremental learning):
on ajuste les poids $\weights$ après la présentation d'un seul exemple
("ce n'est pas une véritable descente de gradient").
C'est mieux pour éviter les minimums locaux, surtout si les exemples sont
mélangés au début de chaque itération | # *Apprentissage différé* (ang. *batch learning*):
# TODO
# Est-ce que la fonction objectif $\errfunc$ est une fonction multivariée
# ou est-ce une aggrégation des erreurs de chaque exemple ?
# **TODO: règle du delta / règle du delta généralisée** | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Rétropropagation du gradient
Rétropropagation du gradient:
une méthode pour calculer efficacement le gradient de la fonction objectif $\errfunc$.
Intuition:
La rétropropagation du gradient n'est qu'une méthode parmis d'autre pour résoudre le probème d'optimisation des poids $\weight$. On pourrait très bien résoudre ce ... | # TODO
#Voc:
#- *erreur marginale*: **TODO** | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Note intéressante de Jürgen Schmidhuber : http://people.idsia.ch/~juergen/who-invented-backpropagation.html
Signaux d'erreur $\errsig_\cur$ pour les neurones de sortie $(\cur \in \Omega)$
$$
\errsig_\cur = \activfunc'(\pot_\cur)[\sigout_\cur - \sigoutdes_\cur]
$$
Signaux d'erreur $\errsig_\cur$ pour les neurones cachés... | fig, ax = nnfig.init_figure(size_x=8, size_y=4)
nnfig.draw_synapse(ax, (0, -2), (10, 0))
nnfig.draw_synapse(ax, (0, 2), (10, 0), label=tex(STR_WEIGHT + "_{" + STR_NEXT + STR_CUR + "}"), label_position=0.5, fontsize=14)
nnfig.draw_synapse(ax, (10, 0), (12, 0))
nnfig.draw_neuron(ax, (0, -2), 0.5, empty=True)
nnfig.dr... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Plus de détail : calcul de $\errsig_\cur$
Dans l'exemple suivant on ne s'intéresse qu'aux poids $\weight_1$, $\weight_2$, $\weight_3$, $\weight_4$ et $\weight_5$ pour simplifier la demonstration. | fig, ax = nnfig.init_figure(size_x=8, size_y=4)
HSPACE = 6
VSPACE = 4
# Synapse #####################################
# Layer 1-2
nnfig.draw_synapse(ax, (0, VSPACE), (HSPACE, VSPACE), label=tex(STR_WEIGHT + "_1"), label_position=0.4)
nnfig.draw_synapse(ax, (0, -VSPACE), (HSPACE, VSPACE), color="lightgray")
nnfig... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Attention: $\weight_1$ influe $\pot_2$ et $\pot_3$ en plus de $\pot_1$ et $\pot_o$.
Calcul de la dérivée partielle de l'erreur par rapport au poid synaptique $\weight_4$
rappel:
$$
\begin{align}
\errfunc &= \frac12 \left( \sigout_o - \sigoutdes_o \right)^2 \tag{1} \
\sigout_o &= \activfunc(\pot_o) \tag{2} \
\pot_o ... | # Define the activation function and its derivative
activation_function = tanh
d_activation_function = d_tanh
def init_weights(num_input_cells, num_output_cells, num_cell_per_hidden_layer, num_hidden_layers=1):
"""
The returned `weights` object is a list of weight matrices,
where weight matrix at index $i$... | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Divers
Le PMC peut approximer n'importe quelle fonction continue avec une précision arbitraire suivant le nombre de neurones présents sur la couche cachée.
Initialisation des poids: généralement des petites valeurs aléatoires | # TODO: la différence entre:
# * réseau bouclé
# * réseau récurent | nb_sci_ai/ai_ml_multilayer_perceptron_fr.ipynb | jdhp-docs/python_notebooks | mit |
Structure Types
Structure types are assigned by hand by ICSD curators. | # How many ternaries have been assigned a structure type?
structure_types = [line[3] for line in data if line[3] is not '']
unique_structure_types = set(structure_types)
print("There are {} ICSD ternaries entries.".format(len(data)))
print("Structure types are assigned for {} entries.".format(len(structure_types)))
pri... | notebooks/old_ICSD_Notebooks/Understanding ICSD data.ipynb | bismayan/MaterialsMachineLearning | mit |
Filter for stoichiometric compounds only: | def is_stoichiometric(composition):
return np.all(np.mod(composition.values(), 1) == 0)
stoichiometric_compositions = [c for c in compositions if is_stoichiometric(c)]
print("Number of stoichiometric compositions: {}".format(len(stoichiometric_compositions)))
ternaries = set(c.formula for c in stoichiometric_comp... | notebooks/old_ICSD_Notebooks/Understanding ICSD data.ipynb | bismayan/MaterialsMachineLearning | mit |
Long Formulas | # What are the longest formulas?
for formula in sorted(formulas, key = lambda x: len(x), reverse = True)[:20]:
print(formula) | notebooks/old_ICSD_Notebooks/Understanding ICSD data.ipynb | bismayan/MaterialsMachineLearning | mit |
Two key insights:
1. Just because there are three elements in the formula
doesn't mean the compound is fundamentally a ternary.
There are doped binaries which masquerade as ternaries.
And there are doped ternaries which masquerade as quaternaries,
or even quintenaries. Because I only asked for compositions
... | def filter_in_set(compound, universe):
return all((e in universe) for e in Composition(compound))
transition_metals = [e for e in Element if e.is_transition_metal]
tm_ternaries = [c for c in formulas if filter_in_set(c, transition_metals)]
print("Number of intermetallics:", len(tm_ternaries))
unique_tm_ternaries ... | notebooks/old_ICSD_Notebooks/Understanding ICSD data.ipynb | bismayan/MaterialsMachineLearning | mit |
A repository: a group of linked commits
<!-- offline:

-->
<img src="https://raw.github.com/fperez/reprosw/master/fig/threecommits.png" >
Note: these form a Directed Acyclic Graph (DAG), with nodes identified by their hash.
A hash: a fingerprint of the content of each commit and its par... | import sha
# Our first commit
data1 = 'This is the start of my paper2.'
meta1 = 'date: 1/1/12'
hash1 = sha.sha(data1 + meta1).hexdigest()
print 'Hash:', hash1
# Our second commit, linked to the first
data2 = 'Some more text in my paper...'
meta2 = 'date: 1/2/12'
# Note we add the parent hash here!
hash2 = sha.sha(dat... | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
And this is pretty much the essence of Git!
First things first: git must be configured before first use
The minimal amount of configuration for git to work without pestering you is to tell it who you are: | %%bash
git config --global user.name "Fernando Perez"
git config --global user.email "Fernando.Perez@berkeley.edu" | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
And how you will edit text files (it will often ask you to edit messages and other information, and thus wants to know how you like to edit your files): | %%bash
# Put here your preferred editor. If this is not set, git will honor
# the $EDITOR environment variable
git config --global core.editor /usr/bin/jed # my lightweight unix editor
# On Windows Notepad will do in a pinch, I recommend Notepad++ as a free alternative
# On the mac, you can set nano or emacs as a bas... | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
Set git to use the credential memory cache so we don't have to retype passwords too frequently. On Linux, you should run the following (note that this requires git version 1.7.10 or newer): | %%bash
git config --global credential.helper cache
# Set the cache to timeout after 2 hours (setting is in seconds)
git config --global credential.helper 'cache --timeout=7200' | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
Github offers in its help pages instructions on how to configure the credentials helper for Mac OSX and Windows.
Stage 1: Local, single-user, linear workflow
Simply type git to see a full list of all the 'core' commands. We'll now go through most of these via small practical exercises: | !git | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
And git rm works in a similar fashion.
Exercise
Add a new file file2.txt, commit it, make some changes to it, commit them again, and then remove it (and don't forget to commit this last step!).
Local user, branching
What is a branch? Simply a label for the 'current' commit in a sequence of ongoing commits:
<!-- offlin... | %%bash
cd test
git status
ls | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
Since the above cell didn't produce any output after the git remote -v call, it means we have no remote repositories configured. We will now proceed to do so. Once logged into GitHub, go to the new repository page and make a repository called test. Do not check the box that says Initialize this repository with a REA... | %%bash
cd test
git remote add origin https://github.com/fperez/test.git
git push -u origin master | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
We can now see this repository publicly on github.
Let's see how this can be useful for backup and syncing work between two different computers. I'll simulate a 2nd computer by working in a different directory... | %%bash
# Here I clone my 'test' repo but with a different name, test2, to simulate a 2nd computer
git clone https://github.com/fperez/test.git test2
cd test2
pwd
git remote -v | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
Note: While it's a good idea to understand the basics of fixing merge conflicts by hand, in some cases you may find the use of an automated tool useful. Git supports multiple merge tools: a merge tool is a piece of software that conforms to a basic interface and knows how to merge two files into a new one. Since thes... | from IPython.display import YouTubeVideo
YouTubeVideo('U8GBXvdmHT4') | day1/Version Control.ipynb | AstroHackWeek/AstroHackWeek2014 | bsd-3-clause |
Deciding a model
The first thing once we've got some data is decide which is the model that generated the data. In this case we decide that the height of Python developers comes from a normal distribution.
A normal distribution has two parameters, the mean $\mu$ and the standard deviation $\sigma$ (or the variance $\si... | import numpy
import scipy.stats
from matplotlib import pyplot
mu = 0.
sigma = 1.
x = numpy.linspace(-10., 10., 201)
likelihood = scipy.stats.norm.pdf(x, mu, sigma)
pyplot.plot(x, likelihood)
pyplot.xlabel('x')
pyplot.ylabel('Likelihood')
pyplot.title('Normal distribution with $\mu=0$ and $\sigma=1$'); | docs/Bayesian inference tutorial.ipynb | datapythonista/datapythonista.github.io | apache-2.0 |
Following the example, we wanted to score how good are the parameters $\mu=175$ and $\sigma=5$ for our data. So far we choosen these parameters arbitrarily, but we'll choose them in a smarter way later on.
If we take the probability density function (p.d.f.) of the normal distribution and we compute for the first data ... | import math
1. / math.sqrt(2 * math.pi * (5 **2)) * math.exp(-((183 - 175) ** 2) / (2 * (5 ** 2))) | docs/Bayesian inference tutorial.ipynb | datapythonista/datapythonista.github.io | apache-2.0 |
This is the probability that 183 was generated by a normal distribution with mean 175 and standard deviation 5.
With scipy we can easily compute the likelihood of all values in our data: | import scipy.stats
mu = 175
sigma = 5
x = [183, 168, 177, 170, 175, 177, 178, 166, 174, 178]
scipy.stats.norm.pdf(x, mu, sigma) | docs/Bayesian inference tutorial.ipynb | datapythonista/datapythonista.github.io | apache-2.0 |
Prior
The prior is our knowledge of the parameters before we observe the data. It's probably the most subjective part of Bayesian inference, and different approaches can be used.
We can use informed priors, and try to give the model as much information as possible. Or use uninformed priors, and let the process find the... | import numpy
import scipy.stats
from matplotlib import pyplot
mean_height = numpy.linspace(0, 272, 273)
probability = scipy.stats.uniform.pdf(mean_height, 0, 272)
pyplot.plot(mean_height, probability)
pyplot.xlabel('Mean height')
pyplot.ylabel('Probability')
pyplot.title('Uninformed prior for Python developers height... | docs/Bayesian inference tutorial.ipynb | datapythonista/datapythonista.github.io | apache-2.0 |
This could work, but we can do better. Just having 10 data points, the amount of information that we can learn from them is quite limited. And we may use these 10 data points to discover something we already know. That the probability of the mean height being 0 is nil, as it is the probability of the maximum ever obser... | import numpy
import scipy.stats
from matplotlib import pyplot
world_height_mean = 165
world_height_standard_deviation = 7
mean_height = numpy.linspace(0, 272, 273)
probability = scipy.stats.norm.pdf(mean_height, world_height_mean, world_height_standard_deviation * 2)
pyplot.plot(mean_height, probability)
pyplot.xlab... | docs/Bayesian inference tutorial.ipynb | datapythonista/datapythonista.github.io | apache-2.0 |
Violations of graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a negative example of the principles that Tufte describes in The Visual Display of Quantitative Information.
CNN
Fox News
Time
Upload the image for the visualization to this directory and displa... | # Add your filename and uncomment the following line:
Image(filename='StockPicture.png') | assignments/assignment04/TheoryAndPracticeEx02.ipynb | LimeeZ/phys292-2015-work | mit |
Graficas chidas! | def awesome_settings():
# awesome plot options
sns.set_style("white")
sns.set_style("ticks")
sns.set_context("paper", font_scale=2)
sns.set_palette(sns.color_palette('Set2'))
# image stuff
plt.rcParams['figure.figsize'] = (12.0, 6.0)
plt.rcParams['savefig.dpi'] = 60
plt.rcParams['lin... | Dia2/2_Intro_Matplotlib.ipynb | beangoben/quantum_solar | mit |
1 Crear graficas (plt.plot)
Un ejemplo "complejo"
Crear graficas es muy facil en matplotlib, aqui va un ejemplo complicado..si entiendes este pedazo de codigo puedes entender el resto. | # datos
x = np.linspace(0.0, 2.0, 40)
y1 = np.sin(2*np.pi*x)
y2 = 0.5*x+0.1
y3 = 0.5*x**2+0.5*x+0.1
# a graficas
plt.plot(x,y1,'--',label='Seno')
plt.plot(x,y2,'-',label='Linea')
plt.plot(x,y3,'.',label='Cuadratica')
# estilo
plt.xlabel('y')
plt.ylabel('x')
plt.title('Unas grafiquitas')
plt.legend(loc='best')
sns.des... | Dia2/2_Intro_Matplotlib.ipynb | beangoben/quantum_solar | mit |
Ahora por pedazos
Podemos usar la funcion np.linspace para crear valores en un rango, por ejemplo si queremos 100 numeros entre 0 y 10 usamos:
Y podemos graficar dos cosas al mismo tiempo:
Que tal si queremos distinguir cada linea? Pues usamos legend(), de leyenda..tambien tenemos que agregarles nombres a cada plot
Tam... | mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
n, bins, patches = plt.hist(x, 50, normed=1)
plt.ylabel('Porcentaje')
plt.xlabel('IQ')
plt.title('Distribucion de IQ entre 10k personas')
plt.xlim([0,200])
sns.despine()
plt.show() | Dia2/2_Intro_Matplotlib.ipynb | beangoben/quantum_solar | mit |
This crazy try-except construction is our way of making sure the notebooks will work when completed without actually providing complete code. You can either write your code directly in the except block, or delete the try, exec and except lines entirely (remembering to unindent the remaining lines in that case, because ... | try:
exec(open('Solution/goals.py').read())
except IOError:
my_goals = REPLACE_WITH_YOUR_SOLUTION() | tutorials/Week1/GithubAndGoals.ipynb | drphilmarshall/StatisticalMethods | gpl-2.0 |
This cell just prints out the string my_goals. | print(my_goals) | tutorials/Week1/GithubAndGoals.ipynb | drphilmarshall/StatisticalMethods | gpl-2.0 |
1. Load trajectory
Read the heat current from a simple column-formatted file. The desired columns are selected based on their header (e.g. with LAMMPS format).
For other input formats see corresponding the example. | jfile = st.i_o.TableFile('./data/Silica.dat', group_vectors=True)
jfile.read_datalines(start_step=0, NSTEPS=0, select_ckeys=['flux1']) | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
2. Heat Current
Define a HeatCurrent from the trajectory, with the correct parameters. | DT_FS = 1.0 # time step [fs]
TEMPERATURE = 1065.705630 # temperature [K]
VOLUME = 3130.431110818 # volume [A^3]
j = st.HeatCurrent(jfile.data['flux1'], UNITS= 'metal', DT_FS=DT_FS,
TEMPERATURE=TEMPERATURE, VOLUME=VOLUME)
# trajectory
f = plt.figure()
ax = plt.plot(j.timeseries... | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
Compute the Power Spectral Density and filter it for visualization. | # Periodogram with given filtering window width
ax = j.plot_periodogram(PSD_FILTER_W=0.5, kappa_units=True)
print(j.Nyquist_f_THz)
plt.xlim([0, 50])
ax[0].set_ylim([0, 150]);
ax[1].set_ylim([12, 18]); | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
3. Resampling
If the Nyquist frequency is very high (i.e. the sampling time is small), such that the log-spectrum goes to low values, you may want resample your time series to obtain a maximum frequency $f^$.
Before performing that operation, the time series is automatically filtered to reduce the amount of aliasing in... | FSTAR_THZ = 28.0
jf,ax = j.resample(fstar_THz=FSTAR_THZ, plot=True, freq_units='thz')
plt.xlim([0, 80])
ax[1].set_ylim([12,18]);
ax = jf.plot_periodogram(PSD_FILTER_W=0.1)
ax[1].set_ylim([12, 18]); | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
4. Cepstral Analysis
Perform Cepstral Analysis. The code will:
1. the parameters describing the theoretical distribution of the PSD are computed
2. the Cepstral coefficients are computed by Fourier transforming the log(PSD)
3. the Akaike Information Criterion is applied
4. the resulting $\kappa$ is returned | jf.cepstral_analysis()
# Cepstral Coefficients
print('c_k = ', jf.dct.logpsdK)
ax = jf.plot_ck()
ax.set_xlim([0, 50])
ax.set_ylim([-0.5, 0.5])
ax.grid();
# AIC function
f = plt.figure()
plt.plot(jf.dct.aic, '.-', c=c[0])
plt.xlim([0, 200])
plt.ylim([2800, 3000]);
print('K of AIC_min = {:d}'.format(jf.dct.aic_Kmin))... | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
Plot the thermal conductivity $\kappa$ as a function of the cutoff $P^*$ | # L_0 as a function of cutoff K
ax = jf.plot_L0_Pstar()
ax.set_xlim([0, 200])
ax.set_ylim([12.5, 14.5]);
print('K of AIC_min = {:d}'.format(jf.dct.aic_Kmin))
print('AIC_min = {:f}'.format(jf.dct.aic_min))
# kappa as a function of cutoff K
ax = jf.plot_kappa_Pstar()
ax.set_xlim([0,200])
ax.set_ylim([0, 5.0]);
print('... | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
You can now visualize the filtered PSD... | # filtered log-PSD
ax = j.plot_periodogram(0.5, kappa_units=True)
ax = jf.plot_periodogram(0.5, axes=ax, kappa_units=True)
ax = jf.plot_cepstral_spectrum(axes=ax, kappa_units=True)
ax[0].axvline(x = jf.Nyquist_f_THz, ls='--', c='r')
ax[1].axvline(x = jf.Nyquist_f_THz, ls='--', c='r')
plt.xlim([0., 50.])
ax[1].set_ylim(... | examples/example_cepstrum_singlecomp_silica.ipynb | lorisercole/thermocepstrum | gpl-3.0 |
Lists are mutable while strings are immutable. We can never change a string, only reassign it to something else. | S = 'abc'
#S[1] = 'z' # <== Doesn't work!
L = ['a', 'b', 'c']
L[1] = 'z'
print L | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
Some common list procedures:
reduce
Convert a sequence (eg list) into a single element. Examples: sum, mean
map
Apply some function to each element of a sequence. Examples: making every element in a list positive, capitalizing all elements of a list
filter
Selecting some elements of a sequence according to some conditi... | a = 23
b = 23
a is b
list1 = [1,2,3]
list2 = [1,2,3]
list1 is list2 | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
list1 and list2 are equivalent (same values) but not identical (same object). In order to make these two lists identical we can alias the object. | list2 = list1
list1 is list2 | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
Now both names/variables point at the same object (reference the same object). | list1[0] = 1234
print list1
print list2
Back to the strings,
b = 'abc'
a = b
a is b | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
Let's try to change b by assigning to a (they reference the same object after all) | a = 'xyz'
print a
print b | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
What happened is that we have reassigned a to a new object, that is they no longer point at the same object. | a is b
id(b) | python-club/notebooks/python-club-10.ipynb | wtsi-medical-genomics/team-code | gpl-2.0 |
토큰(token)
토큰은 문서에서 단어장을 생성할 때 하나의 단어가 되는 단위를 말한다. analyzer, tokenizer, token_pattern 등의 인수로 조절할 수 있다.
문서를 보고 어떤 언어인지 맞추는 방법은 토큰으로 사용빈도를 보고 맞춘다. 예를 들어 제일 많이 나오는 char를 e로 잡고 그 다음 뭐 인지를 패턴화해서 맞추는 방식으로 | vect = CountVectorizer(analyzer="char").fit(corpus) #토큰 1개가 vocaburary로 인식. 원래 기본은 word이지만 char가 들어갈 수 있다.
vect.vocabulary_
import nltk
nltk.download("punkt")
vect = CountVectorizer(tokenizer=nltk.word_tokenize).fit(corpus)
vect.vocabulary_
vect = CountVectorizer(token_pattern="t\w+").fit(corpus)
vect.vocabulary_ | 통계, 머신러닝 복습/160615수_16일차_문서 전처리 Text Preprocessing/4.문서 전처리.ipynb | kimkipyo/dss_git_kkp | mit |
빈도수
max_df, min_df 인수를 사용하여 문서에서 토큰이 나타난 횟수를 기준으로 단어장을 구성할 수도 있다. 토큰의 빈도가 max_df로 지정한 값을 초과 하거나 min_df로 지정한 값보다 작은 경우에는 무시한다. 인수 값은 정수인 경우 횟수, 부동소수점인 경우 비중을 뜻한다. | vect = CountVectorizer(max_df=4, min_df=2).fit(corpus)
vect.vocabulary_, vect.stop_words_
vect.transform(corpus).toarray()
vect.transform(corpus).toarray().sum(axis=0) | 통계, 머신러닝 복습/160615수_16일차_문서 전처리 Text Preprocessing/4.문서 전처리.ipynb | kimkipyo/dss_git_kkp | mit |
TF-IDF
TF-IDF(Term Frequency – Inverse Document Frequency) 인코딩은 단어를 갯수 그대로 카운트하지 않고 모든 문서에 공통적으로 들어있는 단어의 경우 문서 구별 능력이 떨어진다고 보아 가중치를 축소하는 방법이다.
구제적으로는 문서 $d$(document)와 단어 $t$ 에 대해 다음과 같이 계산한다.
$$ \text{tf-idf}(d, t) = \text{tf}(d, t) \cdot \text{idf}(d, t) $$
여기에서
$\text{tf}(d, t)$: 단어의 빈도수
$\text{idf}(d, t)$ : inve... | from sklearn.feature_extraction.text import TfidfVectorizer
tfidv = TfidfVectorizer().fit(corpus)
tfidv.transform(corpus).toarray() | 통계, 머신러닝 복습/160615수_16일차_문서 전처리 Text Preprocessing/4.문서 전처리.ipynb | kimkipyo/dss_git_kkp | mit |
Hashing Trick
CountVectorizer는 모든 작업을 in-memory 상에서 수행하므로 데이터 양이 커지면 속도가 느려지거나 실행이 불가능해진다. 이 때
HashingVectorizer를 사용하면 Hashing Trick을 사용하여 메모리 및 실행 시간을 줄일 수 있다. 하지만 사용 빈도로는 이게 더 잘 안 쓰인다. | from sklearn.datasets import fetch_20newsgroups
twenty = fetch_20newsgroups()
len(twenty.data)
%time CountVectorizer().fit(twenty.data).transform(twenty.data)
from sklearn.feature_extraction.text import HashingVectorizer
hv = HashingVectorizer(n_features=10)
%time hv.transform(twenty.data) | 통계, 머신러닝 복습/160615수_16일차_문서 전처리 Text Preprocessing/4.문서 전처리.ipynb | kimkipyo/dss_git_kkp | mit |
예 | import json
import string
from konlpy.utils import pprint
from konlpy.tag import Hannanum
hannanum = Hannanum()
req = urllib2.Request("https://www.datascienceschool.net/download-notebook/708e711429a646818b9dcbb581e0c10a/")
opener = urllib2.build_opener()
f = opener.open(req)
json = json.loads(f.read())
cell = ["\n".jo... | 통계, 머신러닝 복습/160615수_16일차_문서 전처리 Text Preprocessing/4.문서 전처리.ipynb | kimkipyo/dss_git_kkp | mit |
The code in dataset_fn will be invoked on the input device, which is usually
the CPU, on each of the worker machines.
Model construction and compiling
Now, you will create a tf.keras.Model with the APIs of choice (a trivial
tf.keras.models.Sequential model is being used as a demonstration here),
followed by a Model.com... | # TODO
with strategy.scope():
model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)])
model.compile(tf.keras.optimizers.SGD(), loss='mse', steps_per_execution=10) | courses/machine_learning/deepdive2/production_ml/solutions/parameter_server_training.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Then we create the training dataset wrapped in a dataset_fn: | def dataset_fn(_):
raw_dataset = tf.data.Dataset.from_tensor_slices(examples)
# TODO
train_dataset = raw_dataset.map(
lambda x: (
{"features": feature_preprocess_stage(x["features"])},
label_preprocess_stage(x["label"])
)).shuffle(200).batch(32).repeat()
return train_dataset | courses/machine_learning/deepdive2/production_ml/solutions/parameter_server_training.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Build the model
Second, we create the model and other objects. Make sure to create all variables
under strategy.scope. | # These variables created under the `strategy.scope` will be placed on parameter
# servers in a round-robin fashion.
with strategy.scope():
# Create the model. The input needs to be compatible with KPLs.
# TODO
model_input = keras.layers.Input(
shape=(3,), dtype=tf.int64, name="model_input")
emb_layer = ... | courses/machine_learning/deepdive2/production_ml/solutions/parameter_server_training.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Then we create a per-worker dataset and an iterator. In the per_worker_dataset_fn below, wrapping the dataset_fn into
strategy.distribute_datasets_from_function is recommended to allow efficient
prefetching to GPUs seamlessly. | @tf.function
def per_worker_dataset_fn():
return strategy.distribute_datasets_from_function(dataset_fn)
# TODO
per_worker_dataset = coordinator.create_per_worker_dataset(per_worker_dataset_fn)
per_worker_iterator = iter(per_worker_dataset) | courses/machine_learning/deepdive2/production_ml/solutions/parameter_server_training.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Here is how you can fetch the result of a RemoteValue: | # TODO
loss = coordinator.schedule(step_fn, args=(per_worker_iterator,))
print ("Final loss is %f" % loss.fetch()) | courses/machine_learning/deepdive2/production_ml/solutions/parameter_server_training.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Initial set-up
Load experiments used for unified dataset calibration:
- Steady-state activation [Li1997]
- Activation time constant [Li1997]
- Steady-state inactivation [Li1997]
- Inactivation time constant (fast+slow) [Li1997]
- Recovery time constant (fast+slow) [Li1997] | from experiments.ical_li import (li_act_and_tau, # combines steady-state activation and time constant
li_inact_1000,
li_inact_kin_80,
li_recov)
modelfile = 'models/nygren_ical.mmt' | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Plot steady-state and time constant functions of original model | from ionchannelABC.visualization import plot_variables
sns.set_context('talk')
V = np.arange(-140, 50, 0.01)
nyg_par_map = {'di': 'ical.d_inf',
'f1i': 'ical.f_inf',
'f2i': 'ical.f_inf',
'dt': 'ical.tau_d',
'f1t': 'ical.tau_f_1',
'f2t': 'ical.tau_f_2'}
f, a... | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Set up prior ranges for each parameter in the model.
See the modelfile for further information on specific parameters. Prepending `log_' has the effect of setting the parameter in log space. | limits = {'ical.p1': (-100, 100),
'ical.p2': (0, 50),
'log_ical.p3': (-7, 3),
'ical.p4': (-100, 100),
'ical.p5': (0, 50),
'log_ical.p6': (-7, 3)}
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
# Test this... | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Run ABC calibration | db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "nygren_ical_dgate_unified.db"))
logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG) | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Initialise ABCSMC (see pyABC documentation for further details).
IonChannelDistance calculates the weighting applied to each datapoint based on the experimental variance. | abc = ABCSMC(models=model,
parameter_priors=prior,
distance_function=IonChannelDistance(
exp_id=list(observations.exp_id),
variance=list(observations.variance),
delta=0.05),
population_size=ConstantPopulationSize(2000),
... | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Analysis of results | history = History(db_path)
history.all_runs()
df, w = history.get_distribution(m=0)
df.describe()
sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
g = plot_sim_results(modelfile,
li_act_and_tau,
df=df, w=w)
plt.tight_layout()
... | docs/examples/human-atrial/nygren_ical_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Scatter Chart
Scatter Chart Selections
Click a point on the Scatter plot to select it. Now, run the cell below to check the selection. After you've done this, try holding the ctrl (or command key on Mac) and clicking another point. Clicking the background will reset the selection. | x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(20)
y_data = np.random.randn(20)
scatter_chart = Scatter(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc}, default_colors=['dodgerblue'],
interactions={'click': 'select'},
selected_style={'opacity': 1.0, 'fil... | examples/Mark Interactions.ipynb | rmenegaux/bqplot | apache-2.0 |
Scatter Chart Interactions and Tooltips | from ipywidgets import *
x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(20)
y_data = np.random.randn(20)
dd = Dropdown(options=['First', 'Second', 'Third', 'Fourth'])
scatter_chart = Scatter(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc}, default_colors=['dodgerblue'],
names=... | examples/Mark Interactions.ipynb | rmenegaux/bqplot | apache-2.0 |
Line Chart | # Adding default tooltip to Line Chart
x_sc = LinearScale()
y_sc = LinearScale()
x_data = np.arange(100)
y_data = np.random.randn(3, 100)
def_tt = Tooltip(fields=['name', 'index'], formats=['', '.2f'], labels=['id', 'line_num'])
line_chart = Lines(x=x_data, y=y_data, scales= {'x': x_sc, 'y': y_sc},
... | examples/Mark Interactions.ipynb | rmenegaux/bqplot | apache-2.0 |
Bar Chart | # Adding interaction to select bar on click for Bar Chart
x_sc = OrdinalScale()
y_sc = LinearScale()
x_data = np.arange(10)
y_data = np.random.randn(2, 10)
bar_chart = Bars(x=x_data, y=[y_data[0, :].tolist(), y_data[1, :].tolist()], scales= {'x': x_sc, 'y': y_sc},
interactions={'click': 'select'},
... | examples/Mark Interactions.ipynb | rmenegaux/bqplot | apache-2.0 |
Histogram | # Adding tooltip for Histogram
x_sc = LinearScale()
y_sc = LinearScale()
sample_data = np.random.randn(100)
def_tt = Tooltip(formats=['', '.2f'], fields=['count', 'midpoint'])
hist = Hist(sample=sample_data, scales= {'sample': x_sc, 'count': y_sc},
tooltip=def_tt, display_legend=True, labels=['... | examples/Mark Interactions.ipynb | rmenegaux/bqplot | apache-2.0 |
You use the yerr argument of the function plt.errorbar() in order to specify what your error rate in the y-direction is. There's also an xerr optional argument, if your error is actually in the x-direction.
What about the histograms we built from the color channels of the images in last week's lectures? We can use matp... | x = np.random.normal(size = 100)
_ = plt.hist(x, bins = 20) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
plt.hist() has only 1 required argument: a list of numbers.
However, the optional bins argument is very useful, as it dictates how many bins you want to use to divide up the data in the required argument. Too many bins and every bar in the histogram will have a count of 1; too few bins and all your data will end up in ... | _ = plt.hist(x, bins = 2) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
And too many: | _ = plt.hist(x, bins = 200) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
Picking the number of bins for histograms is an art unto itself that usually requires a lot of trial-and-error, hence the importance of having a good visualization setup!
Another point on histograms, specifically its lone required argument: matplotlib expects a 1D array.
This is important if you're trying to visualize,... | import matplotlib.image as mpimg
img = mpimg.imread("Lecture22/image1.png") # Our good friend!
channel = img[:, :, 0] # The "R" channel
_ = plt.hist(channel) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
Offhand, I don't know what this is, but it definitely is not the intensity histogram we were hoping for.
Here's the magical way around it: all NumPy arrays (which images objects are!) have a flatten() method.
This function is dead simple: no matter how many dimensions the NumPy array has, whether it's a grayscale image... | print(channel.shape) # Before
flat = channel.flatten()
print(flat.shape) # After | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
Then just feed the flattened array into the hist method: | _ = plt.hist(flat) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
The last type of plot we'll discuss here isn't really a "plot" in the sense as the previous ones have been, but it is no less important: showing images! | img = mpimg.imread("Lecture22/image1.png")
plt.imshow(img) | lectures/Lecture24.ipynb | eds-uga/cbio4835-sp17 | mit |
Setting EEG Montage (using standard montages)
In the case where your data don't have locations you can set them
using a :class:mne.channels.Montage. MNE comes with a set of default
montages. To read one of them do: | montage = mne.channels.read_montage('standard_1020')
print(montage) | 0.18/_downloads/11f39f61bd7f4cfd5791b0d10da462f2/plot_eeg_erp.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Model initialization
The uniform model doesn't take any special initialization arguments, so the initialization is straightforward. | tm = UniformModel() | notebooks/example_uniform_model.ipynb | hpparvi/PyTransit | gpl-2.0 |
OpenCL
Usage
The OpenCL version of the uniform model, pytransit.UniformModelCL works identically to the Python version, except that the OpenCL context and queue can be given as arguments in the initialiser, and the model evaluation method can be told to not to copy the model from the GPU memory. If the context and queu... | import pyopencl as cl
from pytransit import UniformModelCL
devices = cl.get_platforms()[0].get_devices()[2:]
ctx = cl.Context(devices)
queue = cl.CommandQueue(ctx)
tm_cl = UniformModelCL(cl_ctx=ctx, cl_queue=queue)
tm_cl.set_data(times_sc)
plot_transits(tm_cl) | notebooks/example_uniform_model.ipynb | hpparvi/PyTransit | gpl-2.0 |
GPU vs. CPU Performance
The performance difference between the OpenCL and Python versions depends on the CPU, GPU, number of simultaneously evaluated models, amount of supersampling, and whether the model data is copied from the GPU memory. The performance difference grows in the favour of OpenCL model with the number ... | times_sc2 = tile(times_sc, 20) # 20000 short cadence datapoints
times_lc2 = tile(times_lc, 50) # 5000 long cadence datapoints
tm_py = UniformModel()
tm_cl = UniformModelCL(cl_ctx=ctx, cl_queue=queue)
tm_py.set_data(times_sc2)
tm_cl.set_data(times_sc2)
%%timeit
tm_py.evaluate_pv(pvp)
%%timeit
tm_cl.evaluate_pv(pv... | notebooks/example_uniform_model.ipynb | hpparvi/PyTransit | gpl-2.0 |
數位數字資料是解析度為8*8的手寫數字影像,總共有1797筆資料。預設為0~9十種數字類型,亦可由n_class來設定要取得多少種數字類型。
輸出的資料包含
1. ‘data’, 特徵資料(179764)
2. ‘images’, 影像資料(1797*88)
3. ‘target’, 資料標籤(1797)
4. ‘target_names’, 選取出的標籤列表(與n_class給定的長度一樣)
5. ‘DESCR’, 此資料庫的描述
可以參考Classification的Ex1
(二)以疊代方式計算模型
RFE以排除最不具目標影響力的特徵,做特徵的影響力排序。並且將訓練用的特徵挑選至n_features_to_select所給定的特... | # Create the RFE object and rank each pixel
svc = SVC(kernel="linear", C=1)
rfe = RFE(estimator=svc, n_features_to_select=1, step=1)
rfe.fit(X, y)
ranking = rfe.ranking_.reshape(digits.images[0].shape) | Feature_Selection/ipython_notebook/ex2_Recursive_feature_elimination.ipynb | dryadb11781/machine-learning-python | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.