markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
3. ROC Curve (what is ROC/AUC?) Area Under the Curve (AUC) over 0.7 is considered useful in classification performance. (Streiner and Cairney, 2007, What's under the roc? an introduction to receiver operating charcteristics curves.) AUC calculated by grid search(0.68) is greater than that by greedy method(0.66) 1...
clf_RF = RandomForestClassifier(n_estimators=18, max_features=14, min_samples_leaf=9, oob_score=True).fit(X_train, y_train) clf_RF_predicted = clf_RF.predict(X_test) from sklearn.metrics import roc_curve, auc fpr_rf, tpr_rf, thresholds_rf = roc_curve(y_test, clf_RF.predict_proba(X_test)[:, 0], pos_label=0) fpr_base, t...
3_model selection_evalutation.ipynb
higee/amazon-helpful-review
mit
2) Grid Search
clf_RF = RandomForestClassifier(n_estimators=10, max_features=19, min_samples_leaf=27, criterion='entropy', oob_score=True).fit(X_train, y_train) clf_RF_predicted = clf_RF.predict(X_test) fpr_rf, tpr_rf, thresholds_rf = roc_curve(y_test, clf_RF.predict_proba(X_test)[:, 0], pos_label=0) fpr_base, tpr_base, thresholds_b...
3_model selection_evalutation.ipynb
higee/amazon-helpful-review
mit
Define hyperparameters
AUTO = tf.data.AUTOTUNE BATCH_SIZE = 128 EPOCHS = 5 CROP_TO = 32 SEED = 26 PROJECT_DIM = 2048 LATENT_DIM = 512 WEIGHT_DECAY = 0.0005
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Load the CIFAR-10 dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() print(f"Total training examples: {len(x_train)}") print(f"Total test examples: {len(x_test)}")
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Defining our data augmentation pipeline As studied in SimCLR having the right data augmentation pipeline is critical for SSL systems to work effectively in computer vision. Two particular augmentation transforms that seem to matter the most are: 1.) Random resized crops and 2.) Color distortions. Most of the other SSL ...
def flip_random_crop(image): # With random crops we also apply horizontal flipping. image = tf.image.random_flip_left_right(image) image = tf.image.random_crop(image, (CROP_TO, CROP_TO, 3)) return image def color_jitter(x, strength=[0.4, 0.4, 0.4, 0.1]): x = tf.image.random_brightness(x, max_delt...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
It should be noted that an augmentation pipeline is generally dependent on various properties of the dataset we are dealing with. For example, if images in the dataset are heavily object-centric then taking random crops with a very high probability may hurt the training performance. Let's now apply our augmentation pip...
ssl_ds_one = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_one = ( ssl_ds_one.shuffle(1024, seed=SEED) .map(custom_augment, num_parallel_calls=AUTO) .batch(BATCH_SIZE) .prefetch(AUTO) ) ssl_ds_two = tf.data.Dataset.from_tensor_slices(x_train) ssl_ds_two = ( ssl_ds_two.shuffle(1024, seed=SEED) ...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Notice that the images in samples_images_one and sample_images_two are essentially the same but are augmented differently. Defining the encoder and the predictor We use an implementation of ResNet20 that is specifically configured for the CIFAR10 dataset. The code is taken from the keras-idiomatic-programmer repository...
!wget -q https://git.io/JYx2x -O resnet_cifar10_v2.py import resnet_cifar10_v2 N = 2 DEPTH = N * 9 + 2 NUM_BLOCKS = ((DEPTH - 2) // 9) - 1 def get_encoder(): # Input and backbone. inputs = layers.Input((CROP_TO, CROP_TO, 3)) x = layers.Rescaling(scale=1.0 / 127.5, offset=-1)( inputs ) x ...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Defining the (pre-)training loop One of the main reasons behind training networks with these kinds of approaches is to utilize the learned representations for downstream tasks like classification. This is why this particular training phase is also referred to as pre-training. We start by defining the loss function.
def compute_loss(p, z): # The authors of SimSiam emphasize the impact of # the `stop_gradient` operator in the paper as it # has an important role in the overall optimization. z = tf.stop_gradient(z) p = tf.math.l2_normalize(p, axis=1) z = tf.math.l2_normalize(z, axis=1) # Negative cosine s...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
We then define our training loop by overriding the train_step() function of the tf.keras.Model class.
class SimSiam(tf.keras.Model): def __init__(self, encoder, predictor): super(SimSiam, self).__init__() self.encoder = encoder self.predictor = predictor self.loss_tracker = tf.keras.metrics.Mean(name="loss") @property def metrics(self): return [self.loss_tracker] ...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Pre-training our networks In the interest of this example, we will train the model for only 5 epochs. In reality, this should at least be 100 epochs.
# Create a cosine decay learning scheduler. num_training_samples = len(x_train) steps = EPOCHS * (num_training_samples // BATCH_SIZE) lr_decayed_fn = tf.keras.optimizers.schedules.CosineDecay( initial_learning_rate=0.03, decay_steps=steps ) # Create an early stopping callback. early_stopping = tf.keras.callbacks.E...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
If your solution gets very close to -1 (minimum value of our loss) very quickly with a different dataset and a different backbone architecture that is likely because of representation collapse. It is a phenomenon where the encoder yields similar output for all the images. In that case additional hyperparameter tuning i...
# We first create labeled `Dataset` objects. train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)) # Then we shuffle, batch, and prefetch this dataset for performance. We # also apply random resized crops as an augmentation but only to the # tr...
examples/vision/ipynb/simsiam.ipynb
keras-team/keras-io
apache-2.0
Dissecting the program above The first line of the program above imports the read_raw_bdf function from the mne.io module. The second line of the program is the most complicated. A lot of stuff is going on there: <img src="images/function_call_explanation.png"> The read_raw_bdf function is called with two parameters. T...
%matplotlib notebook print('From now on, all graphics will send to your browser.')
eeg-erp/adept.ipynb
wmvanvliet/neuroscience_tutorials
bsd-2-clause
Now, it's your turn! Write the Python code that will visualize the raw EEG data we just loaded. Keep the following things in mind: 1. The function is called plot_raw and is kept inside the mne.viz module. Remember to import to function first! 2. Call the function with one parameter, namely the raw variable we created...
fig = plot_raw(raw, events=events)
eeg-erp/adept.ipynb
wmvanvliet/neuroscience_tutorials
bsd-2-clause
Frequency filtering, or, working with objects Throughout this exercise, we have created many variables, such as raw and events. Up to now, we've treated these as simple boxes that hold some data, or rather "objects" as they are called in Python. However, the box/object metaphor is not really a good one. Variables are m...
event_id = { 'Ace of spades': 1, 'Jack of clubs': 2, 'Queen of hearts': 3, 'King of diamonds': 4, '10 of spades': 5, '3 of clubs': 6, '10 of hearts': 7, '3 of diamonds': 8, 'King of spades': 9 }
eeg-erp/adept.ipynb
wmvanvliet/neuroscience_tutorials
bsd-2-clause
A dictionary is created by using curly braces { } and colons :. I've spread out the code over multiple lines to make things a little clearer. The way you create a dictionary is to say {this: means that} and you use commas if you want to put more than one thing in the dictionary. Finally, you should know that Python all...
event_id = { 'Ace of spades': 1, 'Jack of clubs': 2, 'Queen of hearts': 3, 'King of diamonds': 4, '10 of spades': 5, '3 of clubs': 6, '10 of hearts': 7, '3 of diamonds': 8, 'King of spades': 9, }
eeg-erp/adept.ipynb
wmvanvliet/neuroscience_tutorials
bsd-2-clause
Armed with our event_id dictionary, we can move on to creating epochs. For each event, let's cut a snippet of signal from 0.2 seconds before the moment the stimulus was presented, up until 0.5 seconds after it was presented. If we take the moment the stimulus was presented as time 0, we will cut epochs from -0.2 until ...
epochs.plot()
eeg-erp/adept.ipynb
wmvanvliet/neuroscience_tutorials
bsd-2-clause
Load in the permittivity distribution from an FDFD simulation
def reshape_arr(arr, Nx, Ny): return arr.reshape((Nx, Ny, 1)) eps_r = np.load('data/eps_r_splitter4.npy') eps_wg = np.load('data/eps_waveguide.npy') plt.imshow(eps_r.T, cmap='gist_earth_r') plt.show() Nx, Ny = eps_r.shape J_in = np.load('data/J_in.npy') J_outs = np.load('data/J_list.npy') J_wg = np.flipud(J_in.c...
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Initial setting up of parameters
nx, ny, nz = Nx//2, Ny//2, Nz//2 dL = 5e-8 pml = [20, 20, 0] F = fdtd(eps_r, dL=dL, npml=pml) F_wg = fdtd(eps_wg, dL=dL, npml=pml) # source parameters steps = 10000 t0 = 2000 sigma = 100 source_amp = 5 omega = 2 * np.pi * C_0 / 2e-6 # units of 1/sec omega_sim = omega * F.dt # unitless time gaussian = l...
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Compute the transmission (as a function of time) for a straight waveguide (to normalize later)
measured_wg = measure_fields(F_wg, source, steps, J_wg) plt.plot(1e15 * F.dt*np.arange(steps), gaussian(np.arange(steps))/gaussian(np.arange(steps)).max(), label='source (Jz)') plt.plot(1e15 * F.dt*np.arange(steps), measured_wg/measured_wg.max(), label='measured (Ez)') plt.xlabel('time (femtoseconds)') plt.ylabel('amp...
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Show the field plots at 10 time steps
aniplot(F_wg, source, steps, num_panels=10)
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Compute the power spectrum transmitted
plot_spectral_power(gaussian(np.arange(steps)), F.dt, f_top=3e16) gaussian(np.arange(steps)).shape
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Now for the measured fields
plot_spectral_power(measured_wg[:,0], F.dt, f_top=2e14)
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Now measure the transmission for the inverse designed splitter (at each of the four ports)
measured = measure_fields(F, source, steps, J_outs) ham = np.hamming(steps).reshape((steps,1)) # plt.plot(measured*ham**5) plot_spectral_power(measured*ham**100, dt=F.dt, f_top=4e16) plt.plot(1e15 * F.dt*np.arange(steps), gaussian(np.arange(steps))/gaussian(np.arange(steps)).max(), label='source (Jz)') plt.plot(1e15 ...
examples/simulate_splitter_fdtd.ipynb
fancompute/ceviche
mit
Just check that analytical solution coincides with the solution of ODE for the variance
def arccoth(x): return 0.5*np.log((1.+x)/(x-1.)) ############ parameters ############# th = 0.1 # Interaction parameter alpha = np.cos(th) beta = np.sin(th) gamma = 1. def gammaf(t): return 0.25+t/12+t*t/6 def f_gamma(t,*args): return (0.25+t/12+t*t/6)**(0.5) ################# Solution of the differenti...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
Test of different SME solvers
####################### Model ########################### N = 30 # number of Fock states Id = qeye(N) a = destroy(N) s = 0.5*((alpha+beta)*a + (alpha-beta)*a.dag()) x = (a + a.dag())/np.sqrt(2) H = Id c_op = [np.sqrt(gamma)*a] c_op_td = [[a,f_gamma]] sc_op = [s] e_op = [x, x*x] rho0 = fock_dm(N,0) ...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
Plotting the figure - Constant case
# Analetical solution not available: # Compute the evolution with the best solver and very small step size and use it as the reference sol = ssesolve(H, fock(N), tlist, [sc_op[0]+c_op[0]], e_op, nsubsteps=2000, method="homodyne",solver="taylor2.0") y_sse = sol.expect[1]-sol.expect[0]*sol.expect[0].conj() ntraj = 1 de...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
Deterministic part time dependent
def H_f(t,args): return 0.125+t/12+t*t/72 sol = ssesolve([H,[c_op[0].dag()*c_op[0]/2,H_f]], fock(N), tlist, sc_op, e_op, nsubsteps=2500, method="homodyne",solver="taylor2.0") y_sse_td = sol.expect[1]-sol.expect[0]*sol.expect[0].conj() plt.plot(y_sse_td) ntraj = 1 def run_sse_td(**kwargs): ...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
Both d1 and d2 time-dependent
def H_f(t,args): return 0.125+t/12+t*t/72 def H_bf(t,args): return 0.125+t/10+t*t/108 sc_op_td = [[sc_op[0],H_bf]] sol = ssesolve([H,[c_op[0].dag()*c_op[0]/2,H_f]], fock(N), tlist, sc_op_td, e_op, nsubsteps=2000, method="homodyne",solver="taylor15") y_sse_btd = sol.expect[1]-sol.expect[0...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
Multiple sc_ops, time-dependent
def H_f(t,args): return 0.125+t/12+t*t/36 def H_bf(t,args): return 0.125+t/10+t*t/108 sc_op_td = [[sc_op[0]],[sc_op[0],H_bf],[sc_op[0],H_f]] sol = ssesolve([H,[c_op[0].dag()*c_op[0]/2,H_f]], fock(N), tlist/3, sc_op_td, e_op, nsubsteps=2000, method="homodyne",solver="taylor15") y_sse_mul...
development/development-ssesolver-new-methods.ipynb
qutip/qutip-notebooks
lgpl-3.0
In the above example, x and y variables are pointing to same memory location and are two names to the same memory object, thus change in one will result in updating another value as long as they are not assigned to another memory location. With that in mind lets explore the new example
x = [10, 20, 30] y = x print(id(x), id(y)) x = 100 print(x, y) print(id(x), id(y)) x = ['a','b','c','d'] lst = [x, x] print(x, lst) x[2] = 'dd' print(x, lst)
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Copy with the Slice Operator Copying using slice can help us upto a certain level as shown in the below example
x = ['a','b','c','d'] y = x[:2] print(x, y) # Good :) print(id(x), id(y)) # but :( print(id(x[1]), id(y[1])) # thus x[1] = "33" print(x, y) # Good :) print(id(x), id(y)) # but :( print(id(x[1]), id(y[1]))
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
but may will fail, if we have heterogeneous data-types in the list as shown in below examples
x = [["a1", "b1", "c1"],'a','b','c','d'] y = x[:] print(x, y) # Good :) print(id(x), id(y)) # but :( print(id(x[0]), id(y[0])) # thus x[0][1] = "33" print(x, y) # Good :) print(id(x), id(y)) # but :( print(id(x[1]), id(y[1]))
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Now we now know that in Python Assignment statements do not copy objects, instead they create bindings between a target and an object and can't be used to create a copy of the existing object. Few More Examples for better understanding
magic_list = [1,2,3] print (magic_list) for i in magic_list: i = i+1 print (i) print (magic_list) magic_list = ["1","2","3"] print (magic_list) for i in magic_list: i = i+str(1) print (i) print (magic_list) lst1 = ['a','b',['ab','ba']] print(id(lst1)) lst2 = lst1 print(id(lst2)) print(lst1) pri...
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
<img src="files/shallowcopy1.png" width=300> <img src="files/shallowcopy2.png" width=300> <img src="files/shallowcopy3.png" width=470> For collections which are mutable or contain mutable items, copy is sometimes needed so one can change one copy without changing the other. Fortunately we have This module provides gen...
import copy class MyClass: def __init__(self, name): # contructor self.name = name def __cmp__(self, other): return cmp(self.name, other.name) a = MyClass('a') l = [ a ] dup = copy.copy(l) print ('l :', l) print ('dup:', dup) print ('dup is l:', (dup is l)) print ('dup == l:', (dup ...
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Deep Copy - copy.deepcopy(x) Return a deep copy of x.
dup = copy.deepcopy(l) print ('l :', l) print ('dup:', dup) print ('dup is l:', (dup is l)) print ('dup == l:', (dup == l)) print ('dup[0] is l[0]:', (dup[0] is l[0])) print ('dup[0] == l[0]:', (dup[0] == l[0])) # shallow copy import copy lst1 = ['a','b',['ab','ba']] lst2 = copy.copy(lst1) # print(id(lst1)) # prin...
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Difference between shallow and deep copying The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objec...
import copy class MyClass: def __init__(self, name): self.name = name def __cmp__(self, other): return cmp(self.name, other.name) def __copy__(self): print ('__copy__()') return MyClass(self.name) def __deepcopy__(self, memo): print ('__deepcopy__(%s)' % str(mem...
Section 1 - Core Python/Chapter 16 - Standard library/Reference, Shallow and deep copy.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Simple regression tree model Here we define a simple regression tree and then load it into SHAP as a custom model.
X,y = shap.datasets.boston() orig_model = sklearn.tree.DecisionTreeRegressor(max_depth=2) orig_model.fit(X, y) dot_data = sklearn.tree.export_graphviz(orig_model, out_file=None, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) graph # extract the arrays that define the tree ...
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Simple GBM classification model (with 2 trees) Here we define a simple regression tree and then load it into SHAP as a custom model.
X2,y2 = shap.datasets.adult() orig_model2 = sklearn.ensemble.GradientBoostingClassifier(n_estimators=2) orig_model2.fit(X2, y2)
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Pull the info of the first tree
tree_tmp = orig_model2.estimators_[0][0].tree_ # extract the arrays that define the tree children_left1 = tree_tmp.children_left children_right1 = tree_tmp.children_right children_default1 = children_right1.copy() # because sklearn does not use missing values features1 = tree_tmp.feature thresholds1 = tree_tmp.thresho...
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Pull the info of the second tree
tree_tmp = orig_model2.estimators_[1][0].tree_ # extract the arrays that define the tree children_left2 = tree_tmp.children_left children_right2 = tree_tmp.children_right children_default2 = children_right2.copy() # because sklearn does not use missing values features2 = tree_tmp.feature thresholds2 = tree_tmp.thresho...
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Create a list of SHAP Trees
# define a custom tree model tree_dicts = [ { "children_left": children_left1, "children_right": children_right1, "children_default": children_default1, "features": features1, "thresholds": thresholds1, "values": values1 * orig_model2.learning_rate, "node_samp...
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Explain the custom model
# build a background dataset for us to use based on people near a 0.95 cutoff vs = np.abs(orig_model2.predict_proba(X2)[:,1] - 0.95) inds = np.argsort(vs) inds = inds[:200] # build an explainer that explains the probability output of the model explainer2 = shap.TreeExplainer(model2, X2.iloc[inds,:], feature_dependence...
notebooks/tabular_examples/tree_based_models/Example of loading a custom tree model into SHAP.ipynb
slundberg/shap
mit
Think of data structures as like tools. You'll use them to store and retrieve values, to implement more complicated procedures, or algorithms. Data structures hold data. As a preview of how we might get that data in the first place, lets skip ahead and start using the Python library. Actually, lets start outside th...
import math hypotenuse = math.hypot(3, 4) # try your own numbers here! hypotenuse import binascii in_hex = binascii.hexlify(b"i like eating python as much as i like coding in python") in_hex # show ascii bytes in terms of the underlying hex codes
Welcome to Python.ipynb
4dsolutions/Python5
mit
However a lot of what makes Python so great are the modules and packages we might get from the Python repository (aka "Cheese shop"), more formally known as PyPI, the Python Package Index. What you don't find in the Standard Library, you may, in most cases, add to your Python path using pip3 install. If you've used ...
import pandas as pd url = "https://raw.githubusercontent.com/dariusk/corpora/master/data/animals/dinosaurs.json" df = pd.read_json(url) df.head() # just show the first five lines of a much taller table
Welcome to Python.ipynb
4dsolutions/Python5
mit
What happened just there? Pandas is all about Dataframe objects, which McKinney is hoping will be the basis of a more generalized object that works across computer languages, such as R, Python, and those using the Java Virtual Machine (JVM). We just created a Dataframe object by reading in data over the web, from a ...
df.drop('description', axis=1, inplace=True) # you won't be able to run this twice, why? df.head()
Welcome to Python.ipynb
4dsolutions/Python5
mit
Now that our dataframe is this simple, might we convert it to a native list, the data structure we started out with, with the square brackets? Sure we might.
dinos = df["dinosaurs"].tolist() # yep, it's that easy dinos[10:20] # this is called "slicing", getting items 10 to 19 len(dinos) # how many dinosaurs are we talking about actually?
Welcome to Python.ipynb
4dsolutions/Python5
mit
Wow. Yes, you could start using this list to harvest pictures, for example, maybe starting with the some Dinosaur Database.
dinos.sort() # I notice these are not alphabetized. We might sort in place. dinos[-10:] # now lets look from 10th from the end, to the end
Welcome to Python.ipynb
4dsolutions/Python5
mit
Slice notation is important because it's used with numpy arrays as well, in addition to pandas DataFrames and ordinary Python lists. Numpy arrays are like Python lists on steriods, meaning they have enhanced capabilities and multiple dimensions. Lets go back to an ordinary list and see test this feature more.
zoo[1:] # all but 0th element (addressing begins with 0) zoo[-1] # last item in the list
Welcome to Python.ipynb
4dsolutions/Python5
mit
Lets end this section with a quick look at a numpy array. Python lists may be "heterogenous" meaning their elements may be of many different types. Numpy needs its arrays to have all elements the same type, whatever type that may be (floats, ints, complex numbers are all typical).
import numpy as np # notice how we rename the module as we import it test_data = np.random.randint(1, 100, size=(5, 5)) # all integers, in a 5x5 matrix test_data test_data ** 2 # we can raise all these numbers to a 2nd power in one line!
Welcome to Python.ipynb
4dsolutions/Python5
mit
Making an interpolation from TRIGDAT Getting the data We can use GetGBMData to download the data
data = GetGBMData("080916009") data.set_destination("") # You can enter a folder here. If you want the CWD, you do not have to set data.get_trigdat()
examples/demo.ipynb
drJfunk/gbmgeometry
mit
By default, GetGBMData will grad data from all detectors. However, one can set a subset to retrieve different data types
data.select_detectors('n1','n2','b0') data.get_rsp_cspec()
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Interpolating First let's create an interpolating object for a given TRIGDAT file (POSHIST files are also readable)
interp = PositionInterpolator(trigdat="glg_trigdat_all_bn080916009_v02.fit") # In trigger times print "Quaternions" print interp.quaternion(0) print interp.quaternion(10) print print "SC XYZ" print interp.sc_pos(0) print interp.sc_pos(10)
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Single detector One can look at a single detector which knows about it's orientation in the Fermi SC coordinates
na = NaIA(interp.quaternion(0)) print na.get_center() print na.get_center().icrs #J2000 print na.get_center().galactic # Galactic print print "Changing in time" na.set_quaternion(interp.quaternion(100)) print na.get_center() print na.get_center().icrs #J2000 print na.get_center().galactic # Galactic
examples/demo.ipynb
drJfunk/gbmgeometry
mit
We can also go back into the GBMFrame
center_j2000 = na.get_center().icrs center_j2000 center_j2000.transform_to(GBMFrame(quaternion=interp.quaternion(100.)))
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Earth Centered Coordinates The sc_pos are Earth centered coordinates (in km for trigdat and m for poshist) and can also be passed. It is a good idea to specify the units!
na = NaIA(interp.quaternion(0),interp.sc_pos(0)*u.km) na.get_center()
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Working with the GBM class Ideally, we want to know about many detectors. The GBM class performs operations on all detectors for ease of use. It also has plotting capabilities
myGBM = GBM(interp.quaternion(0),sc_pos=interp.sc_pos(0)*u.km) myGBM.get_centers() [x.icrs for x in myGBM.get_centers()]
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Plotting We can look at the NaI view on the sky for a given FOV
myGBM.detector_plot(radius=60) myGBM.detector_plot(radius=10,projection='ortho',lon_0=40) myGBM.detector_plot(radius=10,projection='ortho',lon_0=0,lat_0=40,fignum=2)
examples/demo.ipynb
drJfunk/gbmgeometry
mit
In Fermi GBM coodinates We can also plot in Fermi GBM spacecraft coordinates
myGBM.detector_plot(radius=60,fermi_frame=True) myGBM.detector_plot(radius=10,projection='ortho',lon_0=20,fermi_frame=True) myGBM.detector_plot(radius=10,projection='ortho',lon_0=200,fermi_frame=True,fignum=3) myGBM.detector_plot(radius=10,projection='ortho',lon_0=0,lat_0=40,fignum=2,fermi_frame=True)
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Capturing points on the sky We can even see which detector's FOVs contain a point on the sky. We create a mock GRB SKycoord first.
grb = SkyCoord(ra=130.,dec=-45 ,frame='icrs', unit='deg') myGBM.detector_plot(radius=60, projection='moll', good=True, # only plot NaIs that see the GRB point=grb, lon_0=110,lat_0=-0) myGBM.detector_plot(radius=60, p...
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Looking at Earth occulted points on the sky We can plot the points occulted by the Earth (assuming points 68.5 degrees form the Earth anti-zenith are hidden)
myGBM.detector_plot(radius=10,show_earth=True,lon_0=90) myGBM.detector_plot(radius=10,lon_0=100,show_earth=True,projection='ortho') myGBM.detector_plot(radius=10,show_earth=True,lon_0=120,lat_0=-30,fermi_frame=True,projection='ortho')
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Source/Detector Separation We can even look at the separation angles for the detectors and the source
seps = myGBM.get_separation(grb) seps.sort("Separation") seps
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Examining Legal Detector Pairs To see which detectors are valid, can look at the legal pairs map
get_legal_pairs()
examples/demo.ipynb
drJfunk/gbmgeometry
mit
Introduction Linear regression, like any model regression methods, is made of two parts: * a regression model = a structure with parameters * a regression method to estimate which parameters minimize a residual between the points and the model When least squares methods are used, the residual is the sum of the squares ...
n = 100 x = np.random.normal(1, 0.5, n) noise = np.random.normal(0, 0.25, n) y = 0.75*x + 1 + noise fig, ax = plt.subplots(1, 1, figsize=(6,4)) ax.scatter(x, y) ax.set_xlim([0,2]) ax.set_ylim([0,3.1])
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
Simple linear regression considers the model function \begin{equation} y = \alpha + \beta x \end{equation} We can write the relation between $y_i$ and $x_i$ as: \begin{equation} \forall i, \quad y_i = \alpha + \beta x_i + \varepsilon_i \end{equation} where the $\varepsilon_i$, called residuals, are what's missing betwe...
def fit(x,y, with_constant=True): beta = np.cov(x,y)[0][1] / np.var(x) if with_constant: alpha = np.mean(y) - beta * np.mean(x) else: alpha = 0 r = np.cov(x,y)[0][1] / (np.std(x)*np.std(y)) mse = np.sum((y-alpha-beta*x)**2)/n return([beta,alpha,r,mse]) beta,alpha,r,mse = fi...
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
Expected value $$ \begin{array}{rcl} \mathbf{E}[\hat{\beta}] &=& \mathbf{E}\left[(X^TX)^{-1}X^T(X\beta + \varepsilon)\right]\ &=& \beta + \mathbf{E}\left[(X^TX)^{-1}X^T \varepsilon\right]\ &=& \beta + \mathbf{E}\left[\mathbf{E}\left[(X^TX)^{-1}X^T \varepsilon|X\right]\rig...
n = 200 x = np.random.normal(5, 2, n) noise = np.random.normal(0, 0.25, n) y = 0.75*x + 1 + noise fig, ax = plt.subplots(1, 1, figsize=(6,4)) ax.scatter(x, y) ax.set_xlim([0,10]) ax.set_ylim([0,10]) x_train = x[-40:] x_test = x[:-40] y_train = y[-40:] y_test = y[:-40]
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
We can fit a linear regression model on the training data:
beta,alpha,r,mse = fit(x,y)
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
And use it to predict $y$ on test data:
y_pred = alpha + beta*x_test def pred_plot(y_pred,y_test): fig, ax = plt.subplots(1, 2, figsize=(12,4)) ax[0].scatter(y_test, y_pred) ax[0].plot([0,10],[0,10],color='g') ax[0].set_xlim([0,10]) mse_pred = np.sum((y_test-y_pred)**2)/n ax[0].set_title('MSE: {:.2f}'.format(mse_pred), fontsize=14) ...
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
What could possibly go wrong? Assumptions for OLS $X$ has full column rank If we break this assumption, we can't even compute the OLS estimator. strict exogeneity: $\mathbf{E}\left[\varepsilon|X\right] = 0$ If we break this one, then the OLS estimator gets biased.
n = 100 x = np.random.normal(1, 0.5, n) noise = np.random.normal(0.25, 0.25, n) y = 0.75*x + noise beta,alpha,r,mse = fit(x,y, with_constant=False) fit_plot(x,y,noise,beta,alpha)
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
What would it mean for a prediction model?
n = 200 x = np.random.normal(5, 2, n) noise = np.random.normal(1, 0.25, n) y = 0.75*x + noise x_train = x[-40:] x_test = x[:-40] y_train = y[-40:] y_test = y[:-40] beta,alpha,r,mse = fit(x,y, with_constant=False) y_pred = beta*x_test pred_plot(y_pred,y_test)
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
But if we have a constant in our model, it is unbiased:
n = 100 x = np.random.normal(1, 0.5, n) noise = np.random.normal(0.25, 0.25, n) y = 0.75*x + noise beta,alpha,r,mse = fit(x,y, with_constant=True) fit_plot(x,y,noise,beta,alpha) n = 200 x = np.random.normal(5, 2, n) noise = np.random.normal(1, 0.25, n) y = 0.75*x + noise x_train = x[-40:] x_test = x[:-40] y_train =...
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
<span style='color: red;'>What happened?</span> Homoscedasticity: $\mathbf{E}\left[\varepsilon_i^2|X\right] = \sigma^2$ What happens if we break this assumption?
n = 100 x = np.linspace(0, 2, n) sigma2 = 0.1*x**2 noise = np.random.normal(0, np.sqrt(sigma2), n) y = 0.75*x + 1 + noise beta,alpha,r,mse = fit(x,y) fit_plot(x,y,noise,beta,alpha)
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
When this assumption is violated, we will turn to a weighted least squares estimator. No autocorrelation: $\mathbf{E}\left[\varepsilon_i \varepsilon_j|X\right] = 0 \textrm{ if } i \neq j$ What happens if we break this assumption?
n = 100 x = np.linspace(0, 2, n) sigma2 = 0.1*((6*x).astype(int) % 4) noise = np.random.normal(0, np.sqrt(sigma2), n) y = 0.75*x + 1 + noise beta,alpha,r,mse = fit(x,y) fit_plot(x,y,noise,beta,alpha)
machinelearning-theoryinpractice/01_Regression/01_LinearRegression.ipynb
gansanay/datascience-theoryinpractice
mit
Noiseless mixture of 2 Gaussians in 1D This is original problem considered by Pearson, and we will solve it as an optimization problem. K. Pearson. Contributions to the mathematical theory of evolution. Philosophical Transactions of the Royal Society of London. A, 185:71–110, 1894. We have two Gaussians with means $\xi...
xi,c = sp.symbols('xi,c') K = 2 # number of clusters xi0 = [1, -0.9] # true parameters c0 = [0.4, 0.6] pi0 = [0.4, 0.6] moment_exprs = [xi, xi**2 + c, xi**3 + 3*xi*c, xi**4 + 6*xi**2 * c + 3*c**2,\ xi**5 + 10*xi**3*c + 15*xi*c**2,\ xi**6 + 15*xi**4*c**1 + 45*xi**2*c**2 + 15*c**3 ,\ xi**7...
extra_examples.ipynb
sidaw/mompy
mit
Noisy mixture of Gaussian Now we draw a bunch of samples, and repeat the above experiment.
# draw some samples numsample = 1e5 np.random.seed(1) z = (np.random.rand(numsample) < pi0[0]).astype('int8') means = xi0[0]*z + xi0[1]*(1-z) stds = np.sqrt(c0[0]*z + c0[1]*(1-z)) Xs = means + stds * np.random.randn(numsample) import matplotlib.pyplot as plt %matplotlib inline plt.hist(Xs, 50); # construct the empiri...
extra_examples.ipynb
sidaw/mompy
mit
PSD max-cut This is the problem $\text{minimize} -x^T W x$ subject to constraints $x_i \in {-1,1}$ for a positive definite random matrix $W$.
size = 5 np.random.seed(1) xs = sp.symbols('x1:'+str(size+1)) Wh = np.random.randn(size,size) W = -Wh*Wh.T; gs = [x**2 >=1 for x in xs] + [x**2 <=1 for x in xs] fs = [ w * xs[ij[0]] * xs[ij[1]] for ij,w in np.ndenumerate(W) ] f = sum(fs) print_problem(f, gs) sol = mp.solvers.solve_GMP(f, gs, rounds = 3) mp.extractors...
extra_examples.ipynb
sidaw/mompy
mit
<table class="ee-notebook-buttons" align="left"><td> <a target="_blank" href="http://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a> </td...
from google.colab import auth auth.authenticate_user()
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Upgrade Earth Engine and Authenticate Update Earth Engine to ensure you have the latest version. Authenticate to Earth Engine the same way you did to the Colab notebook. Specifically, run the code to display a link to a permissions page. This gives you access to your Earth Engine account. This should be the same ac...
!pip install -U earthengine-api --no-deps import ee ee.Authenticate() ee.Initialize()
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Test the TensorFlow installation Import TensorFlow and check the version.
import tensorflow as tf print(tf.__version__)
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Define variables The training data are land cover labels with a single vector of Landsat 8 pixel values (BANDS) as predictors. See this example notebook for details on how to generate these training data.
# REPLACE WITH YOUR CLOUD PROJECT! PROJECT = 'your-project' # Cloud Storage bucket with training and testing datasets. DATA_BUCKET = 'ee-docs-demos' # Output bucket for trained models. You must be able to write into this bucket. OUTPUT_BUCKET = 'your-bucket' # This is a good region for hosting AI models. REGION = 'u...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Read data Check existence of the data files Check that you have permission to read the files in the output Cloud Storage bucket.
print('Found training file.' if tf.io.gfile.exists(TRAIN_FILE_PATH) else 'No training file found.') print('Found testing file.' if tf.io.gfile.exists(TEST_FILE_PATH) else 'No testing file found.')
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Read into a tf.data.Dataset Here we are going to read a file in Cloud Storage into a tf.data.Dataset. (these TensorFlow docs explain more about reading data into a tf.data.Dataset). Check that you can read examples from the file. The purpose here is to ensure that we can read from the file without an error. The act...
# Create a dataset from the TFRecord file in Cloud Storage. train_dataset = tf.data.TFRecordDataset([TRAIN_FILE_PATH, TEST_FILE_PATH], compression_type='GZIP') # Print the first record to check. print(iter(train_dataset).next())
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Parse the dataset Now we need to make a parsing function for the data in the TFRecord files. The data comes in flattened 2D arrays per record and we want to use the first part of the array for input to the model and the last element of the array as the class label. The parsing function reads data from a serialized Ex...
def parse_tfrecord(example_proto): """The parsing function. Read a serialized example into the structure defined by FEATURES_DICT. Args: example_proto: a serialized Example. Returns: A tuple of the predictors dictionary and the LABEL, cast to an `int32`. """ parsed_features = tf.io.parse_single_e...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Note that each record of the parsed dataset contains a tuple. The first element of the tuple is a dictionary with bands names for keys and tensors storing the pixel data for values. The second element of the tuple is tensor storing the class label. Adjust dimension and shape Turn the dictionary of {name: tensor,...} ...
# Inputs as a tuple. Make predictors 1x1xP and labels 1x1xN_CLASSES. def to_tuple(inputs, label): return (tf.expand_dims(tf.transpose(list(inputs.values())), 1), tf.expand_dims(tf.one_hot(indices=label, depth=N_CLASSES), 1)) input_dataset = parsed_dataset.map(to_tuple) # Check the first one. pprint(iter(i...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Model setup Make a densely-connected convolutional model, where the convolution occurs in a 1x1 kernel. This is exactly analogous to the model generated in this example notebook, but operates in a convolutional manner in a 1x1 kernel. This allows Earth Engine to apply the model spatially, as demonstrated below. Note ...
from tensorflow import keras # Define the layers in the model. Note the 1x1 kernels. model = tf.keras.models.Sequential([ tf.keras.layers.Input((None, None, len(BANDS),)), tf.keras.layers.Conv2D(64, (1,1), activation=tf.nn.relu), tf.keras.layers.Dropout(0.1), tf.keras.layers.Conv2D(N_CLASSES, (1,1), activatio...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Save the trained model Export the trained model to TensorFlow SavedModel format in your cloud storage bucket. The Cloud Platform storage browser is useful for checking on these saved models.
MODEL_DIR = 'gs://' + OUTPUT_BUCKET + '/demo_pixel_model' model.save(MODEL_DIR, save_format='tf')
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
EEification EEIfication prepares the model for hosting on Google AI Platform. Learn more about EEification from this doc. First, get (and SET) input and output names of the nodes. CHANGE THE OUTPUT NAME TO SOMETHING THAT MAKES SENSE FOR YOUR MODEL! Keep the input name of 'array', which is how you'll pass data into ...
from tensorflow.python.tools import saved_model_utils meta_graph_def = saved_model_utils.get_meta_graph_def(MODEL_DIR, 'serve') inputs = meta_graph_def.signature_def['serving_default'].inputs outputs = meta_graph_def.signature_def['serving_default'].outputs # Just get the first thing(s) from the serving signature def...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Run the EEifier The actual EEification is handled by the earthengine model prepare command. Note that you will need to set your Cloud Project prior to running the command.
# Put the EEified model next to the trained model directory. EEIFIED_DIR = 'gs://' + OUTPUT_BUCKET + '/eeified_pixel_model' # You need to set the project before using the model prepare command. !earthengine set_project {PROJECT} !earthengine model prepare --source_dir {MODEL_DIR} --dest_dir {EEIFIED_DIR} --input {inpu...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Deploy and host the EEified model on AI Platform Now there is another TensorFlow SavedModel stored in EEIFIED_DIR ready for hosting by AI Platform. Do that from the gcloud command line tool, installed in the Colab runtime by default. Be sure to specify a regional model with the REGION parameter. Note that the MODEL_...
MODEL_NAME = 'pixel_demo_model' VERSION_NAME = 'v0' !gcloud ai-platform models create {MODEL_NAME} \ --project {PROJECT} \ --region {REGION} !gcloud ai-platform versions create {VERSION_NAME} \ --project {PROJECT} \ --region {REGION} \ --model {MODEL_NAME} \ --origin {EEIFIED_DIR} \ --framework "TENSORF...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Connect to the hosted model from Earth Engine Generate the input imagery. This should be done in exactly the same way as the training data were generated. See this example notebook for details. Connect to the hosted model. Use the model to make predictions. Display the results. Note that it takes the model a couple...
# Cloud masking function. def maskL8sr(image): cloudShadowBitMask = ee.Number(2).pow(3).int() cloudsBitMask = ee.Number(2).pow(5).int() qa = image.select('pixel_qa') mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0).And( qa.bitwiseAnd(cloudsBitMask).eq(0)) return image.updateMask(mask).select(BANDS).divide(1...
python/examples/ipynb/Earth_Engine_TensorFlow_AI_Platform.ipynb
google/earthengine-api
apache-2.0
Cross-validation We have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.
num_folds = 5 k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100] X_train_folds = [] y_train_folds = [] ################################################################################ # TODO: # # Split up the training data into folds. After splittin...
assign/assignment1/knn.ipynb
zhmz90/CS231N
mit
Le traitement automatique des langues (ou Natural Language Processing) propose un ensemble de méthodes permettant (entre autres) : - d'extraire automatiquement les informations voulues de données textuelles brutes (comme apr exemple les noms propres) - indexer des documents et permettre une recherche par mot-clés (cf....
import httplib2 # pip install httplib2 import json # déjà installée, sinon : pip install json import apiclient.discovery # pip install google-api-python-client import bs4 # déjà ja installée, sinon : pip install bs4 import nltk # pip install nltk --> sous Windows, il faut aller à http://www.lfd.uci.edu/~gohlke/pytho...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Récupération de la clé d'API Google + google a arrêté Google +, l'API est désactivée également vers le 1er mars 2019, le code suivant ne fonctionne pas mais les données récupérées sont toujours disponibles : échantillon googleplus. Pour obtenir une clé d'API (google plus ou autre), il faut : avoir un compte gmail (si ...
#remplacer par VOTRE clé import os try: from pyquickhelper.loghelper import get_password API_KEY = get_password("gapi", "ensae_teaching_cs,key") except Exception as e: print(e)
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Connexion à l'API, et requête d'une personne ayant un compte Google + (avec activités publiques)
if False: # à remplacer par une autre API # Entrer le nom d'une personne ayant un compte google plus public Q = "Tim O'Reilly" # Se connecter à l'API (méthode Oauth2) service = apiclient.discovery.build('plus', 'v1', http=httplib2.Http(), developerKey=API_KEY) ...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
[ { "kind": "plus#person", "etag": "\"Sh4n9u6EtD24TM0RmWv7jTXojqc/tjedXFyeIkzudZzRey5EJb8iZIk\"", "objectType": "person", "id": "107033731246200681024", "displayName": "Tim O'Reilly", "url": "https://plus.google.com/107033731246200681024", "image": { "url": "https://lh4.googleusercontent.com/-J8nmMwIh...
if False: # à remplacer par une autre API # Parce que l'on travaille sur un Notebook il est possible d'afficher facilement les images correspondantes # l'identifiant unique d'avatar google plus et le nom from IPython.core.display import HTML html = [] for p in people_feed['items']: html +=...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Requete sur l'activité de la personne sélectionnée
if False: # à remplacer par une autre API USER_ID = '107033731246200681024' activity_feed = service.activities().list( userId=USER_ID, collection='public', maxResults='100' # Max allowed per API ).execute() res = json.dumps(activity_feed, indent=1) print(res if len(res) < 1000 el...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
{ "kind": "plus#activityFeed", "etag": "\"Sh4n9u6EtD24TM0RmWv7jTXojqc/UVhLnzZeFbRMD00k0VRD5tkC6es\"", "nextPageToken": "ADSJ_i32R0IpxThTClWgVQ71un8FkJDHG8Pl4hLCvWIbyb6T65r6coxSlWk1svDgsrzxTQ3JHFV1CGnbjFCSaY14sttcvnb1QgiHBgXRtn3A8GjJjin7", "title": "Google+ List of Activities for Collection PUBLIC", "updated": "201...
import json with open("ressources_googleplus/107033731246200681024.json", "r", encoding="utf-8") as f: activity_feed = json.load(f) res = json.dumps(activity_feed, indent=1) print(res if len(res) < 1000 else res[:1000] + "...")
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Nettoyage des données textuelles avec BS4
from bs4 import BeautifulSoup def cleanHtml(html): if html == "": return "" return BeautifulSoup(html, 'html.parser').get_text() try: print(activity_feed[0]['object']['content']) print("\n") print(cleanHtml(activity_feed[0]['object']['content'])) except Exception as e: print(e)
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Récupération des données et stockage Créer un dossier "ressources_googleplus" dans votre répertoire courant (%pwd pour le connaitre)
if False: # à remplacer par une autre API import json import apiclient.discovery MAX_RESULTS = 200 # limite fixée à 100 résultats par requete => on va itérer sur une boucle pour en avoir 200 activity_feed = service.activities().list( userId=USER_ID, collection='public', maxResults='1...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Analyse des données textuelles - TD-IDF, similarité cosine et n-grams Le calcul tf-idf (term frequency–inverse document frequency) permet de calculer un score de proximité entre un terme de recherche et un document (c'est ce que font les moteurs de recherche). La partie tf calcule une fonction croissante de la fréquenc...
import json with open("ressources_googleplus/107033731246200681024.json", "r", encoding="utf-8") as f: activity_results = json.load(f)
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit
Exemple sur un petit corpus de 3 documents
corpus = { 'a' : "Mr. Green killed Colonel Mustard in the study with the candlestick. \ Mr. Green is not a very nice fellow.", 'b' : "Professor Plum has a green plant in his study.", 'c' : "Miss Scarlett watered Professor Plum's green plant while he was away \ from his office last week." } terms = { 'a' : [ i.lowe...
_doc/notebooks/td2a_eco/td2a_TD5_Traitement_automatique_des_langues_en_Python.ipynb
sdpython/ensae_teaching_cs
mit