markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We then use the restored model to predict the class-numbers for those images.
y_pred = model3.predict(x=images)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Get the class-numbers as integers.
cls_pred = np.argmax(y_pred, axis=1)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Plot the images with their true and predicted class-numbers.
plot_images(images=images, cls_pred=cls_pred, cls_true=cls_true)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Visualization of Layer Weights and Outputs Helper-function for plotting convolutional weights
def plot_conv_weights(weights, input_channel=0): # Get the lowest and highest values for the weights. # This is used to correct the colour intensity across # the images so they can be compared with each other. w_min = np.min(weights) w_max = np.max(weights) # Number of filters used in the conv....
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Get Layers Keras has a simple way of listing the layers in the model.
model3.summary()
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
We count the indices to get the layers we want. The input-layer has index 0.
layer_input = model3.layers[0]
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
The first convolutional layer has index 2.
layer_conv1 = model3.layers[2] layer_conv1
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
The second convolutional layer has index 4.
layer_conv2 = model3.layers[4]
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Convolutional Weights Now that we have the layers we can easily get their weights.
weights_conv1 = layer_conv1.get_weights()[0]
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
This gives us a 4-rank tensor.
weights_conv1.shape
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Plot the weights using the helper-function from above.
plot_conv_weights(weights=weights_conv1, input_channel=0)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
We can also get the weights for the second convolutional layer and plot them.
weights_conv2 = layer_conv2.get_weights()[0] plot_conv_weights(weights=weights_conv2, input_channel=0)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Helper-function for plotting the output of a convolutional layer
def plot_conv_output(values): # Number of filters used in the conv. layer. num_filters = values.shape[3] # Number of grids to plot. # Rounded-up, square-root of the number of filters. num_grids = math.ceil(math.sqrt(num_filters)) # Create figure with a grid of sub-plots. fig, axes = pl...
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Input Image Helper-function for plotting a single image.
def plot_image(image): plt.imshow(image.reshape(img_shape), interpolation='nearest', cmap='binary') plt.show()
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Output of Convolutional Layer In order to show the output of a convolutional layer, we can create another Functional Model using the same input as the original model, but the output is now taken from the convolutional layer that we are interested in.
output_conv2 = Model(inputs=layer_input.input, outputs=layer_conv2.output)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
This creates a new model-object where we can call the typical Keras functions. To get the output of the convoloutional layer we call the predict() function with the input image.
layer_output2 = output_conv2.predict(np.array([image1])) layer_output2.shape
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
We can then plot the images for all 36 channels.
plot_conv_output(values=layer_output2)
03C_Keras_API.ipynb
Hvass-Labs/TensorFlow-Tutorials
mit
Layered violin plot Without color, this plot can simply display the distribution of importance for each variable as a standard violin plot.
shap.summary_plot(shap_values[:1000,:], X.iloc[:1000,:], plot_type="layered_violin", color='#cccccc')
notebooks/tabular_examples/tree_based_models/Scatter Density vs. Violin Plot Comparison.ipynb
slundberg/shap
mit
For example, in the above, we can see that s5 is the most important variable, and generally it causes either a large positive or negative change in the prediction. However, is it large values of s5 that cause a positive change and small ones that cause a negative change - or vice versa, or something more complicated? I...
shap.summary_plot(shap_values[:1000,:], X.iloc[:1000,:], plot_type="layered_violin", color='coolwarm')
notebooks/tabular_examples/tree_based_models/Scatter Density vs. Violin Plot Comparison.ipynb
slundberg/shap
mit
Here, red represents large values of a variable, and blue represents small ones. So, it becomes clear that large values of s5 do indeed increase the prediction, and vice versa. You can also see that others (like s6) are pretty evenly split, which indicates that while overall they're still important, their interaction i...
shap.summary_plot(shap_values[:1000,:], X.iloc[:1000,:])
notebooks/tabular_examples/tree_based_models/Scatter Density vs. Violin Plot Comparison.ipynb
slundberg/shap
mit
<!--#### Pros - if you're looking for really fine features, and your data doesn't have the problems below, then this might be better. However, you probably shouldn't be using a graph to discover such fine features. #### Cons - generally doesn't look as nice for most data sets - can be quite noisy - no smoothing etc....
shap.summary_plot(shap_values[:1000,:], X.iloc[:1000,:], plot_type="violin")
notebooks/tabular_examples/tree_based_models/Scatter Density vs. Violin Plot Comparison.ipynb
slundberg/shap
mit
The function plot_taylor_approximations included here was written by Fernando Perez and was part of work on the original IPython project. Although attribution seems to have been lost over time, we gratefully acknowledge FP and thank him for this code!
def plot_taylor_approximations(func, x0=None, orders=(2, 4), xrange=(0,1), yrange=None, npts=200): """Plot the Taylor series approximations to a function at various orders. Parameters ---------- func : a sympy function x0 : float Origin of the Taylor series expansion. If not given, x0=xrange...
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Lecture 10: Taylor's Series and Discrete Calculus Background It is common in physics and engineering to represent transcendental functions and other nonlinear expressions using a few terms from a Taylor series. This series provides a fast and efficient way to compute quantities such as $\mathrm{sin}(x)$ or $e^x$ to a...
import sympy as sp x, y, z, t, a = sp.symbols('x y z t a') k, m, n = sp.symbols('k m n', integer=True) f, g, h = sp.symbols('f g h', cls=sp.Function) sp.var('a1:6') sp.init_printing()
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
It is important to read about SymPy symbols at this time. We can generate a sequence using SeqFormula.
a1 = sp.SeqFormula(n**2, (n,0,5)) list(a1)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
if we want the limit of the sequence at infinity: $$[0, 1, 4, 9, \ldots ]$$ we can use limit_seq:
sp.limit_seq(a1.formula, n)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
DIY: Determine if the following sequences are convergent or divergent. If convergent, what is the limit? $$ \begin{aligned} a_n = & \frac{1}{n} \ a_n = & 1 - (0.2)^n \ a_n = & \frac{1}{2n+1} \end{aligned} $$
# Your code here.
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Infinite Series A series is the sum of a sequence. An infinite series will converge if the partial sums of the series has a finite limit. For example, examine the partial sums of the series: $$ \sum^{\infty}_{n=1} \frac{1}{2^n} $$
a2 = sp.Sum(1/2**n, (n,0,1)) a2 a2.doit() a4 = sp.Sum(n**2, (n,0,5)) a4 a5 = sp.Sum(k**2, (k, 1, m)) a5 a4.doit() a5.doit()
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
A power series is of the form: $$ \sum_{n=0}^{\infty} M_{n} x^{n} = M_0 + M_1 x + M_2 x^2 + \cdots $$
M = sp.IndexedBase('M') sp.Sum(M[n]*x**n, (n,0,m))
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
We can define the series about the point $a$ as follows:
sp.Sum(M[n]*(x-a)**n, (n,0,m))
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
SymPy has a function that can take SymPy expressions and represent them as power series:
sp.series(f(x), x, x0=0)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
DIY: Use SymPy to determine series approximations to $e^x$, $sin(x)$, and $cos(x)$ about the point $x=0$.
# Your code here.
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Taylor's Series Below we present a derivation of Taylor's series and small algebraic argument for series representations of functions. In contrast to the ability to use sympy functions without any deeper understanding, these presentations are intended to give you insight into the origin of the series representation a...
import sympy as sp sp.init_printing() x, A, B, C, D, E = sp.symbols('x, A, B, C, D, E')
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
To help us get our work done we can use sympy's diff function. Testing this function with a known result, we can write:
sp.diff(sp.sin(x),x)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
A list comprehension is used to organize the results. In each iteration the exact function and the power series are differentiated and stored as an element of a list. The list can be inspected and a set of simultaneous equations can be written down and solved to determine the values of the coefficients. Casting the ...
orderOfDifferentiation = 1 powerSeries = A+B*x+C*x**2+D*x**3+E*x**4 # Differentiate, element by element, the list [sp.sin(x),powerSeries] [sp.diff(a,x,orderOfDifferentiation) for a in [sp.sin(x),powerSeries]]
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
A list comprehension can be used to organize and extend the results further. We can wrap the list above into another list that changes the order of differentiation each iteration.
maximumOrder = 5 funcAndSeries = [[sp.diff(a,x,order) for a in [sp.sin(x),powerSeries]] for order in range(maximumOrder)] funcAndSeries
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Casting the results as a sympy Matrix object the list is more easily viewed in the Jupyter notebook:
sp.Matrix(funcAndSeries)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
DIY: Determine the coefficients in the above power series. You don't necessarily need to write code to complete this DIY problem.
# Your code here if you feel you need it.
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Your markdown here. Computing a Taylor's Series Symbolically Using sympy the Taylor's series can be computed symbolically.
from sympy import init_printing, symbols, Function init_printing() x, c = symbols("x,c") f = Function("f") f(x).series(x, x0=c, n=3)
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
One of the major uses of Taylor's series in computation is for the evaluation of derivatives. Take note of the fact that the derivatives of a function appear in the evaluation of the series. Computing Derivatives of Discrete Data It may be straightforward to compute the derivative of some functions. For example: $$f...
x, h, c = sp.symbols("x,h,c") f = sp.Function("f") # the .subs() method replaces occurences of 'x' with something else taylorExpansionPlus = f(x).series(x, x0=c, n=3).removeO().subs(x,c+h) taylorExpansionMinus = f(x).series(x, x0=c, n=3).removeO().subs(x,c-h) taylorExpansionPlus
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Meaning that: $$ f(c+h) = \frac{h^{2}}{2} \left. \frac{d^{2}}{d \xi_{1}^{2}} f{\left (\xi_{1} \right )} \right|{\substack{ \xi{1}=c }} + h \left. \frac{d}{d \xi_{1}} f{\left (\xi_{1} \right )} \right|{\substack{ \xi{1}=c }} + f{\left (c \right )} $$
taylorExpansionMinus
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Meaning that: $$ f(c-h) = \frac{h^{2}}{2} \left. \frac{d^{2}}{d \xi_{1}^{2}} f{\left (\xi_{1} \right )} \right|{\substack{ \xi{1}=c }} - h \left. \frac{d}{d \xi_{1}} f{\left (\xi_{1} \right )} \right|{\substack{ \xi{1}=c }} + f{\left (c \right )} $$ Solving for First and Second Derivatives Inspection of the results s...
(taylorExpansionMinus-f(c-h))-(taylorExpansionPlus-f(c+h))
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Remember that sympy expressions are zero by default. So this is true: $$ - 2 h \left. \frac{d}{d \xi_{1}} f{\left (\xi_{1} \right )} \right|{\substack{ \xi{1}=c }} - f{\left (c - h \right )} + f{\left (c + h \right )} = 0 $$ Find the second derivative in this expression:
(taylorExpansionMinus-f(c-h))+(taylorExpansionPlus-f(c+h))
Lecture-10A-Taylors-Series.ipynb
mathinmse/mathinmse.github.io
mit
Mapping all fatalities and getting unique hashs for each
# mapping all traffic fatals in WV to a geohash data=bl.map_table(data,6,list=True) matched=[] # getting matching uniques for row in bl.df2list(data): oldrow=row for row in totaluniques: if oldrow[-1]==row: matched.append(row) # getting point for row in matched: count+=1 temp=data[...
example_jupyter/example.ipynb
murphy214/berrl
apache-2.0
Showing the new url made with fatalities along certain routes
bl.show(newurl)
example_jupyter/example.ipynb
murphy214/berrl
apache-2.0
First, set filename to what we want to examine and read PhSF header
C = 25 phsfname = "PHSF" + "." + str(C) phsfname = "../" + phsfname print ("We're reading the {1}mm phase space file = {0}".format(phsfname, C))
C25_GP3.ipynb
Iwan-Zotow/VV
mit
The result is as expected. Only few percent of the values in the 1.33 and 1.17 MeV bins are due to scattered radiation. Most values are coming from primary source and are δ-peaks in energy. Spatial Distribution tests Here we will plot spatial distribution of the particles, projected from collimator exit position to the...
Znow = 197.5 # we at 200mm at the cooolimator exit Zshot = 380.0 # shot isocenter is at 380mm # radial, X and Y, all units in mm hr = H1Du.H1Du(120, 0.0, 40.0) hx = H1Du.H1Du(128, -32.0, 32.0) hy = H1Du.H1Du(128, -32.0, 32.0) for e in events: WT = e[0] xx, yy, zz = BEAMphsf.move_event(e, Znow, Zshot) ...
C25_GP3.ipynb
Iwan-Zotow/VV
mit
We find spatial distribution to be consistent with the collimation setup Angular Distribution tests Here we plot particles angular distribution for all three directional cosines, at the collimator exit. We expect angular distribution to fill collimation angle which is close to 0.033 radians (0.5x25/380).
# angular, WZ, WX and WY, all units in radians h_wz = H1Du.H1Du(100, 1.0 - 0.05, 1.0) h_wx = H1Du.H1Du(110, -0.055, 0.055) h_wy = H1Du.H1Du(110, -0.055, 0.055) for e in events: WT = e[0] wx = e[5] wy = e[6] wz = e[7] h_wz.fill(wz, WT) h_wx.fill(wx, WT) h_wy.fill(wy, WT) print...
C25_GP3.ipynb
Iwan-Zotow/VV
mit
Integral 1 $$ I_1 = \int_0^\frac{\pi}{2} \sin^2{x} {dx} = \frac{\pi}{4} $$
def integrand(x, a): return np.sin(x)**2 def integral_approx(a): # Use the args keyword argument to feed extra arguments to your integrand I, e = integrate.quad(integrand, 0, np.pi/2, args=(a,)) return I def integral_exact(a): return np.pi/4 print("Numerical: ", integral_approx(1.0)) print("Exact...
assignments/assignment09/IntegrationEx02.ipynb
LimeeZ/phys292-2015-work
mit
Integral 2 $$ I_2 = \int_0^\infty \frac{x\sin{mx}}{x^2 + a^2} {dx} = \frac{\pi}{2} e^{-ma} $$
def integrand(x, m, a): return (x*np.sin((m*x)))/(x**2 + a**2) def integral_approx(m, a): # Use the args keyword argument to feed extra arguments to your integrand I, e = integrate.quad(integrand, 0, np.inf, args=(m,a,)) return I def integral_exact(m, a): return ((np.pi)*.5) *(np.exp(-1*m*a)) pri...
assignments/assignment09/IntegrationEx02.ipynb
LimeeZ/phys292-2015-work
mit
Integral 3 $$ I_3 = \int_0^\frac{\pi}{2} \sin{ax^2} {dx} = \frac{1}{2} \sqrt{\frac{\pi}{2 \pi}} $$
def integrand(a,x): return np.sin((a)*(x**2)) def integral_approx(a): # Use the args keyword argument to feed extra arguments to your integrand I, e = integrate.quad(integrand, 0, (np.pi/2), args=(a)) return I def integral_exact(a): return .5*(np.sqrt((np.pi)/np.pi*2*np.pi)) print("Numerical: ", ...
assignments/assignment09/IntegrationEx02.ipynb
LimeeZ/phys292-2015-work
mit
Integral 4 $$ I_4 = \int_0^\infty e^{-ax} \cos{bx}{dx}= \frac{a}{a^2+b^2}$$
def integrand(a, x, b): return np.exp(-a*x) * np.cos(b*x) def integral_approx(a, b): # Use the args keyword argument to feed extra arguments to your integrand I, e = integrate.quad(integrand, 0, np.inf, args=(a, b)) return I def integral_exact(a, b): return a / (a**2 + b**2) print("Numerical: ", ...
assignments/assignment09/IntegrationEx02.ipynb
LimeeZ/phys292-2015-work
mit
Integral 5 $$ I_5 = \int_0^\infty e^{-ax^{2}} {dx}= \frac{1}{2} \sqrt{\frac{\pi}{a}}$$
def integrand(x, a): return np.exp((-a)*(x**2)) def integral_approx(a): # Use the args keyword argument to feed extra arguments to your integrand I, e= integrate.quad(integrand, 0, np.inf, args=(a,)) return I def integral_exact(a): return 0.5*(np.sqrt((np.pi)/a)) print("Numerical: ", integral_app...
assignments/assignment09/IntegrationEx02.ipynb
LimeeZ/phys292-2015-work
mit
Naive implementation
def convolution_naive(image, kernel): output = np.zeros((image.shape[0] - kernel.shape[0] + 1, image.shape[1] - kernel.shape[1] + 1)) # walk over output rows for i in range(output.shape[0]): # walk over output columns for j in range(output.shape[1]): # wal...
deep-learning/Convolution.ipynb
amirziai/learning
mit
Tests the implementation
for _ in range(1000): shape = np.random.randint(5, 20, (1, 2)) image_test = np.random.randint(1, 10, shape[0]) actual = convolution_naive(image_test, kernel) expected = convolve(image_test, kernel_flipped, mode='valid') np.testing.assert_equal(actual, expected) print('All tests passed')
deep-learning/Convolution.ipynb
amirziai/learning
mit
Vertical edge detection
image = np.zeros((6, 6)) image[:, 0:3] = 10 image convolution_naive(image, kernel)
deep-learning/Convolution.ipynb
amirziai/learning
mit
Horizontal edge detection
kernel_horizontal = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) kernel_horizontal image = np.array([ [10, 10, 10, 0, 0, 0], [10, 10, 10, 0, 0, 0], [10, 10, 10, 0, 0, 0], [0, 0, 0, 10, 10, 10], [0, 0, 0, 10, 10, 10], [0, 0, 0, 10, 10, 10], ]) convolution_naive(image, kernel_horizontal) conv...
deep-learning/Convolution.ipynb
amirziai/learning
mit
Sobel filter
kernel_sobel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) kernel_sobel
deep-learning/Convolution.ipynb
amirziai/learning
mit
Padding output size = n + 2 * p - f + 1 n: same padding
def padding_for_same(filter_size): return (filter_size - 1) / 2 padding_for_same(3) # even-shaped filters are problematic # odd-shaped is the convention padding_for_same(4)
deep-learning/Convolution.ipynb
amirziai/learning
mit
Strided convolutions
def convolution_strided_naive(image, kernel, stride): output_x = int((image.shape[0] - kernel.shape[0]) / stride + 1) output_y = int((image.shape[1] - kernel.shape[1]) / stride + 1) output = np.zeros((output_x, output_y)) # walk over output rows for i in range(output.shape[0]): # walk over...
deep-learning/Convolution.ipynb
amirziai/learning
mit
Flipping the kernel ⚠ What we've done so far is technically called cross-correlation and not convolution. So what's really done in most of deep learning literature is actually cross-correlation and not convolution. https://www.coursera.org/learn/convolutional-neural-networks/lecture/wfUhx/strided-convolutions
def mirror(x): return np.flipud(np.fliplr(kernel)).T kernel = np.array([ [3, 4, 5], [1, 0, 2], [-1, 9, 7] ]) mirror(kernel)
deep-learning/Convolution.ipynb
amirziai/learning
mit
The reason this is done in signal processing and some branches of math is that we get associativity properties which is lost with our previous notation. However deep learners do not care about associativity (keeps code simple and achieves the same result). Convolution over volumes https://www.coursera.org/learn/convolu...
def convolution_3d_naive(image, kernel): assert image.ndim == 3, "we're 3d now bro" assert kernel.ndim == 3, "we're 3d now bro" output = np.zeros((image.shape[0] - kernel.shape[0] + 1, image.shape[1] - kernel.shape[1] + 1)) # walk over output rows for i in range(output.s...
deep-learning/Convolution.ipynb
amirziai/learning
mit
The subchains are calculated over and over again, so use caching to avoid recalculating subchains. collatz is changed to be recursive to take advantage of lru_cache. Using cache was inspired by Kristian.
@lru_cache(maxsize=None) def collatz(n): x = [n] if n > 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 x.extend(collatz(n)) return x list(gen_collatz(13)) collatz(13) def foo(n): max_chain_len = 0 max_chain_n = 0 for i in range(1, n): if ...
euler-014-longest-collatz-sequence-20161214.ipynb
james-prior/euler
mit
Only the lengths of the Collatz chains are wanted, not the numbers in the Collatz chains, so len_collatz is created to return only the lengths of the Collatz chains. len_collatz is also recursive to take advantage of lru_cache. len_collatz is faster than collatz, but not as general as collatz.
@lru_cache(maxsize=None) def len_collatz(n): len_chain = 1 if n > 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 len_chain += len(collatz(n)) return len_chain len_collatz(13) def foo(n): max_chain_len = 0 max_chain_n = 0 for i in range(1, n): ...
euler-014-longest-collatz-sequence-20161214.ipynb
james-prior/euler
mit
We often use $\boldsymbol{X}$ to represent a dataset of input vectors. The $i^{th}$ input vector in $X$ is notated $X_i$, though often times when iterating through our dataset (like in a summation) we will call our datapoints $x \in X$ and write the the $i^{th}$ input vector as $x^{(i)}$. The $j^{th}$ component of the ...
zeroes = [X[i] for i in range(len(y)) if y[i] == 0] # all 64-dim lists with label '0' ones = [X[i] for i in range(len(y)) if y[i] == 1] # all 64-dim lists with label '1' both = zeroes + ones labels = [0] * len(zeroes) + [1] * len(ones)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
Supervised learning is an area of study within machine learning that entails passing an input vector into a model and outputting a label. Supervised learning is further broken down into classification tasks, in which the label $y$ is taken from some finite set of objects like {red, green blue} or {0, 1, 2, ..., 9} and ...
from sklearn.linear_model import LogisticRegression clf = LogisticRegression() # clf is code speak for 'classifier' clf.fit(X=both, y=labels)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
A lot just happened in those three short lines. Let's step through it line by line: from sklearn.linear_model import LogisticRegression From the sklearn (scikit-learn) linear_model module, we import a classifier called Logistic Regression. Linear models are models (or predictors) that attempt to seperate vector inputs ...
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(both, labels, test_size=0.3) clf = LogisticRegression() clf.fit(X_train, y_train) clf.score(X_test, y_test)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
Amazing! Our predictor was able to predict the labels of the test set with 100% accuracy! Okay, maybe not that amazing. Remember when we projected the ones and zeroes into $\mathbb{R}^2$ in our PCA notebook? They looked like they might be linearly seperable. And that was only in two dimensions. Our classifier can take ...
clf.predict(X_test)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
clf.predict tells us the actual predictions made on the test set.
def print_proba_table(prob_list, stride=1): mnist_classes = [i for i in range(len(prob_list[0]))] print("Class:", *mnist_classes, sep="\t") print("index", *["---" for i in range(len(mnist_classes))], sep="\t") counter = 0 for prob in prob_list[::stride]: print(counter*stride, *[round(prob[i]...
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
clf.predict_proba tells us how confident our predictor is for each label that that is the correct label for the input. The above table, along with the score, tells us that this was a very easy classification task for our predictor. How effective do you think logistic regression will be on the entire digits dataset?
from sklearn.decomposition import PCA pca = PCA(2) Xproj = pca.fit_transform(X) plt.scatter(Xproj.T[0], Xproj.T[1], c=y, alpha=0.5)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
Here's a 2D projection of the entire digits dataset using PCA, yikes! By the way, PCA is a linear dimensionality reduction technique, so it gives us a rough idea of what a linear classifier like logistic regression has to deal with. There also exist non-linear dimensionality reduction techniques, which let you project ...
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) clf = LogisticRegression() clf.fit(X_train, y_train) clf.score(X_test, y_test)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
Not so easy now, is it? But is 94.8% accuracy good "enough"? Depends on your application.
print_proba_table(clf.predict_proba(X_test), stride=10)
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
From this table we can tell that for a good portion of our digits our classifier had very high confidence in their class label, even with 10 different classes to choose from. But some digits were able to steal at least a tenth of a percent of confidence from our predictor across four different digits. And from clf.scor...
uncertain_indices = [] prob = clf.predict_proba(X_test) for i in range(len(prob)): # number of classes with > 0.45 confidence contender_count = sum([1 if p > 0.45 else 0 for p in prob[i]]) if contender_count == 2: uncertain_indices.append(i) f, ax = plt.subplots(5, 3, sharex=False, sharey=True) f.se...
2016-2017.Meetings/fall/02.hello_machine2.ipynb
nelson-liu/lectures
mit
Generative Model Hyperparameters Below we use RandomSearch to search over a random set (with n=5 below) of hyperparameter configurations, validating on the development set and saving the best model. Note we can also use the GridSearch class to search over all combinations of hyperparameters. We start by defining the mo...
from snorkel.learning import GenerativeModel from snorkel.learning import RandomSearch param_ranges = { 'step_size' : [1e-2, 1e-3, 1e-4, 1e-5, 1e-6], 'decay' : [1.0, 0.95, 0.9], 'epochs' : [20, 50, 100] } searcher = RandomSearch(GenerativeModel, param_ranges, L_train, n=5)
tutorials/advanced/Hyperparameter_Search.ipynb
HazyResearch/snorkel
apache-2.0
Finally we fit to the dev set--i.e. we execute the search, scoring and selecting the best configuration according to the dev set score:
%%time gen_model, run_stats = searcher.fit(L_dev, L_gold_dev) run_stats
tutorials/advanced/Hyperparameter_Search.ipynb
HazyResearch/snorkel
apache-2.0
Now we can apply the best learned model. Note that this is just a toy example- the above search may not be that interesting (i.e. all models may get perfect scores). But in practice, hyperparameter tuning is extremely important, especially for the end discriminative model (see below).
# Note that in other tutorials, this is often named `train_marginals`! Y_train = gen_model.marginals(L_train)
tutorials/advanced/Hyperparameter_Search.ipynb
HazyResearch/snorkel
apache-2.0
Making new Layers and Models via subclassing <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/guide/keras/custom_layers_and_models"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_bl...
import tensorflow as tf from tensorflow import keras
site/en-snapshot/guide/keras/custom_layers_and_models.ipynb
tensorflow/docs-l10n
apache-2.0
We will train the model with the following parameters
optimal_params = { 'iteration': [300] * 4, 'learning_rate': [0.04, 0.06, 10, 14], 'degree': [3, 1, 3, 1], 'scaled': [False] * 2 + [True] * 2 } optimal_params = OrderedDict(sorted(optimal_params.items(), key=lambda x: x[0]))
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
About parameters: Iteration - Number of the last iteration for the model with FreezeOut, after this iteration, learning rates in all layers will be zero. learning rate - Initial learning rate for all layers. In the scaled method, it will be divided by a number of the last iteration for this layer. degree - Linear or C...
plt.style.use('seaborn-poster') plt.style.use('ggplot') iteration = 300 _, axarr = plt.subplots(2, 2) axarr=axarr.reshape(-1) for params in range(4): graph = [] for i in range(1, 6): gefault_learning = optimal_params['learning_rate'][params] last = int(iteration*(i/10 + 0.5) ** optimal_param...
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
We'll compare ResNet model with FreezeOut vs classic ResNet model. First we load MNIST data
src = './../MNIST_data' with open(os.path.join(src, 'mnist_pics.blk'), 'rb') as file: images = blosc.unpack_array(file.read()).reshape(-1, 28, 28) with open(os.path.join(src, 'mnist_labels.blk'), 'rb') as file: labels = blosc.unpack_array(file.read()) global_freeze_loss = [] pipelines = []
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
Then create dataset and pipeline
res_loss=[] ix = DatasetIndex(range(50000)) sess = tf.Session() sess.run(tf.global_variables_initializer()) test_dset = Dataset(ix, ResBatch) test_pipeline = (test_dset.p .train_res(res_loss, images[:50000], labels[:50000])) for i in tqn(range(500)): test_pipeline.next_batch(300,n_epochs=None, shuf...
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
The config allows to easily change the configuration of the model
params_list = pd.DataFrame(optimal_params).values for params in tqn(params_list): freeze_loss = [] config = { 'freeznet':{'iteration': params[1], 'degree': params[0], 'learning_rate': params[2], 'scaled': params[3]} } dataset = Dataset...
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
Plots below show the losses of the models with different learning rate parameters
_, ax = plt.subplots(2,2) ax = ax.reshape(-1) for i in range(4): utils.ax_draw(global_freeze_loss[i][:300], res_loss[:300], params_list[i], ax[i]) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
You can see models that use scaled method are more unstable. The spikes in plots can be explained by large momentum. It is easy to see, what loss of the model with freezeout decrease faster than loss of the classic model. If we continue to train the models, you can see an effect of the new learning rate(1e-2 is the sam...
_, ax = plt.subplots(2,2) ax = ax.reshape(-1) for i in range(4): utils.ax_draw(global_freeze_loss[i], res_loss, params_list[i], ax[i]) plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
examples/experiments/freezeout/FreezeOut.ipynb
analysiscenter/dataset
apache-2.0
It looks like the score stabilizes after about 6 features, reaches a max at 16, then begins to taper off after about 70 features. We will save the top 45 and the top 75.
# save results to dataframe selected_summary = pd.DataFrame.from_dict(read_dictionary).T selected_summary['index'] = selected_summary.index selected_summary.sort_values(by='avg_score', ascending=0) # save dataframe selected_summary.to_csv('SFS_RF_selected_features_summary.csv', sep=',', header=True, index = False) # ...
MandMs/03_Facies_classification-MandMs_SFS_v2-validation_set.ipynb
seg/2016-ml-contest
apache-2.0
The DualMap class accepts the same arguments as the normal Map class. Except for these: 'width', 'height', 'left', 'top', 'position'. In the following example we create a DualMap, add layer controls and then show the map. Try panning and zooming to check that both maps are synchronized.
m = folium.plugins.DualMap(location=(52.1, 5.1), zoom_start=8) m
examples/plugin-DualMap.ipynb
python-visualization/folium
mit
Veamos la respuesta a una página web clásica
HTML('<iframe src="https://developer.github.com/v3/" width="700" height="400"></iframe>')
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Veamos la respuesta de una web api
HTML(url="https://api.github.com/")
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
En definitiva, cuando utilizamos una WEB API, están involucrados: Cliente: realiza la petición a través de la url Servidor: da una respuesta a la url recibida Protocolo: se establece en la especificación de la API ¿Cómo utilizar una API? El uso de WEB APIs permite: obtener información que sería cosotsa de obtener y p...
HTML('<iframe src="https://opendata.aemet.es/centrodedescargas/inicio" width="1000" height="400"></iframe>')
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Módulo requests Aunque existen otras formas y librería para trabajar con HTTP en Python, el módulo requests está específicamente pensado para trabajar con APIs web. Como siempre hasta ahora, lo primero es importarlo:
import requests
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Necesitaremos cargar nuesta API key, lo más cómodo es almacenarla en un fichero y cargarla desde ahí. Creemos una función para leerla:
# preserve def load_api_key(file): """Returns the contents in the file without the final line break """ with open(file, 'r') as f: api_key = f.read().rstrip() return api_key # cargamos la api_key api_key = load_api_key("../../apikey-aemet.txt")
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Debemos saber cuál es la url a la que vamos a hacer la petición:
# Fijamos la url y los parámetros # Predicción costera de Asturias, Cantabria y País Vasco debemos introducir # https://opendata.aemet.es/opendata/api/prediccion/maritima/costera/costa/41 url = "https://opendata.aemet.es/opendata/api/prediccion/maritima/costera/costa/41" querystring = {"api_key": api_key}
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Por último, lanzamos la petición:
# Lanzamos la request response = requests.get(url, params=querystring, verify=False)
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Comprobando la respuesta:
# Vemos la respuesta response
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Vemos que hemos obtenido una respuesta con código 200, esto quiere decir, en el código habitual de las API-REST, que todo ha ido bien. De hecho, es conveniente ver que todo ha ido bien antes de hacer nada más:
# código de estado response.status_code == requests.codes.ok
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Pero... ¿dónde están nuestros datos?
response.content
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
¡Parece que esto es un json!
content = response.json() content
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
Efectivamente, la mayoría de las WEB APIs devuelven json o xml. Pero, otra vez... ¿dónde están nuestros datos?
r_meta = requests.get(content['metadatos'], verify=False) r_data = requests.get(content['datos'], verify=False) if r_meta.status_code == requests.codes.ok: metadata = r_meta.json() if r_data.status_code == requests.codes.ok: data = r_data.json() print(metadata[0].keys()) print(data[0].keys()) metadata[0...
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
En definitiva, podríamos reagrupar todo lo anterior como:
# preserve from warnings import warn def get_prediction_for_cantabria(api_key): url = "https://opendata.aemet.es/opendata/api/prediccion/maritima/costera/costa/41" querystring = {"api_key": api_key} response = requests.get(url, params=querystring, verify=False) prediction = None if...
notebooks/070-AEMET_APIREST.ipynb
CAChemE/curso-python-datos
bsd-3-clause
You can also write a program into a file and then execute it like so: MacBook-Pro-2:~ tla$ cat Documents/test.py print("Hello, this is a test and it works!") MacBook-Pro-2:~ tla$ python Documents/test.py Hello, this is a test and it works! As we will learn later, it is possible to give more arguments at the command ...
year = 2015 print("Let's party like it's", year)
unit1/Running_Python.ipynb
DiXiT-eu/collatex-tutorial
gpl-3.0
Just like the Python interactive shell (and unlike running a Python program from a file), the IPython notebook remembers everything you define until you restart it. This is why we call them "interactive" - you can define things, look at them, and then do things with them without having to start over every time.
year += 1 print("Now we are partying like it's", year)
unit1/Running_Python.ipynb
DiXiT-eu/collatex-tutorial
gpl-3.0