markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Le score td-idf pour le terme "Mr. Green" est le plus élevé pour le document a. Exercice 1 Quel document est le plus proche du terme "green plant ? Calculer les scores TF-IDF pour le terme "green plan". Cela correspond-il à vos attentes ? Que se passe-t-il si vous inversez les termes "green" et "plant" ? Que se passe-...
import nltk # nltk donne accès a des methodes, mais aussi à des données, qui faut télécharge grâce à la commande .download() nltk.download('stopwords') from pprint import pprint len(activity_results) if len(activity_results) > 0: pprint(activity_results[0]) if len(activity_results) > 0: pprint(activity_res...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Exercice 4 Quel document est le plus proche de celui-ci: https://plus.google.com/+TimOReilly/posts/7EaHeYc1BiB ? Représenter la matrice de distance à l'aide d'une heatmap. Que donne un clustering hiérarchique ? Approche contextuelle Les approches bag-of-words, bien que simplistes, permettent de créer d'indexer et de ...
import nltk sentence = "Mr. Green killed Colonel Mustard in the study with the " + \ "candlestick. Mr. Green is not a very nice fellow." print(list(nltk.ngrams(sentence.split(), 2))) txt = nltk.Text(sentence.split()) txt.collocation_list()
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
$\alpha$-CsCl ($Pm\overline{3}m$) Let's start with the typical $\alpha$ form of CsCl.
# Create CsCl structure a = 4.209 #Angstrom latt = Lattice.cubic(a) structure = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]]) c = XRDCalculator() c.show_plot(structure)
notebooks/2013-01-01-Calculating XRD patterns.ipynb
materialsvirtuallab/matgenb
bsd-3-clause
$\beta$-CsCl ($Fm\overline{3}m$) Let's now look at the $\beta$ (high-temperature) form of CsCl.
# Create CsCl structure a = 6.923 #Angstrom latt = Lattice.cubic(a) structure = Structure(latt, ["Cs", "Cs", "Cs", "Cs", "Cl", "Cl", "Cl", "Cl"], [[0, 0, 0], [0.5, 0.5, 0], [0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0.5], [0, 0, 0.5], [0, 0.5, 0], [0.5, 0, 0]]) c.show_plot(...
notebooks/2013-01-01-Calculating XRD patterns.ipynb
materialsvirtuallab/matgenb
bsd-3-clause
Define some helpful functions
def estimate_d(img, name, wavelength, pixel_size): # find the res = find_ring_center_acorr_1D(img) res2 = refine_center(img, res, pixel_size, 25, 5, thresh=0.1, window_size=5) bins, sums, counts = img_to_relative_xyi(img, res2, radial_grid) mask = counts > 10 bin_centers = bin_edges_to_centers(...
broken/powder_calibration/D_estimate_demo.ipynb
sameera2004/scikit-xray-examples
bsd-3-clause
Setup data for Si standard sample
si_fname = 'Si_STD_d204-00002.tif' si_name = 'Si' si_wavelength = 0.1839 si_data = TiffStack(si_fname)
broken/powder_calibration/D_estimate_demo.ipynb
sameera2004/scikit-xray-examples
bsd-3-clause
Setup data for LaB6 calibration standard
lab6_fname = 'LaB6_d500-0p72959-2Kx2K_pix200.tif' lab6_name = 'LaB6' lab6_wavelength = .72959 lab6_data = TiffStack(lab6_fname)
broken/powder_calibration/D_estimate_demo.ipynb
sameera2004/scikit-xray-examples
bsd-3-clause
Calibrate Si data
calib_si = estimate_d(si_data[0], si_name, si_wavelength, pixel_size) print("D: {} ± {}".format(calib_si[0], calib_si[1])) print("center: {}".format(calib_si[2])) cal_si = skbeam.core.calibration.calibration_standards['Si'] si_rings = calib_si[0] * np.tan(cal_si.convert_2theta(si_wavelength)) / .2 fig, ax = plt.subpl...
broken/powder_calibration/D_estimate_demo.ipynb
sameera2004/scikit-xray-examples
bsd-3-clause
Calibrate using Lab 6 data
calib_lab6 = estimate_d(lab6_data[0], lab6_name, lab6_wavelength, pixel_size) print("D: {} ± {}".format(calib_lab6[0], calib_lab6[1])) print("center: {}".format(calib_lab6[2])) cal_lab6 = nsls2.calibration.calibration_standards['LaB6']\n", lab6_rings = calib_lab6[0] * np.tan(cal_lab6.convert_2theta(lab6_wavelength)) /...
broken/powder_calibration/D_estimate_demo.ipynb
sameera2004/scikit-xray-examples
bsd-3-clause
Polynomial a Polynomial is an Expr defined by factors and with some more methods
p1=Polynomial([-1,1,3]) # inited from coefficients in ascending power order p1 # Latex output by default p2=Polynomial('- 5x^3 +3*x') # inited from string, in any power order, with optional spaces and * p2.plot() [(x,p1(x)) for x in itertools2.linspace(-1,1,11)] #evaluation p1-p2+2 # addition and subtraction of poly...
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Motion "motion laws" are functions of time which return (position, velocity, acceleration, jerk) tuples
from Goulib.motion import *
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Polynomial Segments Polynomials are very handy to define Segments as coefficients can easily be determined from start/end conditions. Also, polynomials can easily be integrated or derivated in order to obtain position, velocity, or acceleration laws from each other. Motion defines several handy functions that return Se...
seg=Segment2ndDegree(0,1,(-1,1,2)) # time interval and initial position,velocity and constant acceleration seg.plot() seg=Segment4thDegree(0,0,(-2,1),(2,3)) #start time and initial and final (position,velocity) seg.plot() seg=Segment4thDegree(0,2,(-2,1),(None,3)) # start and final time, initial (pos,vel) and final ve...
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Interval operations on [a..b[ intervals
from Goulib.interval import * Interval(5,6)+Interval(2,3)+Interval(3,4)
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Piecewise Piecewise defined functions
from Goulib.piecewise import *
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
The simplest are piecewise continuous functions. They are defined by $(x_i,y_i)$ tuples given in any order. $f(x) = \begin{cases}y_0 & x < x_1 \ y_i & x_i \le x < x_{i+1} \ y_n & x > x_n \end{cases}$
p1=Piecewise([(4,4),(3,3),(1,1),(5,0)]) p1 # default rendering is LaTeX p1.plot() #pity that matplotlib doesn't accept large LaTeX as title...
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
By default y0=0 , but it can be specified at construction. Piecewise functions can also be defined by adding (x0,y,x1) segments
p2=Piecewise(default=1) p2+=(2.5,1,6.5) p2+=(1.5,1,3.5) p2.plot(xmax=7,ylim=(-1,5)) plot.plot([p1,p2,p1+p2,p1-p2,p1*p2,p1/p2], labels=['p1','p2','p1+p2','p1-p2','p1*p2','p1/p2'], xmax=7, ylim=(-2,10), offset=0.02) p1=Piecewise([(2,True)],False) p2=Piecewise([(1,True),(2,False),(3,True)],False) plot.plot([p1...
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Piecewise Expr function
from math import cos f=Piecewise().append(0,cos).append(1,lambda x:x**x) f f.plot()
notebooks/polynomial.ipynb
goulu/Goulib
lgpl-3.0
Expected Output <table> <center> Total Params: 3743280 </center> </table> By using a 128-neuron fully connected layer as its last layer, the model ensures that the output is an encoding vector of size 128. You then use the encodings the compare two face images as follows: <img src="images/distance_kiank.png" style="w...
# GRADED FUNCTION: triplet_loss def triplet_loss(y_true, y_pred, alpha = 0.2): """ Implementation of the triplet loss as defined by formula (3) Arguments: y_true -- true labels, required when you define a loss in Keras, you don't need it in this function. y_pred -- python list containing three...
Course 4/Face Recognition for the Happy House v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Now, when someone shows up at your front door and swipes their ID card (thus giving you their name), you can look up their encoding in the database, and use it to check if the person standing at the front door matches the name on the ID. Exercise: Implement the verify() function which checks if the front-door camera pi...
# GRADED FUNCTION: verify def verify(image_path, identity, database, model): """ Function that verifies if the person on the "image_path" image is "identity". Arguments: image_path -- path to an image identity -- string, name of the person you'd like to verify the identity. Has to be a residen...
Course 4/Face Recognition for the Happy House v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Expected Output: <table> <tr> <td> **It's not kian, please go away** </td> <td> (0.86224014, False) </td> </tr> </table> 3.2 - Face Recognition Your face verification system is mostly working well. But since Kian got his ID card stolen, when he came back ...
# GRADED FUNCTION: who_is_it def who_is_it(image_path, database, model): """ Implements face recognition for the happy house by finding who is the person on the image_path image. Arguments: image_path -- path to an image database -- database containing image encodings along with the name of th...
Course 4/Face Recognition for the Happy House v3.ipynb
ShubhamDebnath/Coursera-Machine-Learning
mit
Now that we have a function to generate hillshade, we need to read in the NEON LiDAR Digital Terrain Model (DTM) geotif using the raster2array function and then calculate hillshade using the hillshade function. We can then plot both using the plot_band_array function.
# Use raster2array to convert TEAK DTM Geotif to array & plot dtm_array, dtm_metadata = raster2array('TEAK_D17_Data_2013/TEAK_LiDAR_Data/TEAK_lidarDTM.tif') plot_band_array(dtm_array,dtm_metadata['extent'],'TEAK DTM','Elevation, m',colormap='gist_earth') ax = plt.gca(); plt.grid('on') # Use hillshade function on a DTM...
code/Python/remote-sensing/lidar/create_hillshade_from_terrain_raster_py.ipynb
mjones01/NEON-Data-Skills
agpl-3.0
Calculate CHM & Overlay on Top of Hillshade
#Calculate CHM from DSM & DTM: dsm_array, dsm_metadata = raster2array('TEAK_D17_Data_2013/TEAK_LiDAR_Data/TEAK_lidarDSM.tif') teak_chm = dsm_array - dtm_array; plot_band_array(teak_chm,dtm_metadata['extent'],'TEAK Canopy Height Model','Canopy Height, m',colormap='Greens') ax = plt.gca(); plt.grid('on') #Overlay trans...
code/Python/remote-sensing/lidar/create_hillshade_from_terrain_raster_py.ipynb
mjones01/NEON-Data-Skills
agpl-3.0
Links to Tutorials on Creating Hillshades: Python Hillshade: - http://geoexamples.blogspot.com/2014/03/shaded-relief-images-using-gdal-python.html - http://pangea.stanford.edu/~samuelj/musings/dems-in-python-pt-3-slope-and-hillshades-.html ESRI ArcGIS Hillshade Algorithm: - http://webhelp.esri.com/arcgisdesktop/9.2/ind...
#Importing the TEAK CHM Geotiff resulted in v. sparse data ? chm_array, chm_metadata = raster2array('TEAK_lidarCHM.tif') print('TEAK CHM Array\n:',chm_array) # print(chm_metadata) #print metadata in alphabetical order for item in sorted(chm_metadata): print(item + ':', chm_metadata[item]) # print(chm_metadat...
code/Python/remote-sensing/lidar/create_hillshade_from_terrain_raster_py.ipynb
mjones01/NEON-Data-Skills
agpl-3.0
Now we are ready to set up our AIRL trainer. Note, that the reward_net is actually the network of the discriminator. We evaluate the learner before and after training so we can see if it made any progress.
from imitation.algorithms.adversarial.airl import AIRL from imitation.rewards.reward_nets import BasicShapedRewardNet from imitation.util.networks import RunningNorm from stable_baselines3 import PPO from stable_baselines3.common.evaluation import evaluate_policy from stable_baselines3.common.vec_env import DummyVecEnv...
examples/4_train_airl.ipynb
HumanCompatibleAI/imitation
mit
Prepare the dependencies
%%px import os import time import nnabla as nn import nnabla.communicators as C from nnabla.ext_utils import get_extension_context import nnabla.functions as F from nnabla.initializer import ( calc_uniform_lim_glorot, UniformInitializer) import nnabla.parametric_functions as PF import nnabla.solvers as S impor...
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Define the communicator for gradients exchange.
%%px extension_module = "cudnn" ctx = get_extension_context(extension_module) comm = C.MultiProcessCommunicator(ctx) comm.init() n_devices = comm.size mpi_rank = comm.rank device_id = mpi_rank ctx = get_extension_context(extension_module, device_id=device_id)
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Check different ranks are assigned to different devices
%%px print("n_devices={}".format(n_devices)) print("mpi_rank={}".format(mpi_rank))
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Create data points and a very simple neural network
%%px # Data points setting n_class = 2 b, c, h, w = 4, 1, 32, 32 # Data points x_data = np.random.rand(b, c, h, w) y_data = np.random.choice(n_class, b).reshape((b, 1)) x = nn.Variable(x_data.shape) y = nn.Variable(y_data.shape) x.d = x_data y.d = y_data # Network setting C = 1 kernel = (3, 3) pad = (1, 1) stride = ...
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Important notice here is that w_init is passed to parametric functions to let the network on each GPU start from the same values of trainable parameters in the optimization process. Create a solver.
%%px # Solver and add parameters solver = S.Adam() solver.set_parameters(nn.get_parameters())
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Training Recall the basic usage of nnabla API for training a neural network, it is loss.forward() solver.zero_grad() loss.backward() solver.update() In use of C.MultiProcessCommunicator, these steps are performed in different GPUs, and the only difference from these steps is comm.all_reduce(). Thus, in case of C.Mul...
%%px # Training steps loss.forward() solver.zero_grad() loss.backward()
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Check gradients of weights once,
%%px for n, v in nn.get_parameters().items(): print(n, v.g)
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
You can see the different values on each device, then call all_reduce,
%%px comm.all_reduce([x.grad for x in nn.get_parameters().values()], division=True)
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Commonly, all_reduce only means the sum; however, comm.all_reduce addresses both cases: summation and summation division. Again, check gradients of weights,
%%px for n, v in nn.get_parameters().items(): print(n, v.g)
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
You can see the same values over the devices because of all_reduce. Update weights,
%%px solver.update()
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
This concludes the usage of C.MultiProcessCommunicator for Data Parallel Distributed Training. Now you should have an understanding of how to use C.MultiProcessCommunicator, go to the cifar10 example, classification.py for more details. Advanced Topics When working with multiple nodes with multiple devices (e.g. GP...
extension_module = "cudnn" type_config = "float" ctx = get_extension_context(extension_module, type_config=type_config) comm = C.MultiProcessDataParalellCommunicator(ctx) comm.init() if comm.rank == 0: ... # Here, we do some task on node 0 if comm.rank != 0: ... # here, we do some task on other nodes # Til...
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
In order to avoid above unexpected exception, we have to explicitly set the synchronization point.
extension_module = "cudnn" type_config = "float" ctx = get_extension_context(extension_module, type_config=type_config) comm = C.MultiProcessDataParalellCommunicator(ctx) comm.init() if comm.rank == 0: ... # Here, we do some task on node 0 if comm.rank != 0: ... # here, we do some task on other nodes comm....
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
We placed the synchronization point immediately before comm.all_reduce(), which means that we knew comm.all_reduce() should be perform synchronously after this point. Thus, we may ensure the whole training can be performed stably and not need to wait forever due to a corrupted process. If want to disable this watch dog...
%%bash export NNABLA_MPI_WATCH_DOG_MUTE=1
tutorial/multi_device_training.ipynb
sony/nnabla
apache-2.0
Project 1: Quick Theory Validation
from collections import Counter import numpy as np positive_counts = Counter() negative_counts = Counter() total_counts = Counter() for i in range(len(reviews)): if(labels[i] == 'POSITIVE'): for word in reviews[i].split(" "): positive_counts[word] += 1 total_counts[word] += 1 e...
sentiment-network/Sentiment Classification - Mini Project 5.ipynb
swirlingsand/deep-learning-foundations
mit
Project 2: Creating the Input/Output Data
vocab = set(total_counts.keys()) vocab_size = len(vocab) print(vocab_size) # list(vocab) import numpy as np layer_0 = np.zeros((1,vocab_size)) layer_0 from IPython.display import Image Image(filename='sentiment_network.png') word2index = {} for i,word in enumerate(vocab): word2index[word] = i # word2inde...
sentiment-network/Sentiment Classification - Mini Project 5.ipynb
swirlingsand/deep-learning-foundations
mit
Project 3: Building a Neural Network Start with your neural network from the last chapter 3 layer neural network no non-linearity in hidden layer use our functions to create the training data create a "pre_process_data" function to create vocabulary for our training data generating functions modify "train" to train ov...
import time import sys import numpy as np # Let's tweak our network from before to model these phenomena class SentimentNetwork: def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1): # set our random number generator np.random.seed(1) self.pre_process_data...
sentiment-network/Sentiment Classification - Mini Project 5.ipynb
swirlingsand/deep-learning-foundations
mit
Understanding Neural Noise
from IPython.display import Image Image(filename='sentiment_network.png') def update_input_layer(review): global layer_0 # clear out previous state, reset the layer to be all 0s layer_0 *= 0 for word in review.split(" "): layer_0[0][word2index[word]] += 1 update_input_layer(reviews[0...
sentiment-network/Sentiment Classification - Mini Project 5.ipynb
swirlingsand/deep-learning-foundations
mit
Project 4: Reducing Noise in our Input Data
import time import sys import numpy as np # Let's tweak our network from before to model these phenomena class SentimentNetwork: def __init__(self, reviews,labels,hidden_nodes = 10, learning_rate = 0.1): # set our random number generator np.random.seed(1) self.pre_process_data...
sentiment-network/Sentiment Classification - Mini Project 5.ipynb
swirlingsand/deep-learning-foundations
mit
Problem 1) An (oversimplified) 1-D Model For this introductory problem we are going to simulate a 1 dimensional detector (the more complex issues associated will real stars on 2D detectors will be covered tomorrow by Dora). We will generate stars as Gaussians $N(\mu, \sigma^2)$, with mean $\mu$ and variance $\sigma^2$....
def phi(x, mu, fwhm): # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 1b Plot the noise-free PSF for a star with $\mu = 10$ and $\mathrm{FWHM} = 3$. What is the flux of this star?
x = # complete plt.plot( # complete print("The flux of the star is: {:.3f}".format( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 1c Add Sky noise (a constant in this case) to your model. Define the sky as S, with total stellar flux F. Plot the model for S = 100 and F = 500.
plt.plot( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 2) Add Noise We will add noise to this simulation assuming that photon counting contributes the only source of uncertainty (this assumption is far from sufficient in real life). Within each pixel, $n$ photons are detected with an uncertainty that follows a Poisson distribution, which has the property that the m...
# complete noisy_flux = # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 2b Overplot the noisy signal, with the associated uncertainties, on top of the noise-free signal.
plt.plot( # complete plt.errorbar( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 3) Flux Measurement We will now attempt to measure the flux from a simulated star. Problem 3a Write a function simulate() to simulate the noisy flux measurements of a star with centroid mu, FWHM fwhm, sky background S, and flux F. Hint - it may be helpful to plot the output of your function.
def simulate(# complete # complete # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 3b Using an aperture with radius of 5 pixels centered on the source, measure the flux from a star centered at mu = 0, with fwhm = 5, S = 100, and F = 1000. Hint - assume you can perfectly measure the background, and subtract this prior to the measurement.
# complete sim_star = simulate( # complete ap_flux = # complete print("The star has flux = {:.3f}".format( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 3c Write a Monte Carlo simulator to estimate the mean and standard deviation of the flux from the simulated star. Food for thought - what do you notice if you run your simulator many times?
sim_fluxes = # complete for # complete print("The mean flux = {:.3f} with variance = {:.3f}".format( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 4) PSF Flux measurement In this problem we are going to use our knowledge of the PSF to estimate the flux of the star. We will compare these measurements to the aperture flux measurements above. Problem 4a Create the psf model, psf, which is equivalent to a noise-free star with fwhm = 5.
psf = # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 4b Using the same parameters as problem 3, simulate a star and measure it's PSF flux.
sim_star = simulate( # complete psf_flux = # complete print("The PSF flux is {:.3f}".format( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
Problem 4c As before, write a Monte Carlo simulator to estimate the PSF flux of the star. How do your results compare to above?
sim_fluxes = # complete for # complete print("The mean flux = {:.3f} with variance = {:.3f}".format( # complete
Sessions/Session05/Day1/ReIntroductionToImageProcessing.ipynb
LSSTC-DSFP/LSSTC-DSFP-Sessions
mit
2. Load daily SST data The daily time series of SST off Western Australia at the location of [112.5$^∘$E, 29.5$^∘$S] has been preprocessed over the 1982 to 2017 period in advance. This can be done using NCO, CDO, Matlab, or Python itself. The location is right at the center of domain [112.375~112.625$^∘$E, 29.375~29.62...
sst = np.loadtxt('data/sst_WA.csv', delimiter=',') # Generate time vector using datetime format (January 1 of year 1 is day 1) t = np.arange(date(1982,1,1).toordinal(),date(2017,12,31).toordinal()+1) dates = [date.fromordinal(tt.astype(int)) for tt in t]
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
3. Detect Marine Heatwave The marineHeatWaves (mhw) module consists of a number of functions for the detection and characterization of MHWs. The main function is the detection function (detect) which takes as input a time series of temperature (and a corresponding time vector) and outputs a set of detected MHWs. 3.1 De...
mhws, clim = mhw.detect(t, sst)
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
3.2 Check properties of MHWs The number of MHW events:
mhws['n_events']
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
Maximum intensities (in $^∘$C) of the first ten events
mhws['intensity_max'][0:10]
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
Properties of the event with the largest maximum intensity
ev = np.argmax(mhws['intensity_max']) # Find largest event print 'Maximum intensity:', mhws['intensity_max'][ev], 'deg. C' print 'Average intensity:', mhws['intensity_mean'][ev], 'deg. C' print 'Cumulative intensity:', mhws['intensity_cumulative'][ev], 'deg. C-days' print 'Duration:', mhws['duration'][ev], 'days' print...
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
4. Visualize From the properties of the event with the largest maximum intensity, it can be found that it is the most famous 2011 MHW off WA. 4.1 Plot the SST time series and have a closer look at the identified MHW event
plt.figure(figsize=(14,10)) plt.subplot(2,1,1) # Plot SST, seasonal cycle, and threshold plt.plot(dates, sst, 'k-') plt.plot(dates, clim['thresh'], 'g-') plt.plot(dates, clim['seas'], 'b-') plt.title('SST (black), seasonal climatology (blue), \ threshold (green), detected MHW events (shading)') plt.xlim(t[0],...
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
Yep, It's certainly picked out the largest event in the series (dark red shading). This event also seems to have been preceded and succeeded by a number of shorter, weaker events (light red shading). 4.2 Visualize distributions of MHW statistics across all the detected events
plt.figure(figsize=(15,7)) # Duration plt.subplot(2,2,1) evMax = np.argmax(mhws['duration']) plt.bar(range(mhws['n_events']), mhws['duration'], width=0.6, \ color=(0.7,0.7,0.7)) plt.bar(evMax, mhws['duration'][evMax], width=0.6, color=(1,0.5,0.5)) plt.bar(ev, mhws['duration'][ev], width=0.6, edgecolor=(1,0.,0.)...
ex26-Identify Marine Heatwaves from High-resolution Daily SST Data.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
Lecture des données d'apprentissage et de test Les données peuvent être préalablement téléchargées ou directement lues. Ce sont celles originales du site MNIST DataBase mais préalablement converties au format .csv, certes plus volumineux mais plus facile à lire. Attention le fichier mnist_train.zip présent dans le dépô...
# Lecture des données d'apprentissage N_classes = 10 # path="" # Si les données sont dans le répertoire courant sinon: path="" Dtrain=pd.read_csv(path+"mnist_train.zip",header=None) X_train = Dtrain.values[:,:-1] Y_train = Dtrain.values[:,-1] Dtest=pd.read_csv(path+"mnist_test.csv",header=None) X_test = Dtest.values[...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Attention, avec Keras, la variable réponse doit être une matrice binaire où chaque classe est représentée par une indicatrice: pour chaque individu, l'élément de la colone correspondant à la classe à laquelle il appartient est à 1, sinon il est à 0. Keras possède une fonction to_catergorical permettant de convertir di...
Y_train_cat = ku.to_categorical(Y_train, N_classes) Y_test_cat = ku.to_categorical(Y_test, N_classes)
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Apprentissage et prévision du test Avec réseau dense Première tentative d'appliquer un réseaux de neurone de type Perceptron classique avec 4 couches: * Dense: 52 neurones + Foncton d'activation relu * Dropout: 20% des neurones tiré aléatoirement sont desactivés * Dense: 52 neurones + Foncton d'activation relu * Dropo...
X_train.shape # Définition du réseau model = km.Sequential() model.add(kl.Dense(128, activation='relu', input_shape=(784,))) model.add(kl.Dropout(0.2)) model.add(kl.Dense(128, activation='relu')) model.add(kl.Dropout(0.2)) model.add(kl.Dense(N_classes, activation='softmax')) # Réumé model.summary()
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Retrouvez manuellement le nombre de paramètres.
# apprentissage model.compile(loss='categorical_crossentropy', optimizer=ko.RMSprop(), metrics=['accuracy']) ts = time.time() history = model.fit(X_train, Y_train_cat, batch_size=batch_size, epochs=epochs, verbose=1, ...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Résultats
score_mpl = model.evaluate(X_test, Y_test_cat, verbose=0) predict_mpl = model.predict(X_test) print('Test loss:', score_mpl[0]) print('Test accuracy:', score_mpl[1]) print("Time Running: %.2f seconds" %t_train_mpl ) fig=plt.figure(figsize=(7,6)) ax = fig.add_subplot(1,1,1) ax = sb.heatmap(pd.DataFrame(confusion_matrix(...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Que dire de ces résultats ? Q Faites tourner de nouveaux l'algorithme en normalisant les données afin que celles-ci soit comprises entre 0 et 1. Qu'observez vous? Convolutional Layers Format des données Dans les exemples précédents. Les données était "applaties". Une imade de $28\times 28=784$ pixels est considérée ...
X_train_conv = X_train.reshape(60000, 28, 28, 1) X_test_conv = X_test.reshape(10000, 28, 28, 1)
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Visualisation des données
import keras.preprocessing.image as kpi fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(1,1,1) x = kpi.img_to_array(X_train_conv[0]) ax.imshow(x[:,:,0]/255, interpolation='nearest', cmap="binary") ax.grid(False) plt.show()
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Edge detection Dans cette partie vous pouvez explorer l'effet de filtre de convolution simple sur une image. Un réseau de neuronne constitué d'une couche de convolution constitué d'un seul filtre définie manuellement (non appris par optimisation) est définie dans le code ci-dessous.
from keras.models import Sequential from keras.layers import Conv2D conv_filter = np.array([ [0.2, -0.2, 0], [0.2, -0.2, 0], [0.2, -0.2, 0], ]) def my_init_filter(shape, conv_filter = conv_filter, dtype=None): xf,yf = conv_filter.shape array = conv_filter.reshape(xf, yf, 1, 1) ...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Notez que dans la fonction my_init_filter les dimensions de l'image sont modifiés. A quoi correspondent les deux dimensions ajoutées?
img_in = np.expand_dims(x, 0) img_out = conv_edge.predict(img_in) fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(15, 5)) ax0.imshow(img_in[0,:,:,0], cmap="binary") ax0.set_title("Image originale") ax0.grid(False) norm_conv_filter = (conv_filter-conv_filter.min())/conv_filter.max() ax1.imshow(norm_conv_filter.a...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Que constatez vous? Verifiez que les dimensions de l'image en sortie sont cohérentes. Q Testez ce même code avec un filtre différent. Strides and Padding Dans cette partie vous pouvez explorer l'effet des arguments strideset padding sur une image.
from keras.models import Sequential from keras.layers import Conv2D conv_filter = np.array([ [0, 0, 0], [0, 1, 0], [0, 0, 0], ]) def my_init_filter(shape, conv_filter = conv_filter, dtype=None): xf,yf = conv_filter.shape array = conv_filter.reshape(xf, yf, 1, 1) return array my...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Quel est l'effet du filtre défini ici?
img_in = np.expand_dims(x, 0) img_out = conv_sp.predict(img_in) fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(15, 5)) ax0.imshow(img_in[0,:,:,0].astype(np.uint8), cmap="binary"); ax0.grid(False) norm_conv_filter = (conv_filter-conv_filter.min())/conv_filter.max() ax1.imshow(norm_conv_filter.astype(...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Modifiez les paramètres strideet padding, et observez l'effet sur la dimension des images. Max Pooling Exercice Ecrivez un code similaire pour observez l'effet du MaxPooling.
# %load max_pooling.py
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Convolutional Network (ConvNet) Les propriété d'invariance par translation introduites par les couches opérant une convolution des images ont un impact important sur la qualité des résultats. LeNet5 On teste dans un premier temps le modèle LeNet5 proposer par LeCun et al.
LeNet5model = km.Sequential() LeNet5model.add(kl.Conv2D(filters = 6, kernel_size = 5, strides = 1, activation = 'tanh', input_shape = (28,28,1))) LeNet5model.add(kl.MaxPooling2D(pool_size = 2, strides = 2)) LeNet5model.add(kl.Conv2D(filters = 16, kernel_size = 5,strides = 1, activation = 'tanh')) LeNet5model.add(kl.Max...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Retrouvez manuellement le nombre de paramètres. Q Que dire du nombre de paramètres de ce réseau par rapport au réseau dense précédement défini?
# Apprentissage LeNet5model.compile(loss="categorical_crossentropy", optimizer=ko.Adadelta(), metrics=['accuracy']) ts=time.time() LeNet5model.fit(X_train_conv, Y_train_cat, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(X_test_conv,...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Q Que dire du temps de calcul? Pourquoi est-il plus long que le réseau Dense? Résultats
score_conv = LeNet5model.evaluate(X_test_conv, Y_test_cat, verbose=0) predict_conv = LeNet5model.predict(X_test_conv) print('Test loss:', score_conv[0]) print('Test accuracy:', score_conv[1]) print("Time Running: %.2f seconds" %t_train_conv ) fig=plt.figure(figsize=(7,6)) ax = fig.add_subplot(1,1,1) ax = sb.heatmap(pd...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Autre architecture Réseau Test d'un réseau de convolution constitué de 7 couches: Une couche de convolution 2D, avec fenêtre de taille 3x3 et une fonction d'activation relu Une couche de convolution 2D, avec fenêtre de taille 3x3 et une fonction d'activation relu Une couche max pooling de fenêtre 2x2 Une couche dropo...
# descrition du réseau model = km.Sequential() model.add(kl.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28,28, 1), data_format="channels_last")) model.add(kl.Conv2D(64, (3, 3), activation='relu')) model.add(kl.MaxPooling2D(pool_size=(2, 2))) model.add(kl.Dropout(0.25)) model.add(kl.Flatten()) model.a...
MNIST/Atelier-keras-MNIST.ipynb
wikistat/Ateliers-Big-Data
mit
Let's check how many items in the dictionary.
print len(questions)
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Yes, 7949 items is right. How about question numbers? It is continuous number or not? We might want to check the first and last 10 items.
print sorted(questions.keys())[:10] print sorted(questions.keys())[-10:]
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Yes, it's not continuous data in terms of qid. But, it's OK. What about just see one question? How can we do it? Just look at qid 1.
questions[1]
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Yes, it's dictionary. So, you can use some dictionary functions. Check this out.
questions[1].keys() questions[1]['answer'] questions[1]['pos_token'] questions[1]['pos_token'].keys() questions[1]['pos_token'].values() questions[1]['pos_token'].items()
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
How can figure out questions length without tokenizing question it self?
max(questions[1]['pos_token'].keys())
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Make questions pickled data As you know that, reading csv and coverting it as a dictionary spend more than one minute. Once we convert it as a dictionary, we can save it as a pickled data and we can load it when we need. It is really simple and fast. Look at that! Wait! We will use gzip.open instead of open because pic...
with gzip.open("questions.pklz", "wb") as output: pickle.dump(questions, output)
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Yes, now we can load pickled data as a variable.
with gzip.open("questions.pklz", "rb") as fp: questions_new = pickle.load(fp) print len(questions_new)
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Yes, it took only few second. I will save it, make it as a commit, and push it into github. So, you can use pickled data instead of converting questions.csv
print questions == questions print questions == questions_new questions_new[0] = 1 print questions == questions_new
howto/make_data_a_serialized_object.ipynb
sangheestyle/ml2015project
mit
Now that the <b>data</b> is accessible, it will need to be sliced so that I can create a manageable data object in order to further analyze the data in the <i>csv file</i>.
status = [n for n in data['status']] airline = [n for n in data['airline']] la = [n for n in data['LosAngeles']] phx = [n for n in data['Phoenix']] sandg = [n for n in data['SanDiego']] sanfrn = [n for n in data['SanFrancisco']] seatl = [n for n in data['Seattle']]
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
I will use the zip function to create a tuple set of the above sliced data list, to create a <b>DataFrame</b> object I can work with.
flight_status = zip(status, la, phx, sandg, sanfrn, seatl) flight_status flight_df = DataFrame(data = flight_status, columns = ['status', 'la','phx','sandiego','sanfrancisco','seattle'], index = airline) flight_df flight_df.plot(kind='bar', title='Flights Database Visualization')
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
<img src="bar1.png"> The bar graph above allows me to visualize which cities have the most flights, ontime+delayed each by airline and diferentiated by <b>colored cities</b>. <b>AMWEST</b> and <b>American Airlines</b> both have the highest number of flights in phoenix, followed by <b>ALASKA</b> and <b>United Airlines</...
flight_df.loc['AMWEST', 'phx'].plot(kind='bar', title='Phoenix AMWEST on-time vs delayed')
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
<img src='phx_1aw.png'> <b>AMWEST</b> does relatively well in <i>Phoenix</i> for the number of ontime flights, compared to delayed flights. <img src='phx_1aa.png'> <b>American Airlines</b> does well also in <i> Phoenix</i> although the number of flights are higher in relation to the ontime flights when compared with <b...
flight_df.loc['ALASKA', 'seattle'].plot(kind='bar', title='ALASKA Seattle on-time vs delayed')
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
<img src='stl_1al.png'> The same argument could be made in this observation here, where <b>ALASKA</b> does well over all other flights ontime for Seatle, but ranges close to 400 delays for about nearly 2000 <i>ontime flights</i>.
flight_df.loc['United Airlines', 'seattle'].plot(kind='bar', title='Seatle U. Airlines on-time vs delayed')
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
<img src='stl_1ul.png'>
flight_df.loc['American Airlines', 'phx'].plot(kind='bar', title='Phoenix American Airlines on-time vs delayed')
project_1.ipynb
ModestoCabrera/IS360Project_1
gpl-2.0
Load the MNIST database
# --- load the data img_rows, img_cols = 28, 28 (X_train, y_train), (X_test, y_test) = load_mnist() X_train = 2 * X_train - 1 # normalize to -1 to 1 X_test = 2 * X_test - 1 # normalize to -1 to 1 random.seed(1) #same orientations rotated_X_train = X_train.copy() for img in rotated_X_train: img[:] = scipy.ndim...
Project/trained_mental_rotation_ens.ipynb
science-of-imagination/nengo-buffer
gpl-3.0
Load the saved weight matrices that were created by trainging the model
label_weights = cPickle.load(open("label_weights1000.p", "rb")) activity_to_img_weights = cPickle.load(open("activity_to_img_weights1000.p", "rb")) rotated_after_encoder_weights = cPickle.load(open("rotated_after_encoder_weights1000.p", "r")) #rotated_after_encoder_weights_5000 = cPickle.load(open("rotated_after_enco...
Project/trained_mental_rotation_ens.ipynb
science-of-imagination/nengo-buffer
gpl-3.0
The network where the mental imagery and rotation occurs The state, seed and ensemble parameters (including encoders) must all be the same for the saved weight matrices to work The number of neurons (n_hid) must be the same as was used for training The input must be shown for a short period of time to be able to view ...
rng = np.random.RandomState(9) n_hid = 1000 model = nengo.Network(seed=3) with model: #Stimulus only shows for brief period of time stim = nengo.Node(lambda t: ONE if t < 0.1 else 0) #nengo.processes.PresentInput(labels,1))# ens_params = dict( eval_points=X_train, neuron_type=nengo.LIF(...
Project/trained_mental_rotation_ens.ipynb
science-of-imagination/nengo-buffer
gpl-3.0
We can now build a temporary server which acts just like a normal server, but we have a bit more direct control of it. Warning! All data is lost when this notebook shuts down! This is for demonstration purposes only! For information about how to setup a permanent QCFractal server, see the Setup Quickstart Guide.
server = FractalSnowflakeHandler() server
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
We can then build a typical FractalClient to automatically connect to this server using the client() helper command. Note that the server names and addresses are identical in both the server and client.
client = server.client() client
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
Adding and Querying data A server starts with no data, so let's add some! We can do this by adding a water molecule at a poor geometry from XYZ coordinates. Note that all internal QCFractal values are stored and used in atomic units; whereas, the standard Molecule.from_data() assumes an input of Angstroms. We can sw...
mol = ptl.Molecule.from_data(""" O 0 0 0 H 0 0 2 H 0 2 0 units bohr """) mol
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
We can then measure various aspects of this molecule to determine its shape. Note that the measure command will provide a distance, angle, or dihedral depending if 2, 3, or 4 indices are passed in. This molecule is quite far from optimal, so let's run an geometry optimization!
print(mol.measure([0, 1])) print(mol.measure([1, 0, 2]))
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
Evaluating a Geometry Optimization We originally installed psi4 and geometric, so we can use these programs to perform a geometry optimization. In QCFractal, we call a geometry optimization a procedure, where procedure is a generic term for a higher level operation that will run multiple individual quantum chemistry en...
spec = { "keywords": None, "qc_spec": { "driver": "gradient", "method": "b3lyp", "basis": "6-31g", "program": "psi4" }, } # Ask the server to compute a new computation r = client.add_procedure("optimization", "geometric", spec, [mol]) print(r) print(r.ids)
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
We can see that we submitted a single task to be evaluated and the server has not seen this particular procedure before. The ids field returns the unique id of the procedure. Different procedures will always have a unique id, while identical procedures will always return the same id. We can submit the same procedure ...
r2 = client.add_procedure("optimization", "geometric", spec, [mol]) print(r) print(r.ids)
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause
Querying Procedures Once a task is submitted, it will be placed in the compute queue and evaluated. In this particular case the FractalSnowflakeHandler uses your local hardware to evaluate these jobs. We recommend avoiding large tasks! In general, the server can handle anywhere between laptop-scale resources to many hu...
proc = client.query_procedures(id=r.ids)[0] proc
docs/qcfractal/source/quickstart.ipynb
psi4/DatenQM
bsd-3-clause