markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
mit [SpaCy-jPTDP](https://github.com/KoichiYasuoka/spaCy-jPTDP)
!pip install deplacy spacy_jptdp import spacy_jptdp nlp=spacy_jptdp.load("de_gsd") doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [Turku-neural-parser-pipeline](https://turkunlp.org/Turku-neural-parser-pipeline/)
!pip install deplacy ufal.udpipe configargparse 'tensorflow<2' torch==0.4.1 torchtext==0.3.1 torchvision==0.2.1 !test -d Turku-neural-parser-pipeline || git clone --depth=1 https://github.com/TurkuNLP/Turku-neural-parser-pipeline !cd Turku-neural-parser-pipeline && git submodule update --init --recursive && test -d mod...
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [NLP-Cube](https://github.com/Adobe/NLP-Cube)
!pip install deplacy nlpcube from cube.api import Cube nlp=Cube() nlp.load("de") doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [Spacy-udpipe](https://github.com/TakeLab/spacy-udpipe)
!pip install deplacy spacy-udpipe import spacy_udpipe spacy_udpipe.download("de") nlp=spacy_udpipe.load("de") doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [SpaCy-COMBO](https://github.com/KoichiYasuoka/spaCy-COMBO)
!pip install deplacy spacy_combo import spacy_combo nlp=spacy_combo.load("de_gsd") doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [Trankit](https://github.com/nlp-uoregon/trankit)
!pip install deplacy trankit transformers import trankit nlp=trankit.Pipeline("german") doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
mit [Spacy](https://spacy.io/)
!pip install deplacy !python -m spacy download de_core_news_sm import de_core_news_sm nlp=de_core_news_sm.load() doc=nlp("Er sieht sehr jung aus.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/de.ipynb
kyodocn/deplacy
Solving the Stefan problem with finite elements This Jupyter notebook shows how to solve the Stefan problem with finite elements and goal-oriented adaptive mesh refinement (AMR) using FEniCS. Python packagesImport the Python packages for use in this notebook. We use the finite element method library FEniCS.
import fenics
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
|Note||----|| This Jupyter notebook server is using FEniCS 2017.2.0 from ppa:fenics-packages/fenics, installed via `apt` on Ubuntu 16.04.|FEniCS has convenient plotting features that don't require us to import `matplotlib`; but using `matplotlib` directly will allow us to annotate the plots.
import matplotlib
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Tell this notebook to embed graphical outputs from `matplotlib`, includings those made by `fenics.plot`.
%matplotlib inline
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
We will also use numpy.
import numpy
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Nomenclature||||-|-||$\mathbf{x}$| point in the spatial domain||$t$| time ||$T = T(\mathbf{x},t)$| temperature field ||$\phi$ | solid volume fraction ||$()_t = \frac{\partial}{\partial t}()$| time derivative ||$T_r$| central temperature of the regularization ||$r$| smoothing parameter of the regularization ||$\mathrm{...
def semi_phase_field(T, T_r, r): return 0.5*(1. + numpy.tanh((T_r - T)/r)) regularization_central_temperature = 0. temperatures = numpy.linspace( regularization_central_temperature - 0.5, regularization_central_temperature + 0.5, 1000) legend_strings = [] for regluarization_smoothing_parameter...
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Mesh Define a fine mesh to capture the rapid variation in $\phi(T)$.
N = 1000 mesh = fenics.UnitIntervalMesh(N)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Finite element function space, test function, and solution function Lets use piece-wise linear elements.
P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
|Note||----||`fenics.FiniteElement` requires the `mesh.ufl_cell()` argument to determine some aspects of the domain (e.g. that the spatial domain is two-dimensional).| Make the finite element function space $V$, which enumerates the finite element basis functions on each cell of the mesh.
V = fenics.FunctionSpace(mesh, P1)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Make the test function $\psi \in \mathbf{V}$.
psi = fenics.TestFunction(V)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Make the solution function $T \in \mathbf{V}$.
T = fenics.Function(V)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Benchmark parameters Set the Stefan number, density, specific heat capacity, and thermal diffusivity. For each we define a `fenics.Constant` for use in the variational form so that FEniCS can more efficiently compile the finite element code.
stefan_number = 0.045 Ste = fenics.Constant(stefan_number)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Define the regularized semi-phase-field for use with FEniCS.
regularization_central_temperature = 0. T_r = fenics.Constant(regularization_central_temperature) regularization_smoothing_parameter = 0.005 r = fenics.Constant(regularization_smoothing_parameter) tanh = fenics.tanh def phi(T): return 0.5*(1. + fenics.tanh((T_r - T)/r))
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Furthermore the benchmark problem involves hot and cold walls with constant temperatures $T_h$ and $T_c$, respectively.
hot_wall_temperature = 1. T_h = fenics.Constant(hot_wall_temperature) cold_wall_temperature = -0.01 T_c = fenics.Constant(cold_wall_temperature)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Time discretization To solve the initial value problem, we will prescribe the initial values, and then take discrete steps forward in time which solve the governing equations.We set the initial values such that a small layer of melt already exists touching the hot wall.\begin{align*} T^0 = \begin{cases} ...
initial_melt_thickness = 10./float(N) T_n = fenics.interpolate( fenics.Expression( "(T_h - T_c)*(x[0] < x_m0) + T_c", T_h = hot_wall_temperature, T_c = cold_wall_temperature, x_m0 = initial_melt_thickness, element = P1), V)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Let's look at the initial values now.
fenics.plot(T_n) matplotlib.pyplot.title(r"$T^0$") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.show() fenics.plot(phi(T_n)) matplotlib.pyplot.title(r"$\phi(T^0)$") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.show()
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
|Note||----||$\phi$ undershoots and overshoots the expected minimum and maximum values near the rapid change. This is a common feature of interior layers in finite element solutions. Here, `fenics.plot` projected $phi(T^0)$ onto a piece-wise linear basis for plotting. This could suggest we will encounter numerical issu...
timestep_size = 1.e-2 Delta_t = fenics.Constant(timestep_size) T_t = (T - T_n)/Delta_t phi_t = (phi(T) - phi(T_n))/Delta_t
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Variational form To obtain the finite element weak form, we follow the standard Ritz-Galerkin method. Therefore, we multiply the strong form *from the left* by the test function $\psi$ from the finite element function space $V$ and integrate over the spatial domain $\Omega$. This gives us the variational problem: Find...
dot, grad = fenics.dot, fenics.grad F = (psi*(T_t - 1./Ste*phi_t) + dot(grad(psi), grad(T)))*fenics.dx
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
LinearizationNotice that $\mathcal{F}$ is a *nonlinear* variational form. FEniCS will solve the nonlinear problem using Newton's method. This requires computing the Jacobian (formally the Gâteaux derivative) of the nonlinear variational form, yielding a a sequence of linearized problems whose solutions may converge to...
JF = fenics.derivative(F, T, fenics.TrialFunction(V))
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Boundary conditions We need boundary conditions before we can define a variational *problem* (i.e. in this case a boundary value problem).We consider a constant hot temperature on the left wall, a constant cold temperature on the right wall. Because the problem's geometry is simple, we can identify the boundaries with...
hot_wall = "near(x[0], 0.)" cold_wall = "near(x[0], 1.)"
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Define the boundary conditions for FEniCS.
boundary_conditions = [ fenics.DirichletBC(V, hot_wall_temperature, hot_wall), fenics.DirichletBC(V, cold_wall_temperature, cold_wall)]
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
The variational problem Now we have everything we need to define the variational problem for FEniCS.
problem = fenics.NonlinearVariationalProblem(F, T, boundary_conditions, JF)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
The benchmark solution Finally we instantiate the adaptive solver with our problem and goal
solver = fenics.NonlinearVariationalSolver(problem)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
and solve the problem to the prescribed tolerance.
solver.solve()
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
|Note||----||`solver.solve` will modify the solution `w`, which means that `u` and `p` will also be modified.| Now plot the temperature and solid volume fraction.
def plot(T): fenics.plot(T) matplotlib.pyplot.title("Temperature") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$T$") matplotlib.pyplot.show() fenics.plot(phi(T)) matplotlib.pyplot.title("Solid volume fraction") matplotlib.pyplot.xlabel("$x$") matpl...
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Let's run further.
for timestep in range(10): T_n.vector()[:] = T.vector() solver.solve() plot(T)
_____no_output_____
MIT
tutorials/FEniCS/00-StefanProblem.ipynb
yoczhang/phaseflow-fenics
Simulate straight line and circular movements with Bicycle modelRobot is at the origin (0, 0) and facing North, i.e, $\theta = \pi/2$. Assume the wheelbase of the vehicle $L$ = 0.9 m
#uncomment this decorator to test your code @test def bicycle_model(curr_pose, v, delta, dt=1.0): ''' >>> bicycle_model((0.0,0.0,0.0), 1.0, 0.0) (1.0, 0.0, 0.0) >>> bicycle_model((0.0,0.0,0.0), 0.0, np.pi/4) (0.0, 0.0, 0.0) >>> bicycle_model((0.0, 0.0, 0.0), 1.0, np.pi/4) (1.0, 0.0, 1.11) ''' # writ...
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Simulate Bicycle model with Open Loop controlWe want the robot to follow these instructions**straight 10m, right turn, straight 5m, left turn, straight 8m, right turn**It is in open loop; control commands have to be calculated upfront. How do we do it?To keep things simple in the first iteration, we can fix $v = v_c$ ...
v_c = 1 # m/s delta_c = np.pi/6 # rad/s #calculate time taken to finish a quarter turn (pi/2) # unlike you would need to take into account v_c and L of the vehicle as well t_turn = int(np.pi/2/delta_c) #calculate the time taken to finish straight segments # omega array is to be padded with equivalent zeros t_straigh...
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Let us make a cool function out of this!Take in as input a generic route and convert it into open-loop commandsInput format: [("straight", 5), ("right", 90), ("straight", 6), ("left", 85)]Output: all_v, all_delta
def get_open_loop_commands(route, vc=1, deltac=np.pi/12): all_delta = [] for dir, command in route: if dir == 'straight': t_straight = np.ceil(command/vc).astype('int') all_delta += [0]*t_straight elif dir == 'right': all_delta += [-deltac]*np.ceil(np.deg2rad(command)/deltac...
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Unit test your function with the following inputs+ [("straight", 5), ("right", 90), ("straight", 6), ("left", 85)]+ $v_c = 1$+ $delta_c = \pi/12$
v, delta = get_open_loop_commands([("straight", 5), ("right", 90), ("straight", 6), ("left", 85)], 1, np.pi/12) robot_trajectory = [] all_v, all_delta = get_open_loop_commands([("straight", 5), ("right", 90), ("straight", 6), ("left", 85)]) pose = np.array([0, 0, np.pi/2]) for v, delta in zip(all_v, all_delta): #in...
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:6: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the fu...
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Shape the turnLet us try something cooler than before (though a bit tricky in open loop). Instead of boring circular arcs, change the steering angle so that the robot orientation changes as shown in the equation below$\theta = (\theta_i - \theta_f) * (1 - 3x^2 + 2\theta^3) + \theta_f \thinspace \vee x \in [0,1]$First...
def poly_turn(theta_i, theta_f, n=10): x = np.linspace(0, 1, num=n) return (theta_i-theta_f) * (1 - 3 * x * x + 2 * (x**3)) + theta_f
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
How does a right turn look?
plt.figure() plt.plot(poly_turn(np.pi/2, 0),'.') plt.plot(poly_turn(np.pi/2, 0))
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Now plot a right turn (North to East)
plt.figure() plt.plot(poly_turn(np.pi/2, np.pi),'.') plt.plot(poly_turn(np.pi/2, np.pi))
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
How does $\theta$ change when we had constant $\delta$? Plot it
theta_change = np.diff(poly_turn(np.pi/2, np.pi)) plt.plot(theta_change,'.') plt.plot(theta_change)
_____no_output_____
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
We know the rate of change of $\theta$ is proportional to $\delta$. Can you work out the sequence of $\delta$ to change $\theta$ as in the cubic polynomial shown above?
L = 0.9 v = 1 theta_change = np.diff(poly_turn(np.pi/2, np.pi)) delta = np.arctan((L/v)*theta_change) print(delta)
[0.04844344 0.12920623 0.18593495 0.21942362 0.23048008 0.21942362 0.18593495 0.12920623 0.04844344]
MIT
week1/maithili/Q3 - Q/Attempt1_filesubmission_bicycle_model.ipynb
naveenmoto/lablet102
Table of Contents 1&nbsp;&nbsp;Introduction2&nbsp;&nbsp;Imports3&nbsp;&nbsp;Load the final text cleancat15 data4&nbsp;&nbsp;Plot g00 vs g20 Kernel Author: Bhishan Poudel, Ph.D Contd. Astrophysics Date: Jan 10, 2020 Update: Jan 13, 2020 IntroductionDate: Dec 10, 2019 Mon**Update** 1. Looked at gm0 vs gc0...
import json, os,sys import numpy as np import pandas as pd import seaborn as sns sns.set(color_codes=True) import plotly import ipywidgets pd.set_option('display.max_columns',200) import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline print([(x.__name__, x.__version__) for x in [np,pd,sns,plotly...
_____no_output_____
Apache-2.0
Jan_2020/a03_jan13/a01_cleancat15_gc0_gm0.ipynb
bpRsh/shear_analysis_after_dmstack
Load the final text cleancat15 data```g_sq = g00 g00 + g10 g10gmd_sq = gmd0**2 + gmd1**2```
!head -2 ../data/cleancat/final_text_cleancat15_000_167.txt names = "fN[0][0] fN[1][0] fN[2][0] fN[3][0] id[0][0] id[1][0] id[2][0] id[3][0] x[0] x[1] errx[0][0] errx[0][1] errx[1][0] errx[1][1] errx[2][0] errx[2][1] errx[3][0] ...
(90623, 50)
Apache-2.0
Jan_2020/a03_jan13/a01_cleancat15_gc0_gm0.ipynb
bpRsh/shear_analysis_after_dmstack
Plot g00 vs g20
df.head(2) def plot_g00_20(df,start,end): fig,ax = plt.subplots(1,2,figsize=(12,8)) x = df['gm[0]'] y = df['gc[0]']-df['gm[0]'] xx = df['g[0][0]'] yy = df['g[2][0]']-df['g[0][0]'] ax[0].scatter(x,y) ax[1].scatter(xx,yy) ax[0].set_ylabel('gc0-gm0') ax[0].set_xlabel('gm0') ...
(90623, 50)
Apache-2.0
Jan_2020/a03_jan13/a01_cleancat15_gc0_gm0.ipynb
bpRsh/shear_analysis_after_dmstack
AlexNet in TensorFlowCredits: Forked from [TensorFlow-Examples](https://github.com/aymericdamien/TensorFlow-Examples) by Aymeric Damien SetupRefer to the [setup instructions](http://nbviewer.ipython.org/github/donnemartin/data-science-ipython-notebooks/blob/master/deep-learning/tensor-flow-examples/Setup_TensorFlow.md...
import tensorflow as tf import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # Parameters learning_rate = 0.001 training_iters = 300000 batch_size = 64 display_step = 100 # Network Parameters n_input = 784 # M...
_____no_output_____
Apache-2.0
deep-learning/tensor-flow-examples/notebooks/3_neural_networks/alexnet.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
T81-558: Applications of Deep Neural Networks**Module 6: Convolutional Neural Networks (CNN) for Computer Vision*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more i...
# Nicely formatted time string def hms_string(sec_elapsed): h = int(sec_elapsed / (60 * 60)) m = int((sec_elapsed % (60 * 60)) / 60) s = sec_elapsed % 60 return f"{h}:{m:>02}:{s:>05.2f}"
_____no_output_____
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Part 6.2: Keras Neural Networks for Digits and Fashion MINST Computer VisionThis class will focus on computer vision. There are some important differences and similarities with previous neural networks.* We will usually use classification, though regression is still an option.* The input to the neural network is now ...
import tensorflow.keras from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras import regularizers from tensorflow.keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() print("Shape of x_train: {}".format(x_train.shap...
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 0s 0us/step Shape of x_train: (60000, 28, 28) Shape of y_train: (60000,) Shape of x_test: (10000, 28, 28) Shape of y_test: (10000,)
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Display the Digits The following code shows what the MNIST files contain.
# Display as text from IPython.display import display import pandas as pd print("Shape for dataset: {}".format(x_train.shape)) print("Labels: {}".format(y_train)) # Single MNIST digit single = x_train[0] print("Shape for single: {}".format(single.shape)) display(pd.DataFrame(single.reshape(28,28))) # Display as imag...
x_train shape: (60000, 28, 28, 1) Training samples: 60000 Test samples: 10000 WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for up...
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Training/Fitting CNN - DIGITSThe following code will train the CNN for 20,000 steps. This can take awhile, you might want to scale the step count back. GPU training can help. My results:* CPU Training Time: Elapsed time: 1:50:13.10* GPU Training Time: Elapsed time: 0:13:43.06
import tensorflow as tf import time start_time = time.time() model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=2, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss: {}'.format(score[0])) print('Test accu...
Train on 60000 samples, validate on 10000 samples WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead. Epoch 1/12 - 8s ...
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Evaluate Accuracy - DIGITSNote, if you are using a GPU you might get the **ResourceExhaustedError**. This occurs because the GPU might not have enough ram to predict the entire data set at once.
# Predict using either GPU or CPU, send the entire dataset. This might not work on the GPU. # Set the desired TensorFlow output level for this example score = model.evaluate(x_test, y_test, verbose=0) print('Test loss: {}'.format(score[0])) print('Test accuracy: {}'.format(score[1]))
Test loss: 0.027716550575438943 Test accuracy: 0.9919999837875366
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
GPUs are most often used for training rather than prediction. For prediction either disable the GPU or just predict on a smaller sample. If your GPU has enough memory, the above prediction code may work just fine. If not, just prediction on a sample with the following code:
from sklearn import metrics # For GPU just grab the first 100 images small_x = x_test[1:100] small_y = y_test[1:100] small_y2 = np.argmax(small_y,axis=1) pred = model.predict(small_x) pred = np.argmax(pred,axis=1) score = metrics.accuracy_score(small_y2, pred) print('Accuracy: {}'.format(score))
Accuracy: 0.98989898989899
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
MINST Fashion
import tensorflow.keras from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras import regularizers from tensorflow.keras.datasets import fashion_mnist (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() print("Shape of x_train: {}".for...
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [=====================...
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Display the Apparel The following code shows what the Fashion MNIST files contain.
# Display as text from IPython.display import display import pandas as pd print("Shape for dataset: {}".format(x_train.shape)) print("Labels: {}".format(y_train)) # Single MNIST digit single = x_train[0] print("Shape for single: {}".format(single.shape)) display(pd.DataFrame(single.reshape(28,28))) # Display as imag...
_____no_output_____
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
Training/Fitting CNN - FashionThe following code will train the CNN for 20,000 steps. This can take awhile, you might want to scale the step count back. GPU training can help. My results:* CPU Training Time: Elapsed time: 1:50:13.10* GPU Training Time: Elapsed time: 0:13:43.06
import tensorflow.keras from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras import backend as K batch_size = 128 num_classes = 10 epochs = 12 ...
Train on 60000 samples, validate on 10000 samples Epoch 1/12 - 4s - loss: 0.5299 - acc: 0.8125 - val_loss: 0.3500 - val_acc: 0.8740 Epoch 2/12 - 4s - loss: 0.3456 - acc: 0.8774 - val_loss: 0.2875 - val_acc: 0.8960 Epoch 3/12 - 4s - loss: 0.2973 - acc: 0.8927 - val_loss: 0.2736 - val_acc: 0.9018 Epoch 4/12 - 4s - lo...
Apache-2.0
t81_558_class_06_2_cnn.ipynb
sanjayssane/t81_558_deep_learning
import numpy as np A = np.array([[4,10,8],[10,26,26],[8,26,61]]) print(A) inv_A=np.linalg.inv(A) print(inv_A) B = np.array([[44],[128],[214]]) print(B) #AA^-1X = B.A^-1 X = np.dot(inv_A,B) print(X)
[[ 4 10 8] [10 26 26] [ 8 26 61]] [[ 25.27777778 -11.16666667 1.44444444] [-11.16666667 5. -0.66666667] [ 1.44444444 -0.66666667 0.11111111]] [[ 44] [128] [214]] [[-8.] [ 6.] [ 2.]]
Apache-2.0
Linear_Transformation.ipynb
espinili/Linear-Algebra-58020
Load datasets
from sklearn import datasets digits = datasets.load_digits() features = digits.data target = digits.target
_____no_output_____
MIT
Machine Learning Cookbook/Chapter 2 Loading Data.ipynb
sonwanesuresh95/Books-to-notebooks
Need 240 metric tons of methane. 2.4e^8 grams of methane
from ISRU import Atmospheric_processing_unit import random import json import matplotlib.pyplot as plt peridoic = json.load(open("periodic.json")) avogadro = 6.0221409E23 H = peridoic['H'] C = peridoic['C'] CH_4 = {} CH_4['mass'] = (1 * C['atomic_mass']) + (4 * H['atomic_mass']) CH_4['mass'] apu = Atmospheric_process...
_____no_output_____
MIT
Untitled.ipynb
mkirby1995/PyISRU
**This notebook is an exercise in the [Python](https://www.kaggle.com/learn/python) course. You can reference the tutorial at [this link](https://www.kaggle.com/colinmorris/hello-python).**--- Exercises Welcome to your first set of Python coding problems! If this is your first time using Kaggle Notebooks, welcome! No...
print("You've successfully run some Python code") print("Congratulations!") print("this is sai yugandhar")
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
Try adding another line of code in the cell above and re-running it. Now let's get a little fancier: Add a new code cell by clicking on an existing code cell, hitting the escape key, and then hitting the `a` or `b` key. The `a` key will add a cell above the current cell, and `b` adds a cell below.Great! Now you know ...
from learntools.core import binder; binder.bind(globals()) from learntools.python.ex1 import * print("Setup complete! You're ready to start question 0.")
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
0.*This is a silly question intended as an introduction to the format we use for hands-on exercises throughout all Kaggle courses.***What is your favorite color? **To complete this question, create a variable called `color` in the cell below with an appropriate value. The function call `q0.check()` (which we've alread...
# create a variable called color with an appropriate value on the line below # (Remember, strings in Python must be enclosed in 'single' or "double" quotes colour=("blue") # Check your answer q0.check()
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
Didn't get the right answer? How do you not even know your own favorite color?!Delete the `` in the line below to make one of the lines run. You can choose between getting a hint or the full answer by choosing which line to remove the `` from. Removing the `` is called uncommenting, because it changes that line from a ...
q0.hint() q0.solution()
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
The upcoming questions work the same way. The only thing that will change are the question numbers. For the next question, you'll call `q1.check()`, `q1.hint()`, `q1.solution()`, for question 2, you'll call `q2.check()`, and so on. 1.Complete the code below. In case it's helpful, here is the table of available arithme...
pi = 3.14159 # approximate diameter = 3 # Create a variable called 'radius' equal to half the diameter radius=1/2*diameter # Create a variable called 'area', using the formula for the area of a circle: pi times the radius squared area=pi*radius**2 # Check your answer q1.check() # Uncomment and run the lines below if...
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
2.Add code to the following cell to swap variables `a` and `b` (so that `a` refers to the object previously referred to by `b` and vice versa).
########### Setup code - don't touch this part ###################### # If you're curious, these are examples of lists. We'll talk about # them in depth a few lessons from now. For now, just know that they're # yet another type of Python object, like int or float. a = [1, 2, 3] b = [3, 2, 1] q2.store_original_ids() ##...
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
3.a) Add parentheses to the following expression so that it evaluates to 1.
((5 - 3) // 2) q3.a.hint() # Check your answer (Run this code cell to receive credit!) q3.a.solution()
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
Questions, like this one, marked a spicy pepper are a bit harder.b) 🌶️ Add parentheses to the following expression so that it evaluates to 0
(8 - 3) * (2 - (1 + 1)) #q3.b.hint() # Check your answer (Run this code cell to receive credit!) q3.b.solution()
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
4. Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves.For the sake of their friendship, any candies left over will be smashed. For example, if they collectivelybring home 91 candies, they'll take 30 each and smash 1.Write an arithmetic expression below to calculate how ...
# Variables representing the number of candies collected by alice, bob, and carol alice_candies = 42 bob_candies = 28 carol_candies = 21 # Your code goes here! Replace the right-hand side of this assignment with an expression # involving alice_candies, bob_candies, and carol_candies to_smash = 1 sum = alice_candies+bo...
_____no_output_____
MIT
python/syntax-variables-and-numbers.ipynb
saiyugandharsingamaneni/kaggel-courses
LMDZ GCM[LMDZ](http://lmdz.lmd.jussieu.fr/le-projet-lmdz/formation/2017)[mars?](http://www-mars.lmd.jussieu.fr/) Download, compile
%%bash run=svn && which $run || sudo apt-get install subversion || true which $run || echo "Please install svn..." INST="svn co http://svn.lmd.jussieu.fr/LMDZ/BOL/script_install && cd script_install && chmod +x install*.sh && ./install*.sh" echo $INST ###################### from __future__ import print_function import ...
_____no_output_____
Apache-2.0
LMDZ.ipynb
morianemo/ecflow-notehbook2
ConvNet for image classification (CIFAR-10)
import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.datasets as dset import torchvision.transforms as T from torch.utils.data import DataLoader from torch.utils.data import sampler from pprint import ppr...
using device: cuda
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Load CIFAR-10
# Set up a transform to preprocess the data by subtracting the mean RGB value # and dividing by the standard deviation of each RGB value; transform = T.Compose([ T.ToTensor(), T.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) ]) # Set up a Dataset object for e...
Files already downloaded and verified Files already downloaded and verified Files already downloaded and verified X_train: (49000, 32, 32, 3), [0, 255] X_val: (1000, 32, 32, 3), [0, 255] classes: ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Look at some images
plt.figure(figsize=(8, 4)) batch = (X_train[0:10]) for i in range(10): plt.subplot(2, 5, i + 1) plt.imshow(batch[i].astype('int32')) plt.axis('off') plt.title(classes[y_train[i]]) plt.tight_layout()
_____no_output_____
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
ConvNet
in_channel = 3 channel_1 = 64 channel_2 = 16 num_classes = 10 class Flatten(nn.Module): def forward(self, x): return x.view(x.shape[0], -1) def weights_init(m): if type(m) in [nn.Conv2d, nn.Linear]: nn.init.zeros_(m.bias.data) if INIT_METHOD == 'he_normal': nn.init.kaim...
_____no_output_____
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Training
weights = {} val_acc = train(model, optimizer, epochs=EPOCHS) plt.figure() plt.plot(np.arange(len(val_acc)) + 1, val_acc) plt.xlabel('epoch') plt.ylabel('accuracy, %') plt.title('Validation accuracy') plt.show()
_____no_output_____
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Results
check_accuracy(loader_train, model, dataset='train') val_acc = check_accuracy(loader_val, model) test_acc = check_accuracy(loader_test, model)
Checking accuracy on train set Got 40262 / 49000 correct (82.17%) Checking accuracy on validation set Got 691 / 1000 correct (69.10%) Checking accuracy on test set Got 6867 / 10000 correct (68.67%)
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Searching the weights of the model :)
print(model) print(model[0]) print(model[0].weight.shape)
Conv2d(3, 64, kernel_size=(5, 5), stride=(1, 1)) torch.Size([64, 3, 5, 5])
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Final conv1 weights/filters
print(f'PyTorch') print(f'init_method: {INIT_METHOD}') print(f'val_acc: {val_acc:.2f}%') def normalize_img(x): x_min = x.min() x_max = x.max() x_norm = (x - x_min) / (x_max - x_min) return x_norm plt.figure(figsize=(22, 7)) for i in range(len(model[0].weight)): conv1_filter = model[0].weight[i].tr...
PyTorch init_method: glorot_uniform val_acc: 69.10%
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Conv1 weights/filter during training
imgs_per_line = 16 k = 0 for epoch in weights.keys(): print(f'epoch {epoch}') plt.figure(figsize=(18, 12)) for i in range(imgs_per_line): k += 1 plt.subplot(len(weights), imgs_per_line, k) w = weights[epoch][i].transpose(0, 1).transpose(1, 2).cpu().detach().numpy() plt.imsh...
epoch 0
MIT
2018-2019/assignment 3 (CNN)/ConvNet_CIFAR10_PyTorch.ipynb
Tudor67/Neural-Networks-Assignments
Balanced Binning
from yellowbrick.datasets import load_concrete from yellowbrick.target import BalancedBinningReference # Instantiate the visualizer visualizer = BalancedBinningReference(bins=[0,7,8,9,10]) y = df['RATINGHS'] visualizer.fit(y) # Fit the data to the visualizer visualizer.show() # Finalize and render the ...
_____no_output_____
MIT
.ipynb_checkpoints/Household_Class_Imbalanced-checkpoint.ipynb
georgetown-analytics/First-Home-Recommender
Class Imbalanced
X = df y = df_conv from yellowbrick.target import ClassBalance X = df y = df_conv # Instantiate the visualizer visualizer = ClassBalance( labels=["Un-Satisfied", "Satisfied", "Highly Satisfied","Extreme Satisfied"], size=(1080, 720) ) visualizer.fit(y) visualizer.show() from imblearn.over_sampling import SMOTE sm ...
/Users/sabashaikh/anaconda2/envs/py36/lib/python3.6/site-packages/imblearn/base.py:306: UserWarning: The target type should be binary. warnings.warn('The target type should be binary.')
MIT
.ipynb_checkpoints/Household_Class_Imbalanced-checkpoint.ipynb
georgetown-analytics/First-Home-Recommender
Вступ Створити програму, яка виконує наступні завдання:1. Створити не менше двох об’єктів TimeSeries, у яких індекси створені задопомогою date_range(). Виділити підмасиви у цих об’єктів. Провестиоб’єднання об’єктів TimeSeries за допомогою merge_asof().2. Виконати завдання відповідно до варіанту. Варіант 7.*Файл Micro...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns
_____no_output_____
MIT
docs/lab5/lab5.ipynb
mezgoodle/ad_labs
Дані
df = pd.read_csv('https://raw.githubusercontent.com/mezgoodle/ad_labs/master/data/Microsoft_Stock.csv', index_col='Date', parse_dates=True) df df.info() df.describe().T
_____no_output_____
MIT
docs/lab5/lab5.ipynb
mezgoodle/ad_labs
Перше завдання
date_indexes = pd.date_range('2015-04-01 16:00:00', '2021', freq='3D') date_indexes open_series = pd.Series(df['Open'], index=date_indexes).fillna(method='ffill') open_series date_indexes = pd.date_range('2015-04-01 16:00:00', '2019-11', freq='3B') date_indexes close_series = pd.Series(df['Close'], index=date_indexes)....
_____no_output_____
MIT
docs/lab5/lab5.ipynb
mezgoodle/ad_labs
Друге завдання
close_series = pd.Series(df['Close']) close_series.plot() close_series['2019'].plot() close_series['2018-09'].plot() close_series['2015-11': '2018-01'].plot() close_series['2021-01'].last('2W').plot()
_____no_output_____
MIT
docs/lab5/lab5.ipynb
mezgoodle/ad_labs
Третє завдання
high_series = pd.Series(df['High']) high_series high_series['2016'].mean() high_series.to_period('M').groupby(level=0).mean() high_series['2019'].first('3M').to_period('W').groupby(level=0).mean()
_____no_output_____
MIT
docs/lab5/lab5.ipynb
mezgoodle/ad_labs
!wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/horse-or-human.zip \ -O /tmp/horse-or-human.zip !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/validation-horse-or-human.zip \ -O /tmp/validation-horse-or-human....
--2019-11-15 13:38:59-- https://storage.googleapis.com/laurencemoroney-blog.appspot.com/validation-horse-or-human.zip Resolving storage.googleapis.com (storage.googleapis.com)... 74.125.142.128, 2607:f8b0:400e:c09::80 Connecting to storage.googleapis.com (storage.googleapis.com)|74.125.142.128|:443... connected. HTTP ...
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
The following python code will use the OS library to use Operating System libraries, giving you access to the file system, and the zipfile library allowing you to unzip the data.
import os import zipfile local_zip = '/tmp/horse-or-human.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/horse-or-human') local_zip = '/tmp/validation-horse-or-human.zip' zip_ref = zipfile.ZipFile(local_zip, 'r') zip_ref.extractall('/tmp/validation-horse-or-human') zip_ref.close()
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
The contents of the .zip are extracted to the base directory `/tmp/horse-or-human`, which in turn each contain `horses` and `humans` subdirectories.In short: The training set is the data that is used to tell the neural network model that 'this is what a horse looks like', 'this is what a human looks like' etc. One thin...
# Directory with our training horse pictures train_horse_dir = os.path.join('/tmp/horse-or-human/horses') # Directory with our training human pictures train_human_dir = os.path.join('/tmp/horse-or-human/humans') # Directory with our training horse pictures validation_horse_dir = os.path.join('/tmp/validation-horse-or...
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
Building a Small Model from ScratchBut before we continue, let's start defining the model:Step 1 will be to import tensorflow.
import tensorflow as tf
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
We then add convolutional layers as in the previous example, and flatten the final result to feed into the densely connected layers. Finally we add the densely connected layers. Note that because we are facing a two-class classification problem, i.e. a *binary classification problem*, we will end our network with a [*s...
model = tf.keras.models.Sequential([ # Note the input shape is the desired size of the image 150x150 with 3 bytes color # This is the first convolution tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)), tf.keras.layers.MaxPooling2D(2, 2), # The second convolution tf...
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version. Instructions for updating: If using Ker...
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
The model.summary() method call prints a summary of the NN
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 148, 148, 16) 448 ____________________________________...
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
The "output shape" column shows how the size of your feature map evolves in each successive layer. The convolution layers reduce the size of the feature maps by a bit due to padding, and each pooling layer halves the dimensions. Next, we'll configure the specifications for model training. We will train our model with t...
from tensorflow.keras.optimizers import RMSprop model.compile(loss='binary_crossentropy', optimizer=RMSprop(lr=0.001), metrics=['acc'])
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/nn_impl.py:183: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
Data PreprocessingLet's set up data generators that will read pictures in our source folders, convert them to `float32` tensors, and feed them (with their labels) to our network. We'll have one generator for the training images and one for the validation images. Our generators will yield batches of images of size 300x...
from tensorflow.keras.preprocessing.image import ImageDataGenerator # All images will be rescaled by 1./255 train_datagen = ImageDataGenerator(rescale=1/255) validation_datagen = ImageDataGenerator(rescale=1/255) # Flow training images in batches of 128 using train_datagen generator train_generator = train_datagen.fl...
Found 1027 images belonging to 2 classes. Found 256 images belonging to 2 classes.
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
TrainingLet's train for 15 epochs -- this may take a few minutes to run.Do note the values per epoch.The Loss and Accuracy are a great indication of progress of training. It's making a guess as to the classification of the training data, and then measuring it against the known label, calculating the result. Accuracy i...
history = model.fit_generator( train_generator, steps_per_epoch=8, epochs=15, verbose=1, validation_data = validation_generator, validation_steps=8)
Epoch 1/15 6/8 [=====================>........] - ETA: 1s - loss: 2.9195 - acc: 0.4743Epoch 1/15 8/8 [==============================] - 1s 90ms/step - loss: 0.6141 - acc: 0.6953 8/8 [==============================] - 6s 745ms/step - loss: 2.3494 - acc: 0.4950 - val_loss: 0.6141 - val_acc: 0.6953 Epoch 2/15 7/8 [=======...
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
Running the ModelLet's now take a look at actually running a prediction using the model. This code will allow you to choose 1 or more files from your file system, it will then upload them, and run them through the model, giving an indication of whether the object is a horse or a human.
import numpy as np from google.colab import files from keras.preprocessing import image uploaded = files.upload() for fn in uploaded.keys(): # predicting images path = '/content/' + fn img = image.load_img(path, target_size=(150, 150)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = ...
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
Visualizing Intermediate RepresentationsTo get a feel for what kind of features our convnet has learned, one fun thing to do is to visualize how an input gets transformed as it goes through the convnet.Let's pick a random image from the training set, and then generate a figure where each row is the output of a layer, ...
import numpy as np import random from tensorflow.keras.preprocessing.image import img_to_array, load_img # Let's define a new Model that will take an image as input, and will output # intermediate representations for all layers in the previous model after # the first. successive_outputs = [layer.output for layer in mo...
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
As you can see we go from the raw pixels of the images to increasingly abstract and compact representations. The representations downstream start highlighting what the network pays attention to, and they show fewer and fewer features being "activated"; most are set to zero. This is called "sparsity." Representation spa...
import os, signal os.kill(os.getpid(), signal.SIGKILL)
_____no_output_____
Apache-2.0
HorsevsHumanwithLessSize.ipynb
sunneysood/Tensorflow
Python - Writing Your First Python Code! Welcome! This notebook will teach you the basics of the Python programming language. Although the information presented here is quite basic, it is an important foundation that will help you read and write Python code. By the end of this notebook, you'll know the basics of Pyth...
# Try your first Python output print('Hello, Python!') #ini tugas pertama print ('Nikky Rufiansya')
Nikky Rufiansya
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
After executing the cell above, you should see that Python prints Hello, Python!. Congratulations on running your first Python code! [Tip:] print() is a function. You passed the string 'Hello, Python!' as an argument to instruct Python on what to print. What version of Python are we using? There are two popula...
# Check the Python Version import sys print(sys.version)
3.5.2 (default, Oct 8 2019, 13:06:37) [GCC 5.4.0 20160609]
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
[Tip:] sys is a built-in module that contains many system-specific parameters and functions, including the Python version in use. Before using it, we must explictly import it. Writing comments in Python In addition to writing code, note that it's always a good idea to add comments to your code. It will help ot...
# Practice on writing comments print('Hello, Python!') # This line prints a string # print('Hi') print('\nHia')
Hello, Python! Hia
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
After executing the cell above, you should notice that This line prints a string did not appear in the output, because it was a comment (and thus ignored by Python). The second line was also not executed because print('Hi') was preceded by the number sign () as well! Since this isn't an explanatory comment from ...
# Print string as error message print("Hello, Python!")
Hello, Python!
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
The error message tells you: where the error occurred (more useful in large notebook cells or scripts), and what kind of error it was (NameError) Here, Python attempted to run the function frint, but could not determine what frint is since it's not a built-in function and it has not been previously defined by u...
# Try to see build in error message print("Hello, Python!")
Hello, Python!
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses