markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Relu
perfect for blacking out everyhing beyong threshold
this is just what everyone actually uses | def np_relu(x):
return np.maximum(0, x)
x = np.arange(-10, 10, 0.01)
y = np_relu(x)
centerAxis()
plt.plot(x,y,lw=3) | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
The classic VGG16 Architecture | def predict(model, img_path):
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for e... | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
VGG starts with a number of convolutional blocks for feature extraction and ends with a fully connected classifier | vgg16_model.summary()
!curl -O https://upload.wikimedia.org/wikipedia/commons/thumb/d/de/Beagle_Upsy.jpg/440px-Beagle_Upsy.jpg | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
predict(model = vgg16_model, img_path = '440px-Beagle_Upsy.jpg')
!curl -O https://djcordhose.github.io/ai/img/cat-bonkers.png
predict(model = vgg16_model, img_path = 'cat-bonkers.png')
!curl -O https://djcordhose.github.io/ai/img/squirrels/original/Michigan-MSU-raschka.jpg
!curl -O https://djcordhose.github.io/ai/im... | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit | |
predict(model = vgg16_model, img_path = 'Michigan-MSU-raschka.jpg')
predict(model = vgg16_model, img_path = 'Black_New_York_stuy_town_squirrel_amanda_ernlund.jpeg')
predict(model = vgg16_model, img_path = 'london.jpg') | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit | |
What does the CNN "see"?
Does it "see" the right thing?
Each filter output of a convolutional layer is called feature channel
with each input they should ideally either be
blank if they do not recognize any feature in the input or
encode what the feature channel "sees" in the input
feature channels directly before FC ... | # create a tmp dir in the local directory this notebook runs in, otherwise quiver will fail (and won't tell you why)
!rm -rf tmp
!mkdir tmp | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
Visualizing feature channels using Quiver
Only works locally | # https://github.com/keplr-io/quiver
# Alternative with more styles of visualization: https://github.com/raghakot/keras-vis
# https://github.com/keplr-io/quiver
from quiver_engine import server
server.launch(vgg16_model, input_folder='.', port=7000)
# open at http://localhost:7000/
# interrupt kernel to return contr... | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
Modern Alternative: Resnet
https://keras.io/applications/#resnet50
https://arxiv.org/abs/1512.03385
New Layer Type: https://keras.io/layers/normalization/ | from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
resnet_model = ResNet50(weights='imagenet')
resnet_model.summary()
predict(model = resnet_model, img_path = 'cat-bonkers.png')
predic... | notebooks/workshops/tss/cnn-intro.ipynb | DJCordhose/ai | mit |
Leitura usando matplotlib native e com PIL
O matplotlib possui a leitura nativa de imagens no formato png. Quando este formato é lido, a imagem é automaticamente mapeada da faixa 0 a 255 contido no pixel uint8 da imagem para float 0 a 1 no pixel do array lido
Já se o formato for outro, se o PIL estiver instalado, a lei... | f = mpimg.imread('../data/cameraman.tif')
print(f.dtype,f.shape,f.max(),f.min()) | deliver/Leitura-Display-imagem-com-matplotlib.ipynb | robertoalotufo/ia898 | mit |
Leitura de imagem colorida formato TIFF
Quando a imagem é colorida e não está no formato png, matplotlib utiliza PIL para leitura. O array terá o tipo uint8 e o shape do array é organizado em (H, W, 3). | fcor = mpimg.imread('../data/boat.tif')
print(fcor.dtype,fcor.shape,fcor.max(),fcor.min()) | deliver/Leitura-Display-imagem-com-matplotlib.ipynb | robertoalotufo/ia898 | mit |
Leitura de imagem colorida formato png
Se a imagem está no formato png, o matplotlib mapeia os pixels de 0 a 255 para float de 0 a 1.0 | fcor2 = mpimg.imread('../data/boat.tif')
print(fcor2.dtype, fcor2.shape, fcor2.max(), fcor2.min()) | deliver/Leitura-Display-imagem-com-matplotlib.ipynb | robertoalotufo/ia898 | mit |
Mostrando as imagens lidas | %matplotlib inline
plt.imshow(f, cmap='gray')
plt.colorbar()
plt.imshow(fcor)
plt.colorbar()
plt.imshow(fcor2)
plt.colorbar() | deliver/Leitura-Display-imagem-com-matplotlib.ipynb | robertoalotufo/ia898 | mit |
Observe que o display mostra apenas a última chamada do imshow | plt.imshow(fcor2)
plt.imshow(fcor)
plt.imshow(f, cmap='gray') | deliver/Leitura-Display-imagem-com-matplotlib.ipynb | robertoalotufo/ia898 | mit |
Quick demo | # Let's see a very quick demonstration, how CogStat works
# All results can be seen below. Appropriate graphs and statistics were chosen and compiled automatically by CogStat.
# Load some data
data = cs.CogStatData(data = os.path.join(cs_dir, 'sample_data', 'example_data.csv'))
# Display the data below
cs.display(data... | cogstat/docs/CogStat Jupyter Notebook tutorial.ipynb | cogstat/cogstat | gpl-3.0 |
Import and display data
CogStat can import from three sources:
- It can read from file (either SPSS .sav file or tab separated txt files)
- It can convert pandas data frames (only in the Jupyter Notebook interface)
- It can read multiline string | ### Import from file ###
"""
The file should have the following structure:
- The first line should contain the names of the variables.
- The second lines can contain the measurement levels (int, ord or nom). This is optional, but recommended.
- The rest of the file is your data.
"""
# New CogStat data can be created ... | cogstat/docs/CogStat Jupyter Notebook tutorial.ipynb | cogstat/cogstat | gpl-3.0 |
Filter outliers
Cases can be filtered based on outliers.
In its simplest form (2sd method) a case is an outlier if based on the appropriate variable its value is more extreme than the average +- 2 standard deviation.
When several variables are used for filtering, a case will be an outlier, if it is an outlier based on ... | # Let's import a data file
data = cs.CogStatData(data = os.path.join(cs_dir, 'sample_data', 'example_data.csv'))
cs.display(data.print_data())
# To turn on filtering based on a singla variable:
# Note that even if only a single variable is given, it should be in a list.
cs.display(data.filter_outlier(['X']))
cs.displa... | cogstat/docs/CogStat Jupyter Notebook tutorial.ipynb | cogstat/cogstat | gpl-3.0 |
Analyse the data
CogStat collects the most typical analysis into a single task, and chooses the appropriate methods. This is one of the main strength of CogStat: you don't have to figure out what statistics to use, and don't have to click through several menus and dialogs, but you get all the main (and only the relevan... | # Here are all the available CogStat analysis packages
# Hopefully all these method names speak for themselves
# In a function the chosen analysis will automatically depend on the measurement level, and other properties of the data.
# Load some data
data = cs.CogStatData(data=os.path.join(cs_dir, 'sample_data', 'examp... | cogstat/docs/CogStat Jupyter Notebook tutorial.ipynb | cogstat/cogstat | gpl-3.0 |
Summary (Cheatsheet) | ### Import data ###
# Import from file
data = cs.CogStatData(data=os.path.join(cs_dir, 'sample_data', 'example_data.sav'))
data = cs.CogStatData(data=os.path.join(cs_dir, 'sample_data', 'example_data.csv'))
data = cs.CogStatData(data=os.path.join(cs_dir, 'sample_data', 'example_data.csv'),
measur... | cogstat/docs/CogStat Jupyter Notebook tutorial.ipynb | cogstat/cogstat | gpl-3.0 |
To check the full documentation you can always refer to https://root.cern/doc/master (and then switch to the documentation for your particular ROOT version with the drop-down menu at the top of the page).
Drawing a histogram
Drawing options documentation
The link above contains the documentation for the histogram drawi... | %jsroot on
c = ROOT.TCanvas()
#h.SetLineColor(ROOT.kBlue)
#h.SetFillColor(ROOT.kBlue)
#h.GetXaxis().SetTitle("value")
#h.GetYaxis().SetTitle("count")
#h.SetTitle("My histo with latex: p_{t}, #eta, #phi")
h.Draw() # draw the histogram on the canvas
c.Draw() # draw the canvas on the screen | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
ROOT functions
The type that represents an arbitrary one-dimensional mathematical function in ROOT is TF1.<br>
Similarly, TF2 and TF3 represent 2-dimensional and 3-dimensional functions.
As an example, let's define and plot a simple surface: | f2 = ROOT.TF2("f2", "sin(x*x - y*y)", xmin=-2, xmax=2, ymin=-2, ymax=2)
c = ROOT.TCanvas()
f2.Draw("surf1") # to get a surface instead of the default contour plot
c.Draw() | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
Fitting a histogram
Let's see how to perform simple histogram fits of arbitrary functions. We will need a TF1 that represents the function we want to use for the fit.
This time we define our TF1 as a C++ function (note the usage of the %%cpp magic to define some C++ inline). Here we define a simple gaussian with scale ... | %%cpp
double gaussian(double *x, double *par) {
return par[0]*TMath::Exp(-TMath::Power(x[0] - par[1], 2.) / 2.)
/ TMath::Sqrt(2 * TMath::Pi());
} | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
The function signature, that takes an array of coordinates and an array of parameters as inputs, is the generic signature of functions that can be used to construct a TF1 object: | fitFunc = ROOT.TF1("fitFunc", ROOT.gaussian, xmin=-5, xmax=5, npar=2) | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
Now we fit our h histogram with fitFunc: | res = h.Fit(fitFunc) | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
Drawing the histogram now automatically also shows the fitted function: | c2 = ROOT.TCanvas()
h.Draw()
c2.Draw() | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
For the particular case of a gaussian fit, we could also have used the built-in "gaus" function, as we did when we called FillRandom (for the full list of supported expressions see here): | res = h.Fit("gaus")
c3 = ROOT.TCanvas()
h.Draw()
c3.Draw() | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
For more complex binned and unbinned likelihood fits, check out RooFit, a powerful data modelling framework integrated in ROOT.
ROOT graphs
TGraph is a type useful for scatter plots.
Their drawing options are documented here.
Like for histograms, the aspect of TGraphs can be greatly customized, they can be fitted with ... | g = ROOT.TGraph()
for x in range(-20, 21):
y = -x*x
g.AddPoint(x, y)
c4 = ROOT.TCanvas()
g.SetMarkerStyle(7)
g.SetLineColor(ROOT.kBlue)
g.SetTitle("My graph")
g.Draw()
c4.Draw() | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
The same graph can be displayed as a bar plot: | c5 = ROOT.TCanvas()
g.SetTitle("My graph")
g.SetFillColor(ROOT.kOrange + 1) # base colors can be tweaked by adding/subtracting values to them
g.Draw("AB1")
c5.Draw() | SoftwareCarpentry/04-histograms-and-graphs.ipynb | root-mirror/training | gpl-2.0 |
Shebang: /usr/bin/python2 or /usr/bin/python3
main function
What the heck is __name__ or __file__ ? Snake charmers
Adding parameters to your script ...
Your first imports and function parameters: *args, **kwargs
$ python hello_montoya.py "Hello" "My name is Iñigo Montoya" "You killed my father" "Prepare to Die"
Encodi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def main(*args, **kwargs):
"""Simple main function that prints stuff"""
print(args) # args is a tuple of positional params
print(kwargs) # kwargs is a dict with keyword params
## The names are just a mere convention
if __name__ == '__main__':
... | workshop/fundamentals/fundamental.ipynb | miguelgr/python-crash-course | mit |
Programming Types
Boolean: True, False
NoneType: None
Mutable / Immutable Objects
Some immutable types:
int, float, long, complex
str
bytes
tuple
frozen set
Some mutable types:
byte array
list
set
dict | # Immutable Objects
age = 60 # int
weight = 77.8 # float
infinite = float('inf')
name = "Rick" # basestring/str
nick_names = ("Sanchez", "Grandpa") # tuple
jobs = frozenset(("scientist", "inventor", "arms salesman", "store owner"))
# Mutable Objects
interests = ['interdimensional travel', 'nihilism', 'alcohol']
inf... | workshop/fundamentals/fundamental.ipynb | miguelgr/python-crash-course | mit |
Why immutable objects? | # integers
print(id(age))
age += 10
print(id(age))
age -= 10
print(id(age))
# Strings
print(name + ": Wubba lubba dub-dub!!")
print(name.replace("R", "r"))
print(name.upper(), name.lower())
# Tuples
operations = "test", # note the comma as it makes it a tuple!!! | tuple.count/index
print(id(operations))
operation... | workshop/fundamentals/fundamental.ipynb | miguelgr/python-crash-course | mit |
Operators
Official Docs
Arithmetic Operators: + - / // * ** % | print(1 + 3)
print(2 ** 10)
print(5 % 3)
print(10 / 4) 2
from __future__ import division
print(10 / 4) 2.5 # float division
10 // 4 # in python 3 to get integer division
import operator
operator.add(2, 4)
operator.gt(10, 5) | workshop/fundamentals/fundamental.ipynb | miguelgr/python-crash-course | mit |
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps:
First we must compute the distances between all test examples and all train examples.
Given these distances, for each test example we find the k nearest examples and have them vote for the ... | # Open cs231n/classifiers/k_nearest_neighbor.py and implement
# compute_distances_two_loops.
# Test your implementation:
dists = classifier.compute_distances_two_loops(X_test)
print(dists.shape)
# We can visualize the distance matrix: each row is a single test example and
# its distances to training examples
plt.imsh... | assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb | billzhao1990/CS231n-Spring-2017 | mit |
Inline Question #1: Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.)
What in the data is the cause behind the distinctly bright rows?
What causes the colu... | # Now implement the function predict_labels and run the code below:
# We use k = 1 (which is Nearest Neighbor).
y_test_pred = classifier.predict_labels(dists, k=1)
# Compute and print the fraction of correctly predicted examples
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print... | assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb | billzhao1990/CS231n-Spring-2017 | mit |
You should expect to see approximately 27% accuracy. Now lets try out a larger k, say k = 5: | y_test_pred = classifier.predict_labels(dists, k=5)
num_correct = np.sum(y_test_pred == y_test)
accuracy = float(num_correct) / num_test
print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)) | assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb | billzhao1990/CS231n-Spring-2017 | mit |
You should expect to see a slightly better performance than with k = 1. | # Now lets speed up distance matrix computation by using partial vectorization
# with one loop. Implement the function compute_distances_one_loop and run the
# code below:
dists_one = classifier.compute_distances_one_loop(X_test)
# To ensure that our vectorized implementation is correct, we make sure that it
# agrees ... | assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb | billzhao1990/CS231n-Spring-2017 | mit |
Cross-validation
We have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation. | num_folds = 5
k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]
X_train_folds = []
y_train_folds = []
################################################################################
# TODO: #
# Split up the training data into folds. After splittin... | assignment1/.ipynb_checkpoints/knn-checkpoint.ipynb | billzhao1990/CS231n-Spring-2017 | mit |
RTL and Implimentation Schamatics are from Xilinx Vivado 2016.1
Read Only Memory (ROM)
ROM is a memory structure that holds static information that can only be read from. In other words, these are hard-coded instruction memory. That should never change. Furthermore, this data is held in a sort of array; for example, we... | #use type casting on list genrator to store 0-9 in 8bit binary
TupleROM=tuple([bin(i, 8) for i in range(10)])
TupleROM
f'accesss location 6: {TupleROM[6]}, read contents of location 6 to dec:{int(TupleROM[6], 2)}' | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
And if we try writing to the tuple we will get an error | #TupleROM[6]=bin(16,2) | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Random and Sequntial Access Memory
So to start off with the Random in RAM does not mean Random in a proplositc sence. It refares to Random as in you can randomly access any part of the data array opposed to the now specility sequantil only memory wich are typicly made with a counter or stat machine to sequance that aca... | @block
def ROMLoaded(addr, dout):
"""
A ROM laoded with data already incoded in the structer
insted of using myHDL inchanced parmter loading
I/O:
addr(Signal>4): addres; range is from 0-3
dout(Signal>4): data at each address
"""
@always_comb
def readAction():
... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
ROMLoaded RTL
<img src='ROMLoadedRTL.png'>
ROMLoaded Synthesis
<img src='ROMLoadedSynth.png'> | @block
def ROMLoaded_TBV():
"""Verilog Only Testbench for `ROMLoaded`"""
clk = Signal(bool(0))
addr=Signal(intbv(0)[4:])
dout=Signal(intbv(0)[4:])
DUT=ROMLoaded(addr, dout)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(10)
... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
With myHDL we can dynamicaly load the contents that will be hard coded in the convertion to verilog/VHDL wich is an ammazing benfict for devlopment as is sean here | @block
def ROMParmLoad(addr, dout, CONTENT):
"""
A ROM laoded with data from CONTENT input tuple
I/O:
addr(Signal>4): addres; range is from 0-3
dout(Signal>4): data at each address
Parm:
CONTENT: tuple size 4 with contende must be no larger then 4bit
"""
@always_comb... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
ROMParmLoad RTL
<img src="ROMParmLoadRTL.png">
ROMParmLoad Synthesis
<img src="ROMParmLoadSynth.png"> | @block
def ROMParmLoad_TBV():
"""Verilog Only Testbench for `ROMParmLoad`"""
clk=Signal(bool(0))
addr=Signal(intbv(0)[4:])
dout=Signal(intbv(0)[4:])
CONTENT=tuple([i for i in range(4)][::-1])
DUT=ROMParmLoad(addr, dout, CONTENT)
@instance
def clk_signal():
while True:
... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
we can also create rom that insted of being asynchronous is synchronous | @block
def ROMParmLoadSync(addr, dout, clk, rst, CONTENT):
"""
A ROM laoded with data from CONTENT input tuple
I/O:
addr(Signal>4): addres; range is from 0-3
dout(Signal>4): data at each address
clk (bool): clock feed
rst (bool): reset
Parm:
CONTENT: tuple si... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
ROMParmLoadSync RTL
<img src="ROMParmLoadSyncRTL.png">
ROMParmLoadSync Synthesis
<img src="ROMParmLoadSyncSynth.png"> | @block
def ROMParmLoadSync_TBV():
"""Python Only Testbench for `ROMParmLoadSync`"""
addr=Signal(intbv(0)[4:])
dout=Signal(intbv(0)[4:])
clk=Signal(bool(0))
rst=Signal(bool(0))
CONTENT=tuple([i for i in range(4)][::-1])
DUT=ROMParmLoadSync(addr, dout, clk, rst, CONTENT)
@inst... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
SeqROMEx RTL
<img src="SeqROMExRTL.png">
SeqROMEx Synthesis
<img src="SeqROMExSynth.png"> | @block
def SeqROMEx_TBV():
"""Verilog Only Testbench for `SeqROMEx`"""
dout=Signal(intbv(0)[4:])
clk=Signal(bool(0))
rst=Signal(bool(0))
DUT=SeqROMEx(clk, rst, dout)
@instance
def clk_signal():
while True:
clk.next = not clk
yield delay(1)
... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
read and write memory | @block
def RAMConcur(addr, din, writeE, dout, clk):
"""
Random access read write memeory
I/O:
addr(signal>4): the memory cell arrdress
din (signal>4): data to write into memeory
writeE (bool): write enable contorl; false is read only
dout (signal>4): the data out
clk ... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
RAMConcur RTL
<img src="RAMConcurRTL.png">
RAMConcur Synthesis
<img src="RAMConcurSynth.png"> | @block
def RAMConcur_TBV():
"""Verilog Only Testbench for `RAMConcur`"""
addr=Signal(intbv(0)[4:])
din=Signal(intbv(0)[4:])
writeE=Signal(bool(0))
dout=Signal(intbv(0)[4:])
clk=Signal(bool(0))
CONTENT=tuple([i for i in range(4)][::-1])
DUT=RAMConcur(addr, din, writeE, dout, clk)
... | myHDL_ComputerFundamentals/Memorys/.ipynb_checkpoints/Memory-checkpoint.ipynb | PyLCARS/PythonUberHDL | bsd-3-clause |
Final
Chinmai Raman
5/21/2016
Given three real-valued functions of time x(t), y(t), z(t), consider the following coupled first-order ODEs:
$x˙ = −y − z, y˙ = x + ay, z˙ = b + z(x − c)$
where a = b = 0.2 and c is a parameter that we will tune. Note that this system has a single nonlinear term
xz.
I will be exploring th... | ros = p1.Rossler(2)
ros.run()
ros.plotx()
ros.ploty()
ros.plotz()
ros.plotxy()
ros.plotyz()
ros.plotxz()
ros.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
Problem 2 (c = 2, 3, 4, 4.15, 4.2, 5.7)
c = 2 is plotted above
c = 3 | ros3 = p1.Rossler(3)
ros3.run()
ros3.plotx()
ros3.plotxy()
ros3.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
Already we can see a bifurcation occuring in the y vs x and z vs y vs x graphs that were not there in the case of c =2. The nonlinearity in the z variable has begun to become active in that the trajectory is leaving the x-y plane.
The x vs t graph shows us that the x-values are now alternating between four values, as ... | ros4 = p1.Rossler(4)
ros4.run()
ros4.plotx()
ros4.plotxy()
ros4.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
Another bifurcation has now occured and is apparent in the y vs x graph. The limits of the x-values are now eight-fold; the number of values that x converges to has doubled again. The influence of the non-linearity in z is now very obvious.
c = 4.15 | ros415 = p1.Rossler(4.15)
ros415.run()
ros415.plotx()
ros415.plotxy()
ros415.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
The period doubling is occuring at an increasing rate. This is demonstrated by the thicker lines in the xy and xyz graphs. This period doubling phase will soon end as the system approaches complete chaos and the our predictive power decreases greatly.
c = 4.2 | ros42 = p1.Rossler(4.2)
ros42.run()
ros42.plotx()
ros42.plotxy()
ros42.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
The lines are getting thicker as the bifurcations increase at an increasing rate. It is now not immediately apparent how many asymptotic values x approaches from the x vs t graph.
c = 5.7 | ros57 = p1.Rossler(5.7)
ros57.run()
ros57.plotx()
ros57.plotxy()
ros57.plotxyz() | Final.ipynb | ChinmaiRaman/phys227-final | mit |
The period doubling cascade has given rise to a chaotic attractor with a single lobe. This is an example of spiral-type chaos and exhibits the characteristic sensitivity to initial conditions. The oscillations in the x vs t graph are now completely chaotic and irregular in amplitude. The logistic update map also displa... | p1.plotmaxima('x')
p1.plotmaxima('y')
p1.plotmaxima('z') | Final.ipynb | ChinmaiRaman/phys227-final | mit |
Magic commands
Magic commands start with % charcter, e.g.: | %cd /content | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Shell commands
Shell commands must be precided by ! character, e.g.: | !ls -lah | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
2 - Colab sessions
I invite you to explore Colab front-end menus and see what you get.
When you open a Colab file, you gain a virtual machine session inside the Google Compute Engine.
Special attention should be payed to Colab sessions operation. On one hand, code, text and last result of each code cell execution in t... | !pip freeze | grep keras
print()
!pip freeze | grep tensorflow
!apt update
!apt list --upgradable
!apt upgrade
!python3 --version
!uname -r | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
3 - Hands-on TensorFlow + Keras
3.1 - Load tensor flow | import tensorflow as tf | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
3.2 - Dataset preparation
Import dataset
Modified NIST (MNIST) is a database of handwritten digits. It encompasses a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set produced by EUA National Institute for Standards and Technology (NIST). Images have a fixed-size image a... | mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data() #verificar se esta tupla é realmente necessária
print ("Training set info:",x_train.shape)
print ("Train target info:",y_train.shape)
print ("Test set info:",x_test.shape)
print ("Test target info:",y_test.shape) | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Show sample images | import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for i in range(100,200):
ax = plt.subplot(10, 10, i-99)
plt.axis("off")
plt.imshow(x_train[i].reshape(28,28))
plt.gray() | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Normalize data between [0, 1] | x_train_norm, x_test_norm = x_train / 255.0, x_test / 255.0
plt.figure(figsize=(10, 10))
for i in range(100):
ax = plt.subplot(10, 10, i+1)
plt.axis("off")
plt.imshow(x_test_norm[i].reshape(28,28))
plt.gray() | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
3.3 - Create and Initialize Network Perceptron Architecture
The code bellow creates a single hidden layer perceptron.
Task 1 Calculate the number of parameters of the model bellow. | model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
#Reference: https://towardsdatascience.com/how-to-calculate-the-number-of-parameters-in-keras-model... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 2 Create a new version of the above code converting this sequential implementation into a functional one. Then encapsulate it in a Python function. Make the number of neurons in the hidden layer, the respective activation function and the dropout frequency parameters of such function. Implement it on the code cell... | def createFuncModel(hiddenNeurons: int = 128, activationFunc: str = "relu", dropoutFrequency: float=0.2):
input = tf.keras.Input(shape=(28,28))
layer1 = tf.keras.layers.Flatten()
layer2 = tf.keras.layers.Dense(hiddenNeurons, activation=activationFunc)
layer3 = tf.keras.layers.Dropout(dropoutFrequency)
layer4 ... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
3.4 - Network training
Details about training process can be found in the keras documentation
Present model details | model.summary() | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 3: Compare the number of parameters calculated by yourself to the one provided by model.summary
Number of parameters are equal in both ways (calculated and returned by summary function)
Build network graph object for training | model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
) | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 4: If you try to change loss parameter to 'categorical_crossentropy' the model.fit will stop working. Please explain the reasons why. Make on the next text cell your considerations about Task 4.
Categorical_crossentropy loss function requires the labels to be encoded in a one-hot representation, that is, each labe... | EPOCHS = 10
H = model.fit(x_train_norm, y_train, epochs=EPOCHS) | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 5: Use the 'validation_split' parameter on the previous code cell to dedicate 10% of the training set to validation and run it again. Put your code on the cell bellow. | H = model.fit(x_train_norm, y_train, epochs=EPOCHS, validation_split = 0.1) | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 6: Take note of the accuracy values. Then, run the model construction, the model compilation, and training again and see what happens with the accuracies. Pay attention to implicit parameters initialization and to the effective number o epochs of training in each case.
Scribe your answer to Task 6 on the text cel... | plt.figure(figsize=(10, 10))
plt.plot( H.history["loss"], label="train_loss")
plt.plot( H.history["accuracy"], label="train_acc")
plt.plot( H.history["val_loss"], label="validation_loss")
plt.plot( H.history["val_accuracy"], label="validation_acc")
plt.title("Loss / accuracy evolution")
plt.xlabel("Epoch #")
plt.ylabe... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 7: Include the validation loss and accuraccy on the above chart
3.5 - Test Network
The final model must be evaluated in order to check its quality. | print("Train:")
Train_Evaluation = model.evaluate(x_train_norm, y_train, verbose=2)
print("Test:")
Test_Evaluation = model.evaluate(x_test_norm, y_test, verbose=2) | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 8: Notice the differences between the loss and accuracy presented by the 'model.fit' and the 'model.evaluate'. Don't find out such a strange outcome? Try to explain it on the following text cell.
Model.fit method trains the model by adjusting the weights and minimizing the losses whereas the Model.evaluate meth... | predictions = model.predict(x_test[:10])
predictions
plt.figure(figsize=(10, 10))
for i in range(10):
ax = plt.subplot(10, 10, i+1)
plt.axis("off")
plt.imshow(x_test[i].reshape(28,28))
plt.gray()
print([j for j in range(10) if predictions[i][j] == 1])
| Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
3.6 - Save, del and load trained network | print("Train:")
Train_Evaluation = model.evaluate(x_train_norm, y_train, verbose=2)
print("Test:")
Test_Evaluation = model.evaluate(x_test_norm, y_test, verbose=2)
model.save('ultimate_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model object
from keras.models import load_model... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 10: Modify the above code to persist and recover your HDF5 on google drive. See the following link for more information about how to mount your Google Drive into Colab.
3.7 - Using training checkpoints
The code bellow save the model at each epoch in HDF5 format.
Task 11: Use the callback options 'save_freq' and ... | %cd ../
import os
checkpoint_path = "/content/MyFirstCkpt/"
checkpoint_dir = os.path.dirname(checkpoint_path)
# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_path +'model.{epoch:02d}-{val_loss:.2f}.h5',
save_weights_only=True,
verbose... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 12: Produce in the cells bellow code pieces that help you to get the results necessary to fill in the following tables:
Hidden layer Neurons | Train accuracy |Test accuracy
---- |-----|-----
16| 0.8972 | 0.9396
32 | 0.9475 | 0.9630
64| 0.9723 | 0.9747
128| 0.9854 | 0.9801
256 | 0.9895 | 0.9795 | #Put here the code for obtaining the values for distinct amount of hidden layer neurons.
newModel = createFuncModel(hiddenNeurons=256)
newModel.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
H = newModel.fit(x_train_norm, y_train, epochs=10, validation_split = 0.1... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
Task 13: Using the number of neurons that best performed over the test set in the previous table, fill in the following one.
Dropout frequency | Train accuracy |Test accuracy
--- |-----|-----
0.1| 0.9894 | 0.9787
0.2 | 0.9839 | 0.9791
0.3| 0.9802 | 0.9786
0.4| 0.9714 | 0.9778
0.5 | 0.9622 | 0.9758 | #Put here the code for obtaining the values for distinct values of dropout frequency.
newModel = createFuncModel(hiddenNeurons=128,dropoutFrequency=0.5)
newModel.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
H = newModel.fit(x_train_norm, y_train, epochs=10, vali... | Luiz_Fernando_De_Moura_2021_1_Practice_1_Introduction_to_Colab_and_Keras.ipynb | luizfmoura/datascience | gpl-2.0 |
1. Reading simple JSON from a local file | df = pd.read_json('data/simple.json')
df
df.info() | stop_starting_start_stopping/pandas_convert_json/pandas-convert-json.ipynb | bflaven/BlogArticlesExamples | mit |
2. Reading simple JSON from a URL | URL = 'http://raw.githubusercontent.com/BindiChen/machine-learning/master/data-analysis/027-pandas-convert-json/data/simple.json'
df = pd.read_json(URL)
df
df.info() | stop_starting_start_stopping/pandas_convert_json/pandas-convert-json.ipynb | bflaven/BlogArticlesExamples | mit |
3. Flattening nested list from JSON object | df = pd.read_json('data/nested_list.json')
df
import json
# load data using Python JSON module
with open('data/nested_list.json','r') as f:
data = json.loads(f.read())
# Flatten data
df_nested_list = pd.json_normalize(data, record_path =['students'])
df_nested_list
# To include school_name and class
df_neste... | stop_starting_start_stopping/pandas_convert_json/pandas-convert-json.ipynb | bflaven/BlogArticlesExamples | mit |
4. Flattening nested list and dict from JSON object | ### working
import json
# load data using Python JSON module
with open('data/nested_mix.json','r') as f:
data = json.loads(f.read())
# Normalizing data
df = pd.json_normalize(data, record_path =['students'])
df
# Normalizing data
df = pd.json_normalize(
data,
record_path =['students'],
meta=[
... | stop_starting_start_stopping/pandas_convert_json/pandas-convert-json.ipynb | bflaven/BlogArticlesExamples | mit |
5. Extracting a value from deeply nested JSON | df = pd.read_json('data/nested_deep.json')
df
type(df['students'][0])
# to install glom inside your python env through the notebook
# pip install glom
from glom import glom
df['students'].apply(lambda row: glom(row, 'grade.math')) | stop_starting_start_stopping/pandas_convert_json/pandas-convert-json.ipynb | bflaven/BlogArticlesExamples | mit |
Let's explore the data | products.head()
len(products)
# Sklearn does not work well with empty fields, so we're dropping all rows that have empty fields
products = products.dropna()
len(products) | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Build the word count vector for each review
Here Sklearn works different from the Graphlab.
Word counts are recorded in a sparse matrix, where every column is a unique word and every row is a review. For demonstration purposes and to stay in line with the lecture, the word_counts column is added here, but this is not a... | from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
cv.fit(products['review']) # Create the word count vector
products['word_counts'] = cv.transform(products['review'])
products.head()
products['name'].describe() | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
The total number of reviews is lower than in the lecture video. Likely due to dropping the reviews with NA's.
Explore Vulli Sophie | giraffe_reviews = products[products['name'] == 'Vulli Sophie the Giraffe Teether']
len(giraffe_reviews)
giraffe_reviews['rating'].hist()
giraffe_reviews['rating'].value_counts() | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Build a sentiment classifier
Define what's a positive and negative review | # Ignore all 3* review
products = products[products['rating'] != 3]
products['sentiment'] = products['rating'] >= 4
products.head() | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Let's train the sentiment classifier | from sklearn.cross_validation import train_test_split
# Due to the random divide between the train and test data, the model will be
# slightly different from the lectures from here on out.
train_data, test_data = train_test_split(products, test_size=0.2, random_state=42)
from sklearn.linear_model import LogisticRegr... | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Evaluate the sentiment model | from sklearn import metrics
# These metrics will be slightly different then in the lecture, due to the different
# train/test data split and differences in how the model is fitted
print ("Accuracy:", metrics.accuracy_score(test_data['sentiment'], predicted))
print ("ROC AUC Score:", metrics.roc_auc_score(test_data['s... | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Applying the learned model to understand sentiment for Giraffe | giraffe_reviews['predicted_sentiment'] = sentiment_model.predict_proba(cv.transform(giraffe_reviews['review']))[:,1]
giraffe_reviews.head() | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Sort the reviews based on the predicted sentiment and explore | giraffe_reviews.sort_values(by='predicted_sentiment', inplace=True, ascending=False)
# Despite the slightly different model, the same review is ranked highest in predicted sentiment
giraffe_reviews.head(10)
giraffe_reviews.iloc[0]['review'] | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Let's look at the negative reviews | giraffe_reviews.tail(10)
## We can see the lowest scoring review in the lecture is ranked 10th lowest in this analysis
giraffe_reviews.iloc[-1]['review'] | Machine Learning/1. Foundations A Case Study Approach/Week 3/Analyzing product sentiment.ipynb | Donnyvdm/courses | unlicense |
Fetch the daily returns for a stock | stock_rets = pf.utils.get_symbol_rets('FB') | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
Create Bayesian tear sheet | out_of_sample = stock_rets.index[-40]
pf.create_bayesian_tear_sheet(stock_rets, live_start_date=out_of_sample) | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
Lets go through these row by row:
The first one is the Bayesian cone plot that is the result of a summer internship project of Sepideh Sadeghi here at Quantopian. It's similar to the cone plot you already saw in the tear sheet above but has two critical additions: (i) it takes uncertainty into account (i.e. a short ba... | help(pf.bayesian.run_model) | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
For example, to run a model that assumes returns to be normally distributed, you can call: | # Run model that assumes returns to be T-distributed
trace = pf.bayesian.run_model('t', stock_rets) | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
The returned trace object can be directly inquired. For example might we ask what the probability of the Sharpe ratio being larger than 0 is by checking what percentage of posterior samples of the Sharpe ratio are > 0: | # Check what frequency of samples from the sharpe posterior are above 0.
print('Probability of Sharpe ratio > 0 = {:3}%'.format((trace['sharpe'] > 0).mean() * 100)) | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
But we can also interact with it like with any other pymc3 trace: | import pymc3 as pm
pm.traceplot(trace); | pyfolio/examples/bayesian.ipynb | femtotrader/pyfolio | apache-2.0 |
Create Parametrized Model
To perform the search we will use the openmc.search_for_keff function. This function requires a different function be defined which creates an parametrized model to analyze. This model is required to be stored in an openmc.model.Model object. The first parameter of this function will be modif... | # Create the model. `ppm_Boron` will be the parametric variable.
def build_model(ppm_Boron):
# Create the pin materials
fuel = openmc.Material(name='1.6% Fuel')
fuel.set_density('g/cm3', 10.31341)
fuel.add_element('U', 1., enrichment=1.6)
fuel.add_element('O', 2.)
zircaloy = openmc.Materi... | examples/jupyter/search.ipynb | liangjg/openmc | mit |
Search for the Critical Boron Concentration
To perform the search we imply call the openmc.search_for_keff function and pass in the relvant arguments. For our purposes we will be passing in the model building function (build_model defined above), a bracketed range for the expected critical Boron concentration (1,000 t... | # Perform the search
crit_ppm, guesses, keffs = openmc.search_for_keff(build_model, bracket=[1000., 2500.],
tol=1e-2, print_iterations=True)
print('Critical Boron Concentration: {:4.0f} ppm'.format(crit_ppm)) | examples/jupyter/search.ipynb | liangjg/openmc | mit |
Finally, the openmc.search_for_keff function also provided us with Lists of the guesses and corresponding keff values generated during the search process with OpenMC. Let's use that information to make a quick plot of the value of keff versus the boron concentration. | plt.figure(figsize=(8, 4.5))
plt.title('Eigenvalue versus Boron Concentration')
# Create a scatter plot using the mean value of keff
plt.scatter(guesses, [keffs[i].nominal_value for i in range(len(keffs))])
plt.xlabel('Boron Concentration [ppm]')
plt.ylabel('Eigenvalue')
plt.show() | examples/jupyter/search.ipynb | liangjg/openmc | mit |
Read repeatedly records from oscilloscope | filename = 1
if (filename == 1):
for f in glob.iglob("./data/*.h5"): # delete all .h5 files
print 'Deleting', f
os.remove(f)
else:
print 'Not removing old files, as filename {0} is not 1.'.format(filename)
osc.write(':STOP') # start recording
time.sleep(0.5)
while True:
#print('... | vxi.ipynb | ODZ-UJF-AV-CR/osciloskop | gpl-3.0 |
Read repeatedly records from oscilloscope
This should be run after the initialization step. Timeout at the end should be enlarged if not all 508 frames are transferred. | filename = 1
run_start_time = time.time()
if (filename == 1):
for f in glob.iglob("./data/*.h5"): # delete all .h5 files
print 'Deleting', f
os.remove(f)
else:
print 'Not removing old files, as filename {0} is not 1.'.format(filename)
while True:
osc.write(':WAV:SOUR CHAN1')
osc.w... | vxi.ipynb | ODZ-UJF-AV-CR/osciloskop | gpl-3.0 |
Stopwatch for timing the first loop | first_run_start_time = time.time()
raw_input()
loop_sleep_time = time.time() - first_run_start_time + 15
print loop_sleep_time
loop_sleep_time=60 | vxi.ipynb | ODZ-UJF-AV-CR/osciloskop | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.