markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Let's go ahead and execute the simulation! You'll notice that the output for multi-group mode is exactly the same as for continuous-energy. The differences are all under the hood. | # Run OpenMC
openmc.run() | docs/source/examples/mg-mode-part-i.ipynb | bhermanmit/openmc | mit |
Results Visualization
Now that we have run the simulation, let's look at the fission rate and flux tallies that we tallied. | # Load the last statepoint file and keff value
sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')
# Get the OpenMC pin power tally data
mesh_tally = sp.get_tally(name='mesh tally')
fission_rates = mesh_tally.get_values(scores=['fission'])
# Reshape array to 2D for plotting
fission_rates.shape = mesh.dimensi... | docs/source/examples/mg-mode-part-i.ipynb | bhermanmit/openmc | mit |
Sensitivity map of SSP projections
This example shows the sources that have a forward field
similar to the first SSP vector correcting for ECG. | # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
from mne import read_forward_solution, read_proj, sensitivity_map
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/subjects'
... | 0.18/_downloads/012b7ba30b03ebda4c3419b2e4f5161a/plot_ssp_projs_sensitivity_map.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Some sort of mapping between neural activity and a state in the world
my location
head tilt
image
remembered location
Intuitively, we call this "representation"
In neuroscience, people talk about the 'neural code'
To formalize this notion, the NEF uses information theory (or coding theory)
Representation formal... | from IPython.display import YouTubeVideo
YouTubeVideo('hxdPdKbqm_I', width=720, height=400, loop=1, autoplay=0) | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
Rectified Linear Neuron | # Rectified linear neuron
%pylab inline
import numpy
import nengo
n = nengo.neurons.RectifiedLinear()
J = numpy.linspace(-1,1,100)
plot(J, n.rates(J, gain=10, bias=-5))
xlabel('J (current)')
ylabel('$a$ (Hz)'); | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
Leaky integrate-and-fire neuron
$ a = {1 \over {\tau_{ref}-\tau_{RC}ln(1-{1 \over J})}}$ | #assume this has been run
#%pylab inline
# Leaky integrate and fire
import numpy
import nengo
n = nengo.neurons.LIFRate(tau_rc=0.02, tau_ref=0.002) #n is a Nengo LIF neuron, these are defaults
J = numpy.linspace(-1,10,100)
plot(J, n.rates(J, gain=1, bias=-3))
xlabel('J (current)')
ylabel('$a$ (Hz)'); | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
Response functions
These are called "response functions"
How much neural firing changes with change in current
Similar for many classes of cells (e.g. pyramidal cells - most of cortex)
This is the $G_i$ function in the NEF: it can be pretty much anything
Tuning Curves
Neurons seem to be sensitive to particular va... | #assume this has been run
#%pylab inline
import numpy
import nengo
n = nengo.neurons.LIFRate() #n is a Nengo LIF neuron
x = numpy.linspace(-100,0,100)
plot(x, n.rates(x, gain=1, bias=50), 'b') # x*1+50
plot(x, n.rates(x, gain=0.1, bias=10), 'r') # x*0.1+10
plot(x, n.rates(x, gain=0.5, bias=5), 'g') # x*0.05+5
plot(... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
For mapping #1, the NEF uses a linear map:
$ J = \alpha x + J^{bias} $
But what about type (c) in this graph?
<img src=files/lecture2/tuning_curve.jpg>
Easy enough:
$ J = - \alpha x + J^{bias} $
But what about type(b)? Or these ones?
<img src=files/lecture2/orientation_tuning.png>
There's usually some $x$ which... | #assume this has been run
#%pylab inline
import numpy
import nengo
n = nengo.neurons.LIFRate()
e = numpy.array([1.0, 1.0])
e = e/numpy.linalg.norm(e)
a = numpy.linspace(-1,1,50)
b = numpy.linspace(-1,1,50)
X,Y = numpy.meshgrid(a, b)
from mpl_toolkits.mplot3d.axes3d import Axes3D
fig = figure()
ax = fig.add_subp... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
But that's not how people normally plot it
It might not make sense to sample every possible x
Instead they might do some subset
For example, what if we just plot the points around the unit circle? | import nengo
import numpy
n = nengo.neurons.LIFRate()
theta = numpy.linspace(0, 2*numpy.pi, 100)
x = numpy.array([numpy.cos(theta), numpy.sin(theta)])
plot(x[0],x[1])
axis('equal')
e = numpy.array([1.0, 1.0])
e = e/numpy.linalg.norm(e)
plot([0,e[0]], [0,e[1]],'r')
gain = 1
bias = 2.5
figure()
plot(theta, n.rates(... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
That starts looking a lot more like the real data.
Notation
Encoding
$a_i = G_i[\alpha_i x \cdot e_i + J^{bias}_i]$
Decoding
$\hat{x} = \sum_i a_i d_i$
The textbook uses $\phi$ for $d$ and $\tilde \phi$ for $e$
We're switching to $d$ (for decoder) and $e$ (for encoder)
Decoder
But where do we get $d_i$... | import numpy
import nengo
from nengo.utils.ensemble import tuning_curves
from nengo.dists import Uniform
N = 10
model = nengo.Network(label='Neurons')
with model:
neurons = nengo.Ensemble(N, dimensions=1,
max_rates=Uniform(100,200)) #Defaults to LIF neurons,
... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
What happens to the error with more neurons?
Noise
Neurons aren't perfect
Axonal jitter
Neurotransmitter vesicle release failure (~80%)
Amount of neurotransmitter per vesicle
Thermal noise
Ion channel noise (# of channels open and closed)
Network effects
More information: http://icwww.epfl.ch/~gerstner/SPNM/node33.ht... | #Have to run previous python cell first
A_noisy = A + numpy.random.normal(scale=0.2*numpy.max(A), size=A.shape)
xhat = numpy.dot(A_noisy, d)
pyplot.plot(x, A_noisy)
xlabel('x')
ylabel('firing rate (Hz)')
figure()
plot(x, x)
plot(x, xhat)
xlabel('$x$')
ylabel('$\hat{x}$')
ylim(-1, 1)
xlim(-1, 1)
print 'RMSE', np.sqr... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
What if we just increase the number of neurons? Will it help?
Taking noise into account
Include noise while solving for decoders
Introduce noise term $\eta$
$
\begin{align}
\hat{x} &= \sum_i(a_i+\eta)d_i \
E &= {1 \over 2} \int_{-1}^1 (x-\hat{x})^2 \;dx d\eta\
&= {1 \over 2} \int_{-1}^1 \left(x-\sum_i(a_i+\et... | import numpy
import nengo
from nengo.utils.ensemble import tuning_curves
from nengo.dists import Uniform
N = 100
model = nengo.Network(label='Neurons')
with model:
neurons = nengo.Ensemble(N, dimensions=1,
max_rates=Uniform(100,200)) #Defaults to LIF neurons,
... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
Number of neurons
What happens to the error with more neurons?
Note that the error has two parts:
$
\begin{align}
E = {1 \over 2} \int_{-1}^1 \left(x-\sum_i a_i d_i \right)^2 \;dx + \sigma^2 \sum_i d_i^2
\end{align}
$
Error due to static distortion (i.e. the error introduced by the decoders themselves)
This ... | #%pylab inline
import numpy
import nengo
from nengo.utils.ensemble import tuning_curves
from nengo.dists import Uniform
N = 40
tau_rc = .2
tau_ref = .001
lif_model = nengo.LIFRate(tau_rc=tau_rc, tau_ref=tau_ref)
model = nengo.Network(label='Neurons')
with model:
neurons = nengo.Ensemble(N, dimensions=1,
... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
How good is the representation? | #Have to run previous code cell first
noise = 0.2
with model:
connection = nengo.Connection(neurons, neurons, #This is just to generate the decoders
solver=nengo.solvers.LstsqNoise(noise=0.2)) #Add noise ###NEW
sim = nengo.Simulator(model)
d = sim.data[connection].weights.T
... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
Possible questions
How many neurons do we need for a particular level of accuracy?
What happens with different firing rates?
What happens with different distributions of x-intercepts?
Example 2: Arm Movements (2D)
Georgopoulos et al., 1982. "On the relations between the direction of two-dimensional arm movements a... | import numpy
import nengo
n = nengo.neurons.LIFRate()
theta = numpy.linspace(-numpy.pi, numpy.pi, 100)
x = numpy.array([numpy.sin(theta), numpy.cos(theta)])
e = numpy.array([1.0, 0])
plot(theta*180/numpy.pi, n.rates(numpy.dot(x.T, e), bias=1, gain=0.2)) #bias 1->1.5
xlabel('angle')
ylabel('firing rate')
xlim(-180,... | SYDE 556 Lecture 2 Representation.ipynb | Stanford-BIS/syde556 | gpl-2.0 |
This notebook will demonstrate how to use skrf to do a two-tiered one-port calibration. We'll use data that was taken to characterize a waveguide-to-CPW probe. So, for this specific example the diagram above looks like: | SVG('oneport_tiered_calibration/images/probe.svg') | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
Some Data
The data available is the folders 'tier1/' and 'tier2/'. | ls oneport_tiered_calibration/ | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
(if you dont have the git repo for these examples, the data for this notebook can be found here)
In each folder you will find the two sub-folders, called 'ideals/' and 'measured/'. These contain touchstone files of the calibration standards ideal and measured responses, respectively. | ls oneport_tiered_calibration/tier1/ | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
The first tier is at waveguide interface, and consisted of the following set of standards
short
delay short
load
radiating open (literally an open waveguide) | ls oneport_tiered_calibration/tier1/measured/ | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
Creating Calibrations
Tier 1
First defining the calibration for Tier 1 | from skrf.calibration import OnePort
import skrf as rf
%matplotlib inline
from pylab import *
rf.stylely()
tier1_ideals = rf.read_all_networks('oneport_tiered_calibration/tier1/ideals/')
tier1_measured = rf.read_all_networks('oneport_tiered_calibration/tier1/measured/')
tier1 = OnePort(measured = tier1_measured,... | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
Because we saved corresponding ideal and measured standards with identical names, the Calibration will automatically align our standards upon initialization. (More info on creating Calibration objects this can be found in the docs.)
Similarly for the second tier 2,
Tier 2 | tier2_ideals = rf.read_all_networks('oneport_tiered_calibration/tier2/ideals/')
tier2_measured = rf.read_all_networks('oneport_tiered_calibration/tier2/measured/')
tier2 = OnePort(measured = tier2_measured,
ideals = tier2_ideals,
name = 'tier2',
sloppy_input=True)
tier... | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
Error Networks
Each one-port Calibration contains a two-port error network, that is determined from the calculated error coefficients. The error network for tier1 models the VNA, while the error network for tier2 represents the VNA and the DUT. These can be visualized through the parameter 'error_ntwk'.
For tier 1, | tier1.error_ntwk.plot_s_db()
title('Tier 1 Error Network') | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
Similarly for tier 2, | tier2.error_ntwk.plot_s_db()
title('Tier 2 Error Network') | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
De-embedding the DUT
As previously stated, the error network for tier1 models the VNA, and the error network for tier2 represents the VNA+DUT. So to deterine the DUT's response, we cascade the inverse S-parameters of the VNA with the VNA+DUT.
$$ DUT = VNA^{-1}\cdot (VNA \cdot DUT)$$
In skrf, this is done as follows | dut = tier1.error_ntwk.inv ** tier2.error_ntwk
dut.name = 'probe'
dut.plot_s_db()
title('Probe S-parameters')
ylim(-60,10) | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
You may want to save this to disk, for future use,
dut.write_touchstone() | ls probe* | doc/source/examples/metrology/One Port Tiered Calibration.ipynb | Ttl/scikit-rf | bsd-3-clause |
In pandas | title = "bar chart2"
index = pd.date_range("8/24/2018", periods=6, freq="M")
df1 = pd.DataFrame(np.random.randn(6), index=index)
df2 = pd.DataFrame(np.random.rand(6), index=index)
dfvalue1 = [i[0] for i in df1.values]
dfvalue2 = [i[0] for i in df2.values]
_index = [i for i in df1.index.format()]
bar = pyecharts.Bar(t... | python/pyecharts.ipynb | zzsza/TIL | mit |
가로 그래프 | bar = Bar("가로 그래프")
bar.add("A", attr, v1)
bar.add("B", attr, v2, is_convert=True)
bar.width=800
bar | python/pyecharts.ipynb | zzsza/TIL | mit |
슬라이더 | import random
attr = ["{}th".format(i) for i in range(30)]
v1 = [random.randint(1, 30) for _ in range(30)]
bar = Bar("Bar - datazoom - slider ")
bar.add("", attr, v1, is_label_show=True, is_datazoom_show=True)
# bar.render()
bar
days = ["{}th".format(i) for i in range(30)]
days_v1 = [random.randint(1, 30) for _ in ra... | python/pyecharts.ipynb | zzsza/TIL | mit |
3D | from pyecharts import Bar3D
bar3d = Bar3D("3D Graph", width=1200, height=600)
x_axis = [
"12a", "1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a",
"12p", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p"
]
y_axis = [
"Saturday", "Friday", "Thursday", "Wednesday", "Tues... | python/pyecharts.ipynb | zzsza/TIL | mit |
Boxplot | from pyecharts import Boxplot
boxplot = Boxplot("Box plot")
x_axis = ['expr1', 'expr2', 'expr3', 'expr4', 'expr5']
y_axis = [
[850, 740, 900, 1070, 930, 850, 950, 980, 980, 880,
1000, 980, 930, 650, 760, 810, 1000, 1000, 960, 960],
[960, 940, 960, 940, 880, 800, 850, 880, 900, 840,
830, 790, 810, 880, ... | python/pyecharts.ipynb | zzsza/TIL | mit |
퍼널 | from pyecharts import Funnel
attr = ["A", "B", "C", "D", "E", "F"]
value = [20, 40, 60, 80, 100, 120]
funnel = Funnel("퍼널 그래프")
funnel.add(
"퍼널",
attr,
value,
is_label_show=True,
label_pos="inside",
label_text_color="#fff",
)
funnel.width=700
funnel.height=500
funnel | python/pyecharts.ipynb | zzsza/TIL | mit |
Gauge | from pyecharts import Gauge
gauge = Gauge("Gauge Graph")
gauge.add("이용률", "가운데", 66.66)
gauge | python/pyecharts.ipynb | zzsza/TIL | mit |
导入人脸数据集
在下方的代码单元中,我们导入人脸图像数据集,文件所在路径存储在名为 human_files 的 numpy 数组。 | import random
random.seed(8675309)
# 加载打乱后的人脸数据集的文件名
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)
# 打印数据集的数据量
print('There are %d total human images.' % len(human_files)) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step1'></a>
步骤1:检测人脸
我们将使用 OpenCV 中的 Haar feature-based cascade classifiers 来检测图像中的人脸。OpenCV 提供了很多预训练的人脸检测模型,它们以XML文件保存在 github。我们已经下载了其中一个检测模型,并且把它存储在 haarcascades 的目录中。
在如下代码单元中,我们将演示如何使用这个检测模型在样本图像中找到人脸。 | import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# 提取预训练的人脸检测模型
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# 加载彩色(通道顺序为BGR)图像
img = cv2.imread(human_files[3])
# 将BGR图像进行灰度处理
gray = cv2.cvtCol... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
在使用任何一个检测模型之前,将图像转换为灰度图是常用过程。detectMultiScale 函数使用储存在 face_cascade 中的的数据,对输入的灰度图像进行分类。
在上方的代码中,faces 以 numpy 数组的形式,保存了识别到的面部信息。它其中每一行表示一个被检测到的脸,该数据包括如下四个信息:前两个元素 x、y 代表识别框左上角的 x 和 y 坐标(参照上图,注意 y 坐标的方向和我们默认的方向不同);后两个元素代表识别框在 x 和 y 轴两个方向延伸的长度 w 和 d。
写一个人脸识别器
我们可以将这个程序封装为一个函数。该函数的输入为人脸图像的路径,当图像中包含人脸时,该函数返回 True,反之返回 Fal... | # 如果img_path路径表示的图像检测到了脸,返回"True"
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0 | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】 评估人脸检测模型
<a id='question1'></a>
问题 1:
在下方的代码块中,使用 face_detector 函数,计算:
human_files 的前100张图像中,能够检测到人脸的图像占比多少?
dog_files 的前100张图像中,能够检测到人脸的图像占比多少?
理想情况下,人图像中检测到人脸的概率应当为100%,而狗图像中检测到人脸的概率应该为0%。你会发现我们的算法并非完美,但结果仍然是可以接受的。我们从每个数据集中提取前100个图像的文件路径,并将它们存储在human_files_short和dog_files_short中。 | human_files_short = human_files[:100]
dog_files_short = train_files[:100]
## 请不要修改上方代码
## TODO: 基于human_files_short和dog_files_short
## 中的图像测试face_detector的表现
human_files_short_detect = 0
dog_files_short_detect = 0
for i in range(100):
if (face_detector(human_files_short[i])):
human_files_short_detect += 1... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='question2'></a>
问题 2:
就算法而言,该算法成功与否的关键在于,用户能否提供含有清晰面部特征的人脸图像。
那么你认为,这样的要求在实际使用中对用户合理吗?如果你觉得不合理,你能否想到一个方法,即使图像中并没有清晰的面部特征,也能够检测到人脸?
回答:
不太合理,因为图片的来源不同,不能保证所有的图片的脸部都是清晰的。 如果脸部特征不太清晰,应对图片进行前期的预处理。
<a id='Selection1'></a>
选做:
我们建议在你的算法中使用opencv的人脸检测模型去检测人类图像,不过你可以自由地探索其他的方法,尤其是尝试使用深度学习来解决它:)。请用下方的代码单元来设计和测试你的面部监测算法... | ## (选做) TODO: 报告另一个面部检测算法在LFW数据集上的表现
### 你可以随意使用所需的代码单元数 | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step2'></a>
步骤 2: 检测狗狗
在这个部分中,我们使用预训练的 ResNet-50 模型去检测图像中的狗。下方的第一行代码就是下载了 ResNet-50 模型的网络结构参数,以及基于 ImageNet 数据集的预训练权重。
ImageNet 这目前一个非常流行的数据集,常被用来测试图像分类等计算机视觉任务相关的算法。它包含超过一千万个 URL,每一个都链接到 1000 categories 中所对应的一个物体的图像。任给输入一个图像,该 ResNet-50 模型会返回一个对图像中物体的预测结果。 | from keras.applications.resnet50 import ResNet50
# 定义ResNet50模型
ResNet50_model = ResNet50(weights='imagenet') | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
数据预处理
在使用 TensorFlow 作为后端的时候,在 Keras 中,CNN 的输入是一个4维数组(也被称作4维张量),它的各维度尺寸为 (nb_samples, rows, columns, channels)。其中 nb_samples 表示图像(或者样本)的总数,rows, columns, 和 channels 分别表示图像的行数、列数和通道数。
下方的 path_to_tensor 函数实现如下将彩色图像的字符串型的文件路径作为输入,返回一个4维张量,作为 Keras CNN 输入。因为我们的输入图像是彩色图像,因此它们具有三个通道( channels 为 3)。
该函数首先读取一张图像,然后将其缩放为 ... | from keras.preprocessing import image
from tqdm import tqdm
def path_to_tensor(img_path):
# 用PIL加载RGB图像为PIL.Image.Image类型
img = image.load_img(img_path, target_size=(224, 224))
# 将PIL.Image.Image类型转化为格式为(224, 224, 3)的3维张量
x = image.img_to_array(img)
# 将3维张量转化为格式为(1, 224, 224, 3)的4... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
基于 ResNet-50 架构进行预测
对于通过上述步骤得到的四维张量,在把它们输入到 ResNet-50 网络、或 Keras 中其他类似的预训练模型之前,还需要进行一些额外的处理:
1. 首先,这些图像的通道顺序为 RGB,我们需要重排他们的通道顺序为 BGR。
2. 其次,预训练模型的输入都进行了额外的归一化过程。因此我们在这里也要对这些张量进行归一化,即对所有图像所有像素都减去像素均值 [103.939, 116.779, 123.68](以 RGB 模式表示,根据所有的 ImageNet 图像算出)。
导入的 preprocess_input 函数实现了这些功能。如果你对此很感兴趣,可以在 这里 查看 preprocess... | from keras.applications.resnet50 import preprocess_input, decode_predictions
def ResNet50_predict_labels(img_path):
# 返回img_path路径的图像的预测向量
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(ResNet50_model.predict(img)) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
完成狗检测模型
在研究该 清单 的时候,你会注意到,狗类别对应的序号为151-268。因此,在检查预训练模型判断图像是否包含狗的时候,我们只需要检查如上的 ResNet50_predict_labels 函数是否返回一个介于151和268之间(包含区间端点)的值。
我们通过这些想法来完成下方的 dog_detector 函数,如果从图像中检测到狗就返回 True,否则返回 False。 | def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151)) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【作业】评估狗狗检测模型
<a id='question3'></a>
问题 3:
在下方的代码块中,使用 dog_detector 函数,计算:
human_files_short中图像检测到狗狗的百分比?
dog_files_short中图像检测到狗狗的百分比? | ### TODO: 测试dog_detector函数在human_files_short和dog_files_short的表现
human_files_short_detect = 0
dog_files_short_detect = 0
for i in range(100):
if (dog_detector(human_files_short[i])):
human_files_short_detect += 1
if (dog_detector(dog_files_short[i])):
dog_files_short_detect += 1
print("The perc... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step3'></a>
步骤 3: 从头开始创建一个CNN来分类狗品种
现在我们已经实现了一个函数,能够在图像中识别人类及狗狗。但我们需要更进一步的方法,来对狗的类别进行识别。在这一步中,你需要实现一个卷积神经网络来对狗的品种进行分类。你需要__从头实现__你的卷积神经网络(在这一阶段,你还不能使用迁移学习),并且你需要达到超过1%的测试集准确率。在本项目的步骤五种,你还有机会使用迁移学习来实现一个准确率大大提高的模型。
在添加卷积层的时候,注意不要加上太多的(可训练的)层。更多的参数意味着更长的训练时间,也就是说你更可能需要一个 GPU 来加速训练过程。万幸的是,Keras 提供了能够轻松预测每次迭代(epoch)花... | from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# Keras中的数据预处理过程
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】模型架构
创建一个卷积神经网络来对狗品种进行分类。在你代码块的最后,执行 model.summary() 来输出你模型的总结信息。
我们已经帮你导入了一些所需的 Python 库,如有需要你可以自行导入。如果你在过程中遇到了困难,如下是给你的一点小提示——该模型能够在5个 epoch 内取得超过1%的测试准确率,并且能在CPU上很快地训练。
<a id='question4'></a>
问题 4:
在下方的代码块中尝试使用 Keras 搭建卷积网络的架构,并回答相关的问题。
你可以尝试自己搭建一个卷积网络的模型,那么你需要回答你搭建卷积网络的具体步骤(用了哪些层)以及为什么这样搭建。
你也可以根据上图提示的步骤搭建... | from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
model = Sequential()
### TODO: 定义你的网络架构
model.add(Conv2D(filters=16, kernel_size=2, input_shape=(224, 224, 3), activation='relu'))
model.add(MaxPooling2D(pool_size... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】训练模型
<a id='question5'></a>
问题 5:
在下方代码单元训练模型。使用模型检查点(model checkpointing)来储存具有最低验证集 loss 的模型。
可选题:你也可以对训练集进行 数据增强,来优化模型的表现。 | from keras.callbacks import ModelCheckpoint
### TODO: 设置训练模型的epochs的数量
epochs = 5
### 不要修改下方代码
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
verbose=1, save_best_only=True)
model.fit(train_tensors, train_targets,
validation_data=... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
测试模型
在狗图像的测试数据集上试用你的模型。确保测试准确率大于1%。 | # 获取测试数据集中每一个图像所预测的狗品种的index
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
# 报告测试准确率
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step4'></a>
步骤 4: 使用一个CNN来区分狗的品种
使用 迁移学习(Transfer Learning)的方法,能帮助我们在不损失准确率的情况下大大减少训练时间。在以下步骤中,你可以尝试使用迁移学习来训练你自己的CNN。
得到从图像中提取的特征向量(Bottleneck Features) | bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test'] | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
模型架构
该模型使用预训练的 VGG-16 模型作为固定的图像特征提取器,其中 VGG-16 最后一层卷积层的输出被直接输入到我们的模型。我们只需要添加一个全局平均池化层以及一个全连接层,其中全连接层使用 softmax 激活函数,对每一个狗的种类都包含一个节点。 | VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary()
## 编译模型
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
## 训练模型
checkpointer = ModelCheckpoin... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
测试模型
现在,我们可以测试此CNN在狗图像测试数据集中识别品种的效果如何。我们在下方打印出测试准确率。 | # 获取测试数据集中每一个图像所预测的狗品种的index
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]
# 报告测试准确率
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
使用模型预测狗的品种 | from extract_bottleneck_features import *
def VGG16_predict_breed(img_path):
# 提取bottleneck特征
bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
# 获取预测向量
predicted_vector = VGG16_model.predict(bottleneck_feature)
# 返回此模型预测的狗的品种
return dog_names[np.argmax(predicted_vector)] | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step5'></a>
步骤 5: 建立一个CNN来分类狗的品种(使用迁移学习)
现在你将使用迁移学习来建立一个CNN,从而可以从图像中识别狗的品种。你的 CNN 在测试集上的准确率必须至少达到60%。
在步骤4中,我们使用了迁移学习来创建一个使用基于 VGG-16 提取的特征向量来搭建一个 CNN。在本部分内容中,你必须使用另一个预训练模型来搭建一个 CNN。为了让这个任务更易实现,我们已经预先对目前 keras 中可用的几种网络进行了预训练:
VGG-19 bottleneck features
ResNet-50 bottleneck features
Inception bottleneck features... | ### TODO: 从另一个预训练的CNN获取bottleneck特征
bottleneck_features = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test'] | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】模型架构
建立一个CNN来分类狗品种。在你的代码单元块的最后,通过运行如下代码输出网络的结构:
<your model's name>.summary()
<a id='question6'></a>
问题 6:
在下方的代码块中尝试使用 Keras 搭建最终的网络架构,并回答你实现最终 CNN 架构的步骤与每一步的作用,并描述你在迁移学习过程中,使用该网络架构的原因。
回答:
Xception_model = Sequential()
这一步是调用Xception的预训练模型
Xception_model.add(GlobalAveragePooling2D(input_shape=train... | ### TODO: 定义你的框架
# 调用Xception的预训练模型
Xception_model = Sequential()
#加一个全局平均池化层避免过拟合
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
#添加Dropout层避免过拟合
Xception_model.add(Dropout(0.2))
#添加133个节点的全连接层,使用softmax激活函数输出每个狗狗品种的概率
Xception_model.add(Dense(133, activation='softmax'))
Xception_... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】训练模型
<a id='question7'></a>
问题 7:
在下方代码单元中训练你的模型。使用模型检查点(model checkpointing)来储存具有最低验证集 loss 的模型。
当然,你也可以对训练集进行 数据增强 以优化模型的表现,不过这不是必须的步骤。 | ### TODO: 训练模型
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception1.hdf5',
verbose=1, save_best_only=True)
history = Xception_model.fit(train_Xception, train_targets,
validation_data=(valid_Xception, valid_targets),
epochs=20, batch_size=20, ... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】测试模型
<a id='question8'></a>
问题 8:
在狗图像的测试数据集上试用你的模型。确保测试准确率大于60%。 | ### TODO: 在测试集上计算分类准确率
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]
# 报告测试准确率
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
【练习】使用模型测试狗的品种
实现一个函数,它的输入为图像路径,功能为预测对应图像的类别,输出为你模型预测出的狗类别(Affenpinscher, Afghan_hound 等)。
与步骤5中的模拟函数类似,你的函数应当包含如下三个步骤:
根据选定的模型载入图像特征(bottleneck features)
将图像特征输输入到你的模型中,并返回预测向量。注意,在该向量上使用 argmax 函数可以返回狗种类的序号。
使用在步骤0中定义的 dog_names 数组来返回对应的狗种类名称。
提取图像特征过程中使用到的函数可以在 extract_bottleneck_features.py 中找到。同时,他们应已在之前的代码块中被导入... | ### TODO: 写一个函数,该函数将图像的路径作为输入
### 然后返回此模型所预测的狗的品种
def Xception_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_Xception(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = Xception_model.predict(bottleneck_feature)
# return dog breed that is pre... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step6'></a>
步骤 6: 完成你的算法
实现一个算法,它的输入为图像的路径,它能够区分图像是否包含一个人、狗或两者都不包含,然后:
如果从图像中检测到一只__狗__,返回被预测的品种。
如果从图像中检测到__人__,返回最相像的狗品种。
如果两者都不能在图像中检测到,输出错误提示。
我们非常欢迎你来自己编写检测图像中人类与狗的函数,你可以随意地使用上方完成的 face_detector 和 dog_detector 函数。你__需要__在步骤5使用你的CNN来预测狗品种。
下面提供了算法的示例输出,但你可以自由地设计自己的模型!
<a id='question10'></a>
问题 10:
在下方代... | ### TODO: 设计你的算法
### 自由地使用所需的代码单元数吧
from IPython.core.display import Image, display
def dog_breed_algorithm(img_path):
if dog_detector(img_path) == 1:
print("hello, dog!")
display(Image(img_path,width=200,height=200))
print("Your predicted breed is ... ")
return print(Xception_predi... | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
<a id='step7'></a>
步骤 7: 测试你的算法
在这个部分中,你将尝试一下你的新算法!算法认为__你__看起来像什么类型的狗?如果你有一只狗,它可以准确地预测你的狗的品种吗?如果你有一只猫,它会将你的猫误判为一只狗吗?
上传方式:点击左上角的Jupyter回到上级菜单,你可以看到Jupyter Notebook的右上方会有Upload按钮。
<a id='question11'></a>
问题 11:
在下方编写代码,用至少6张现实中的图片来测试你的算法。你可以使用任意照片,不过请至少使用两张人类图片(要征得当事人同意哦)和两张狗的图片。
同时请回答如下问题:
输出结果比你预想的要好吗 :) ?或者更糟 :( ... | ## TODO: 在你的电脑上,在步骤6中,至少在6张图片上运行你的算法。
## 自由地使用所需的代码单元数吧
for i in range(1, 7):
filename = 'images/' + str(i) + '.jpg'
print('filename = ' + filename)
dog_breed_algorithm(filename)
print('\n') | assets/media/uda-ml/deep/azjc/卷积神经网络的例子/dog/dog_app_zh.ipynb | hetaodie/hetaodie.github.io | mit |
Forward pass: compute scores | scores = net.loss(X)
print('scores: ')
print(scores)
print
print('correct scores:')
correct_scores = np.asarray([
[-0.81233741, -1.27654624, -0.70335995],
[-0.17129677, -1.18803311, -0.47310444],
[-0.51590475, -1.01354314, -0.8504215 ],
[-0.15419291, -0.48629638, -0.52901952],
[-0.00618733, -0.12435261, -0.1... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Forward pass: compute loss | loss, _ = net.loss(X, y, reg=0.05)
corrent_loss = 1.30378789133
# should be very small, get < 1e-12
print('Difference between your loss and correct loss:')
print(np.sum(np.abs(loss - corrent_loss))) | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Backward pass
Implement the rest of the function. This will compute the gradient of the loss with respect to the variables W1, b1, W2, and b2. Now that you (hopefully!) have a correctly implemented forward pass, you can debug your backward pass using a numeric gradient check: | from utils.gradient_check import eval_numerical_gradient
loss, grads = net.loss(X, y, reg=0.05)
# these should all be less than 1e-8 or so
for param_name in grads:
f = lambda W: net.loss(X, y, reg=0.05)[0]
param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)
print('%s max rel... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Train the network
Once you have implemented the method, run the code below to train a two-layer network on toy data. You should achieve a training loss less than 0.2. | net = init_toy_model()
stats = net.train(X, y, X, y, learning_rate=1e-1, reg=5e-6, num_iters=100, verbose=False)
print('Final training loss: ', stats['loss_history'][-1])
# plot the loss history
plt.plot(stats['loss_history'])
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title('Training Loss history')
plt.s... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Load the data
Now that you have implemented a two-layer network that passes gradient checks and works on toy data, it's time to load up our favorite CIFAR-10 data so we can use it to train a classifier on a real dataset. | # Load the raw CIFAR-10 data
cifar10_dir = 'datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# Split the data
num_training = 49000
num_validation = 1000
num_test = 1000
mask = range(num_training, num_training+num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
mask =... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Train a network
To train our network we will use SGD with momentum. In addition, we will adjust the learning rate with an exponential learning rate schedule as optimization proceeds; after each epoch, we will reduce the learning rate by multiplying it by a decay rate. | input_size = 32 * 32 * 3
hidden_size = 50
num_classes = 10
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
learning_rate=1e-4, learning_rate_decay=0.95,
reg=0.25, num_iters=1000, batch_size=200, verbose=Tru... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Debug the training
With the default parameters we provided above, you should get a validation accuracy of about 0.29 on the validation set. This isn't very good.
One strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization.
An... | # Plot the loss function and train / validation accuracies
plt.subplot(2, 1, 1)
plt.plot(stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(stats['train_acc_history'], label='train')
plt.plot(stats['val_acc_history'], label='val')
plt.title('Classi... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Tune your hyperparameters
What's wrong?. Looking at the visualizations above, we see that the loss is decreasing more or less linearly, which seems to suggest that the learning rate may be too low. Moreover, there is no gap between the training and validation accuracy, suggesting that the model we used has low capacity... | input_size = 32 * 32 * 3
num_classes = 10
hidden_layer_size = [50]
learning_rates = [3e-4, 9e-4, 1e-3, 3e-3]
regularization_strengths = [7e-1, 8e-1, 9e-1, 1]
results = {}
best_model = None
best_val = -1
for hidden_size in hidden_layer_size:
for lr in learning_rates:
for reg in regularization_strengths:
... | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
Run on the test set
When you are done experimenting, you should evaluate your final trained network on the test set; you should get above 48%.
We will give you extra bonus point for every 1% of accuracy above 52%. | test_acc = (best_model.predict(X_test) == y_test).mean()
print('Test accuracy: ', test_acc) | test/two_layer_net.ipynb | zklgame/CatEyeNets | mit |
model_mnist_cnn.py | #! /usr/bin/env python
import tensorflow as tf
class mnistCNN(object):
"""
A NN for mnist classification.
"""
def __init__(self, dense=500):
# Placeholders for input, output and dropout
self.input_x = tf.placeholder(tf.float32, [None, 784], name="input_x")
self.input_y = t... | tensorflow_old/02-template_class/template_class.ipynb | sueiras/training | gpl-3.0 |
train.py | #! /usr/bin/env python
from __future__ import print_function
import tensorflow as tf
#from data_utils import get_data, batch_generator
#from model_mnist_cnn import mnistCNN
# Parameters
# ==================================================
# Data loading params
tf.flags.DEFINE_string("data_directory", '/tmp/MNIST_... | tensorflow_old/02-template_class/template_class.ipynb | sueiras/training | gpl-3.0 |
Once you have seen the mean image of your dataset, how does it relate to your own expectations of the dataset? Did you expect something different? Was there something more "regular" or "predictable" about your dataset that the mean image did or did not reveal? If your mean image looks a lot like something recognizab... | # Create a tensorflow operation to give you the standard deviation
# First compute the difference of every image with a
# 4 dimensional mean image shaped 1 x H x W x C
mean_img_4d = ...
subtraction = imgs - mean_img_4d
# Now compute the standard deviation by calculating the
# square root of the sum of squared differ... | session-1/.ipynb_checkpoints/session-1-checkpoint.ipynb | dariox2/CADL | apache-2.0 |
What we've just done is build a "hand-crafted" feature detector: the Gabor Kernel. This kernel is built to respond to particular orientation: horizontal edges, and a particular scale. It also responds equally to R, G, and B color channels, as that is how we have told the convolve operation to work: use the same kerne... | # Create a set of operations using tensorflow which could
# provide you for instance the sum or mean value of every
# image in your dataset:
# First flatten our convolved images so instead of many 3d images,
# we have many 1d vectors.
# This should convert our 4d representation of N x H x W x C to a
# 2d representatio... | session-1/.ipynb_checkpoints/session-1-checkpoint.ipynb | dariox2/CADL | apache-2.0 |
What does your sorting reveal? Could you imagine the same sorting over many more images reveal the thing your dataset sought to represent? It is likely that the representations that you wanted to find hidden within "higher layers", i.e., "deeper features" of the image, and that these "low level" features, edges essen... | utils.build_submission('session-1.zip',
('dataset.png',
'mean.png',
'std.png',
'normalized.png',
'kernel.png',
'convolved.png',
'sorted.png',
... | session-1/.ipynb_checkpoints/session-1-checkpoint.ipynb | dariox2/CADL | apache-2.0 |
Placement of ticks and custom tick labels
We can explicitly determine where we want the axis ticks with set_xticks and set_yticks, which both take a list of values for where on the axis the ticks are to be placed. We can also use the set_xticklabels and set_yticklabels methods to provide a list of custom text labels fo... | fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(x, x**2, x, x**3, lw=2)
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18)
yticks = [0, 50, 100, 150]
ax.set_yticks(yticks)
ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); ... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
There are a number of more advanced methods for controlling major and minor tick placement in matplotlib figures, such as automatic placement according to different policies. See http://matplotlib.org/api/ticker_api.html for details.
Scientific notation
With large numbers on axes, it is often better use scientific nota... | fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2, x, np.exp(x))
ax.set_title("scientific notation")
ax.set_yticks([0, 50, 100, 150])
from matplotlib import ticker
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-1,1))
ax.yaxis.set_major_formatter(for... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Axis number and axis label spacing | # distance between x and y axis and the numbers on the axes
matplotlib.rcParams['xtick.major.pad'] = 5
matplotlib.rcParams['ytick.major.pad'] = 5
fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2, x, np.exp(x))
ax.set_yticks([0, 50, 100, 150])
ax.set_title("label and axis spacing")
# padding between axis label and... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Axis position adjustments
Unfortunately, when saving figures the labels are sometimes clipped, and it can be necessary to adjust the positions of axes a little bit. This can be done using subplots_adjust: | fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2, x, np.exp(x))
ax.set_yticks([0, 50, 100, 150])
ax.set_title("title")
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.subplots_adjust(left=0.15, right=.9, bottom=0.1, top=0.9); | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Axis grid
With the grid method in the axis object, we can turn on and off grid lines. We can also customize the appearance of the grid lines using the same keyword arguments as the plot function: | fig, axes = plt.subplots(1, 2, figsize=(10,3))
# default grid appearance
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)
# custom grid appearance
axes[1].plot(x, x**2, x, x**3, lw=2)
axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Axis spines
We can also change the properties of axis spines: | fig, ax = plt.subplots(figsize=(6,2))
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('blue')
ax.spines['left'].set_color('red')
ax.spines['left'].set_linewidth(2)
# turn off axis spine to the right
ax.spines['right'].set_color("none")
ax.yaxis.tick_left() # only ticks on the left side | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Twin axes
Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the twinx and twiny functions: | fig, ax1 = plt.subplots()
ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Axes where x and y is zero | fig, ax = plt.subplots()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0)) # set position of y spi... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Other 2D plot styles
In addition to the regular plot method, there are a number of other functions for generating different kind of plots. See the matplotlib plot gallery for a complete list of available plot types: http://matplotlib.org/gallery.html. Some of the more useful ones are show below: | n = np.array([0,1,2,3,4,5])
fig, axes = plt.subplots(1, 4, figsize=(12,3))
axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx)))
axes[0].set_title("scatter")
axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")
axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")
axes[3].fill_betw... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Text annotation
Annotating text in matplotlib figures can be done using the text function. It supports LaTeX formatting just like axis label texts and titles: | fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3)
ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue")
ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green"); | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Figures with multiple subplots and insets
Axes can be added to a matplotlib Figure canvas manually using fig.add_axes or using a sub-figure layout manager such as subplots, subplot2grid, or gridspec:
subplots | fig, ax = plt.subplots(2, 3)
fig.tight_layout() | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
subplot2grid | fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2,0))
ax5 = plt.subplot2grid((3,3), (2,1))
fig.tight_layout() | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
gridspec | import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1])
for g in gs:
ax = fig.add_subplot(g)
fig.tight_layout() | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
add_axes
Manually adding axes with add_axes is useful for adding insets to figures: | fig, ax = plt.subplots()
ax.plot(xx, xx**2, xx, xx**3)
fig.tight_layout()
# inset
inset_ax = fig.add_axes([0.2, 0.55, 0.35, 0.35]) # X, Y, width, height
inset_ax.plot(xx, xx**2, xx, xx**3)
inset_ax.set_title('zoom near origin')
# set axis range
inset_ax.set_xlim(-.2, .2)
inset_ax.set_ylim(-.005, .01)
# set axis ti... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Colormap and contour figures
Colormaps and contour figures are useful for plotting functions of two variables. In most of these functions we will use a colormap to encode one dimension of the data. There are a number of predefined colormaps. It is relatively straightforward to define custom colormaps. For a list of pre... | alpha = 0.7
phi_ext = 2 * np.pi * 0.5
def flux_qubit_potential(phi_m, phi_p):
return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p)
phi_m = np.linspace(0, 2*np.pi, 100)
phi_p = np.linspace(0, 2*np.pi, 100)
X,Y = np.meshgrid(phi_p, phi_m)
Z = flux_qubit_potential(X, Y).T | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
pcolor | fig, ax = plt.subplots()
p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max())
cb = fig.colorbar(p, ax=ax) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
imshow | fig, ax = plt.subplots()
im = ax.imshow(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1])
im.set_interpolation('bilinear')
cb = fig.colorbar(im, ax=ax) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
contour | fig, ax = plt.subplots()
cnt = ax.contour(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1]) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
3D figures
To use 3D graphics in matplotlib, we first need to create an instance of the Axes3D class. 3D axes can be added to a matplotlib figure canvas in exactly the same way as 2D axes; or, more conveniently, by passing a projection='3d' keyword argument to the add_axes or add_subplot methods. | from mpl_toolkits.mplot3d.axes3d import Axes3D | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Surface plots | fig = plt.figure(figsize=(14,6))
# `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0)
# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, ... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Wire-frame plot | fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
Coutour plots with projections | fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25)
cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm)
cset = ax.contour(X,... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/04-Visualization-Matplotlib-Pandas/04b-Pandas Visualization/03 - Advanced Matplotlib Concepts.ipynb | arcyfelix/Courses | apache-2.0 |
The SDK uses the Python logging module to tell you what it's doing; if desired you can control what sort of output you see by uncommenting one of the lines below: | import logging
logger = logging.getLogger("bwapi")
#(Default) All logging messages enabled
#logger.setLevel(logging.DEBUG)
#Does not report URL's of API requests, but all other messages enabled
#logger.setLevel(logging.INFO)
#Report only errors and warnings
#logger.setLevel(logging.WARN)
#Report only errors
#logger... | DEMO.ipynb | anthonybu/api_sdk | mit |
Project
When you use the API for the first time you have to authenticate with Brandwatch. This will get you an access token. The access token is stored in a credentials file (tokens.txt in this example). Once you've authenticated your access token will be read from that file so you won't need to enter your password aga... | BWUser(username="user@example.com", password="YOUR_PASSWORD", token_path="tokens.txt") | DEMO.ipynb | anthonybu/api_sdk | mit |
Now you have authenticated you can load your project: | YOUR_ACCOUNT = your_account
YOUR_PROJECT = your_project
project = BWProject(username=YOUR_ACCOUNT, project=YOUR_PROJECT) | DEMO.ipynb | anthonybu/api_sdk | mit |
Before we really begin, please note that you can get documentation for any class or function by viewing the help documentation | help(BWProject) | DEMO.ipynb | anthonybu/api_sdk | mit |
Queries
Now we create some objects which can manipulate queries and groups in our project: | queries = BWQueries(project) | DEMO.ipynb | anthonybu/api_sdk | mit |
Let's check what queries already exist in the account | queries.names | DEMO.ipynb | anthonybu/api_sdk | mit |
We can also upload queries directly via the API by handing the "name", "searchTerms" and "backfillDate" to the upload funcion. If you don't pass a backfillDate, then the query will not backfill.
The BWQueries class inserts default values for the "languages", "type", "industry", and "samplePercent" parameters, but we c... | queries.upload(name = "Brandwatch Engagement",
includedTerms = "at_mentions:Brandwatch",
backfill_date = "2015-09-01") | DEMO.ipynb | anthonybu/api_sdk | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.