markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Cycling Output Container
l = CyclingOutputContainerLayoutManager() l.setPeriod(2345); # milliseconds l.setBorderDisplayed(False); o = OutputContainer() o.setLayoutManager(l) o.addItem(plot1, "Scatter with History") o.addItem(plot2, "Short Term") o.addItem(plot3, "Long Term") o
doc/python/OutputContainers.ipynb
jpallas/beakerx
apache-2.0
Define service account credentials
# INSERT YOUR SERVICE ACCOUNT HERE SERVICE_ACCOUNT='your-service-account@your-project.iam.gserviceaccount.com' KEY = 'private-key.json' !gcloud iam service-accounts keys create {KEY} --iam-account {SERVICE_ACCOUNT}
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
Create an authorized session to make HTTP requests
from google.auth.transport.requests import AuthorizedSession from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file(KEY) scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/cloud-platform']) session = AuthorizedSession(scoped_crede...
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
Get a list of images at a point Query for Sentinel-2 images at a specific location, in a specific time range and with estimated cloud cover less than 10%.
import urllib coords = [-122.085, 37.422] project = 'projects/earthengine-public' asset_id = 'COPERNICUS/S2' name = '{}/assets/{}'.format(project, asset_id) url = 'https://earthengine.googleapis.com/v1alpha/{}:listImages?{}'.format( name, urllib.parse.urlencode({ 'startTime': '2017-04-01T00:00:00.000Z', 'en...
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
Inspect an image Get the asset name from the previous output and request its metadata.
asset_id = 'COPERNICUS/S2/20170430T190351_20170430T190351_T10SEG' name = '{}/assets/{}'.format(project, asset_id) url = 'https://earthengine.googleapis.com/v1alpha/{}'.format(name) response = session.get(url) content = response.content asset = json.loads(content) print('Band Names: %s' % ','.join(band['id'] for band ...
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
Get pixels from one of the images
import numpy import io name = '{}/assets/{}'.format(project, asset_id) url = 'https://earthengine.googleapis.com/v1alpha/{}:getPixels'.format(name) body = json.dumps({ 'fileFormat': 'NPY', 'bandIds': ['B2', 'B3', 'B4', 'B8'], 'grid': { 'affineTransform': { 'scaleX': 10, 'sca...
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
Get a thumbnail of an image Note that name and asset are already defined from the request to get the asset metadata.
url = 'https://earthengine.googleapis.com/v1alpha/{}:getPixels'.format(name) body = json.dumps({ 'fileFormat': 'PNG', 'bandIds': ['B4', 'B3', 'B2'], 'region': asset['geometry'], 'grid': { 'dimensions': {'width': 256, 'height': 256}, }, 'visualizationOptions': { 'ranges': [{'min':...
python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb
google/earthengine-api
apache-2.0
3. Equations Markdown allows you to write mathematical equations using LaTeX that will be rendered using MathJax. The simplest way of including an equations is to wrap the LaTeX code in sets of double dollar signs, "$$": Planck Equation: $$ B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda...
%%latex \begin{aligned} B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1} \end{aligned}
lessons/jupyter/3_basic_demo.ipynb
ashiklom/studyGroup
apache-2.0
You can also use "line magics" to write LaTeX inline in Markdown cells: %latex \begin{aligned} B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1} \end{aligned} 4. Code You can, of course, also include code in the notebook as code is the default cell type. Let's create a functio...
import numpy as np def planck(wavelength, temp): """ Return the emitted radiation from a blackbody of a given temp and wavelength Args: wavelength (float): wavelength (m) temp (float): temperature of black body (Kelvin) Returns: float: spectral radiance (W / (sr m^3))...
lessons/jupyter/3_basic_demo.ipynb
ashiklom/studyGroup
apache-2.0
5. Visualization Not only can the notebooks display console style text outputs from the code, but it can also display and save very detaild plots. Below I use the Python plotting library, matplotlib, to reproduce the plot displayed in section 2.
# Import and alias to "plt" import matplotlib.pyplot as plt # Calculate wavelength = np.linspace(1e-7, 3e-6, 1000) temp = np.array([3000, 4000, 5000]) rad = np.zeros((wavelength.size, temp.size), dtype=np.float) for i, t in enumerate(temp): rad[:, i] = planck(wavelength, t) % matplotlib nbagg # Plot text_x = w...
lessons/jupyter/3_basic_demo.ipynb
ashiklom/studyGroup
apache-2.0
Load data Similar to previous exercises, we will load CIFAR-10 data from disk.
from utils.data_utils import get_CIFAR10_data cifar10_dir = 'datasets/cifar-10-batches-py' X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data(cifar10_dir, num_training=49000, num_validation=1000, num_test=1000) print (X_train.shape, y_train.shape, X_val.shape, y_val.shape, X_test.shape, y_test.shape)
test/features.ipynb
zklgame/CatEyeNets
mit
Extract Features For each image we will compute a Histogram of Oriented Gradients (HOG) as well as a color histogram using the hue channel in HSV color space. We form our final feature vector for each image by concatenating the HOG and color histogram feature vectors. Roughly speaking, HOG should capture the texture of...
from utils.features_utils import extract_features, hog_feature, color_histogram_hsv num_color_bins = 10 # Number of bins in the color histogram feature_fns = [hog_feature, lambda img: color_histogram_hsv(img, nbin=num_color_bins)] X_train_feats = extract_features(X_train, feature_fns, verbose=True) X_val_feats = extra...
test/features.ipynb
zklgame/CatEyeNets
mit
Train SVM on features Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels.
# Use the validation set to tune the learning rate and regularization strength # val accuracy should reach near 0.44 from classifiers.linear_classifier import LinearSVM learning_rates = [1e-4, 3e-4, 9e-4, 1e-3, 3e-3, 9e-3, 1e-2, 3e-2, 9e-2, 1e-1] regularization_strengths = [1e-1, 3e-1, 9e-1, 1, 3, 9] # results[(lear...
test/features.ipynb
zklgame/CatEyeNets
mit
Inline question 1: Describe the misclassification results that you see. Do they make sense? not obvious sense Neural Network on image features Earlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this...
print(X_train_feats.shape) from classifiers.neural_net import TwoLayerNet input_dim = X_train_feats.shape[1] hidden_dim = 500 num_classes = 10 learning_rates = [3e-1, 9e-1, 1] regularization_strengths = [3e-3, 4e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3, 1e-2] results = {} best_model = None best_val = -1 for lr in learnin...
test/features.ipynb
zklgame/CatEyeNets
mit
Note how tuples are returned. What if one iterable is longer than the other?
x = [1,2,3] y = [4,5,6,7,8] # Zip the lists together zip(x,y)
Zip.ipynb
jserenson/Python_Bootcamp
gpl-3.0
Note how the zip is defined by the shortest iterable length. Its generally advised not to zip unequal length iterables unless your very sure you only need partial tuple pairings. What happens if we try to zip together dictionaries?
d1 = {'a':1,'b':2} d2 = {'c':4,'d':5} zip(d1,d2)
Zip.ipynb
jserenson/Python_Bootcamp
gpl-3.0
The shop-talk around "ø up" and "ø down" involves scaling all linear dimensions of a shape, whereby volume actually increases or decreases by a factor of ø to the 3rd power. When you think "ø to the 3rd" sometimes imagine a tetrahedron of edges ø vis-a-vis a regular tetrahedron of edges 1 (D). Remember in Synergetics...
Blue = ø_down Red = rt2(ø ** 2+1) Orange = ø/Red for item in Blue, Orange, Red: print(item)
CuboidalE3.ipynb
4dsolutions/Python5
mit
For the purposes of Synergetics, our canonical bridge to the Platonics involves making the unit edge of the tetrahedron serve as our D, the Diameter of a unit-radius sphere (D = 2R). We often call this edge length 2, using R as our unit. The Icosahedron with edges D, for example, is our volume of ~18.51..., which Ji...
RT3_vol = 15 * rt2(2) print(RT3_vol)
CuboidalE3.ipynb
4dsolutions/Python5
mit
... and simply divide by 120.
E_vol = (RT3_vol * ø_down ** 3)/120 # a little more than 1/24, volume of T module print(E_vol)
CuboidalE3.ipynb
4dsolutions/Python5
mit
Another expression (in Python) for the E's volume is (rt2(2)/8) * (φ ** -3). For exercise, lets computer these expressions for E's and SuperRT's volume to a hundred places of decimal precision.
from decimal import Decimal, localcontext with localcontext() as cm: cm.prec = 300 # 100 decimal points of precision Phi = (Decimal(1) + Decimal(5).sqrt())/Decimal(2) RT3_vol = Decimal('15') * Decimal('2').sqrt() check_RT = Decimal('20') * (Decimal('9')/Decimal('8')).sqrt() E_volume = (Decimal('2')....
CuboidalE3.ipynb
4dsolutions/Python5
mit
How about we redo those calcs with gmpy2, why not?
import gmpy2 gmpy2.get_context().precision=300 Ø = (1 + gmpy2.root(5, 2))/2 vol_scale_factor = 1.5 rad_scale_factor = gmpy2.root(vol_scale_factor, 3) S3 = gmpy2.root(9/8, 2) SuperRT_vol = S3 * 20 Emod_RT_vol = SuperRT_vol * (1/Ø)**3 print("E3*120: {:80.78f}".format( SuperRT_vol)) print("E vol: {:80.78f}".format( Em...
CuboidalE3.ipynb
4dsolutions/Python5
mit
Here we need to do a bit of preprocessing and getting the images into a form where we can pass batches to the network. First off, we need to rescale the images to a range of -1 to 1, since the output of our generator is also in that range. We also have a set of test and validation images which could be used if we're tr...
def scale(x, feature_range=(-1, 1)): # scale to (0, 1) x = ((x - x.min())/(255 - x.min())) # scale to feature_range min, max = feature_range x = x * (max - min) + min return x class Dataset: def __init__(self, train, test, val_frac=0.5, shuffle=False, scale_func=None): split_id...
dcgan-svhn/DCGAN.ipynb
ktmud/deep-learning
mit
Gradient Descent Now we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of de...
from math import sqrt # recall that the magnitude/length of a vector [g[0], g[1], g[2]] is sqrt(g[0]^2 + g[1]^2 + g[2]^2) def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance): converged = False weights = np.array(initial_weights) # make sure it's a numpy array whi...
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Now compute your predictions using test_simple_feature_matrix and your weights from above.
predictions = predict_output(test_simple_feature_matrix, weights)
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Now that you have the predictions on test data, compute the RSS on the test data set. Save this value for comparison later. Recall that RSS is the sum of the squared errors (difference between prediction and output).
errors = predictions - test_output RSS = np.dot(errors, errors) print RSS
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Use the above parameters to estimate the model weights. Record these values for your quiz.
weights2 = regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance)
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Use your newly estimated weights and the predict_output function to compute the predictions on the TEST data. Don't forget to create a numpy array for these features from the test set first!
(test_feature_matrix, test_output) = get_numpy_data(test_data, model_features, my_output) predictions_test = predict_output(test_feature_matrix, weights2)
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 2 (round to nearest dollar)?
predictions_test[0]
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Quiz Question: Which estimate was closer to the true price for the 1st house on the Test data set, model 1 or model 2? Now use your predictions and the output to compute the RSS for model 2 on TEST data.
errors2 = predictions_test - test_output RSS2 = np.dot(errors2, errors2) print RSS2
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Quiz Question: Which model (1 or 2) has lowest RSS on all of the TEST data?
print RSS > RSS2
Linear_Regression_2_multiple_regression_assignment_2.ipynb
Benedicto/ML-Learning
gpl-3.0
Now we call DBSCAN function from sklearn, giving as input the list of g-vectors. The parameters eps and min_samples are be system/simulation dependent. As a rough rule-of-thumb, reasonable results are obtained by setting eps in the range 0.2-0.6. A pragmatic choice is to tune eps/min sample so as to obtain ~ 10 cluste...
import barnaba.cluster as cc # calculate clusters. Call the function dbscan and return list of labels and center indeces new_labels, center_idx = cc.dbscan(gvecs,list(qq),eps=0.45,min_samples=70) # write to pickle for later pickle.dump([new_labels,center_idx],open("cluster.p", "w"))
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
One possible way to visualize the cluster is to perform a principal component analysis and make a scatter plot.
# Do plots. Import matplotlib and seaborn import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") import matplotlib as mpl from matplotlib.collections import PatchCollection import matplotlib.patches as mpatches # calculate PCA v,w = cc.pca(gvecs,nevecs=3) # Define figure and set aspect fig, ax =...
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
As a last step, we analyze all the cluster individually. We save centroids to a PDB and cluster members to an xtc trajectory file. For each cluster, we calculate the ermsd and rmsd between centroid and cluster memebers.
import mdtraj as md import barnaba as bb print("# Write centroids to PDB files and cluster members to .xtc") top = "topology.pdb" traj = "trajectory.dcd" t = md.load(traj, top=top) dd1 = [] dd2 = [] ll = [] for i,k in enumerate(center_idx): t[qq[k]].save_pdb("cluster_%03d.test.pdb" % (i)) idxs = [ii for ii,kk ...
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
And now we box-plot the data.
# define figure f, (ax1, ax2) = plt.subplots(2, 1, sharex=True,figsize=(6.2,6.3)) # do the boxplot ax1 = sns.boxplot(data=dd1,color='0.5',ax=ax1,fliersize=2.5) ax2 = sns.boxplot(data=dd2,color='0.5',ax=ax2,fliersize=2.5) # write percentages for j in range(9): ax1.text(j,1.5,"%4.0f%s" % (ll[j],"%"),ha="center",va=...
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
Finally, we produce the dynamic secondary structures. We start from native
import os native = "2KOC" cmd1 = "barnaba ANNOTATE --trj %s.pdb --top %s.pdb -o %s" % (native,native,native) cmd2 = "barnaba SEC_STRUCTURE --ann %s.ANNOTATE.stacking.out %s.ANNOTATE.pairing.out -o %s" % (native,native,native) os.system(cmd1) os.system(cmd2)
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
Native <img src="2KOC.SEC_STRUCTURE_175steps.svg" width=300 height=300> And we do the same for the first three clusters:
top = "topology.pdb" for i in range(3): cmd1 = "barnaba ANNOTATE --trj cluster_00%d.traj.xtc --top %s -o c%d" % (i,top,i) cmd2 = "barnaba SEC_STRUCTURE \ --ann c%d.ANNOTATE.stacking.out c%d.ANNOTATE.pairing.out -o c%d" % (i,i,i) os.system(cmd1) os.system(cmd2) print cmd1 %ls *.svg
manuscript_figures/04_figure.ipynb
srnas/barnaba
gpl-3.0
LSTM + CTC Training on UW3 Let's start by downloading the dataset.
!test -f uw3-dew.h5 || (curl http://www.tmbdev.net/ocrdata-hdf5/uw3-dew.h5.gz > uw3-dew.h5.gz && gunzip uw3-dew.h5.gz)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
In HDF5 data files for CLSTM, row t represents the input vector at time step t. For MNIST, we scan through the original image left-to-right over time. Transcripts are stored in a separate ragged array of integers; each integer represents a class that can be mapped to a Unicode codepoint using the codec array. Class 0 i...
index = 5 h5 = h5py.File("uw3-dew.h5","r") imshow(h5["images"][index].reshape(*h5["images_dims"][index]).T) print h5["transcripts"][index]
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
All input vectors need to have the same length, so we just take that off the first vector in the dataset. The number of outputs can be taken from the codec.
ninput = int(h5["images_dims"][0][1]) noutput = len(h5["codec"]) print ninput,noutput
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Let's create a small bidirectional LSTM network.
net = clstm.make_net_init("bidi","ninput=%d:nhidden=50:noutput=%d"%(ninput,noutput)) net.setLearningRate(1e-4,0.9) print clstm.network_info(net) index = 22 xs = array(h5["images"][index].reshape(-1,48,1),'f') transcript = h5["transcripts"][index] imshow(xs.reshape(-1,48).T,cmap=cm.gray)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Forward propagation is quite simple: we take the input data and put it into the input sequence of the network, call the forward method, and take the result out of the output sequence. Note that all sequences (including xs) in clstm are of rank 3, with indexes giving the time step, the feature dimension, and the batch i...
net.inputs.aset(xs) net.forward() pred = net.outputs.array() imshow(pred.reshape(-1,noutput).T, interpolation='none')
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Target arrays are similar to the output array but may have a different number of timesteps. They are aligned with the output using CTC.
def mktarget(transcript,noutput): N = len(transcript) target = zeros((2*N+1,noutput),'f') assert 0 not in transcript target[0,0] = 1 for i,c in enumerate(transcript): target[2*i+1,c] = 1 target[2*i+2,0] = 1 return target target = mktarget(transcript,noutput) imshow(target.T)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
The CTC alignment now combines the network output with the ground truth.
seq = clstm.Sequence() seq.aset(target.reshape(-1,noutput,1)) aligned = clstm.Sequence() clstm.seq_ctc_align(aligned,net.outputs,seq) aligned = aligned.array() imshow(aligned.reshape(-1,noutput).T, interpolation='none')
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
If we repeat these steps over and over again, we eventually end up with a trained network.
for i in range(10000): index = int(rand()*len(h5["images"])) xs = array(h5["images"][index].reshape(-1,ninput,1),'f') transcript = h5["transcripts"][index] net.inputs.aset(xs) net.forward() pred = net.outputs.array() target = mktarget(transcript,noutput) seq = clstm.Sequence() seq.as...
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Let's write a simple decoder.
classes = argmax(pred,axis=1)[:,0] print classes[:100]
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
When we turn this back into a string using a really simple decoder, it doesn't come out too well, but we haven't trained that long anyway. In addition, this decoder is actually very simple
codes = classes[(classes!=0) & (roll(classes,1)==0)] chars = [chr(h5["codec"][c]) for c in codes] print "".join(chars)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Let's wrap this up as a function:
def decode1(pred): classes = argmax(pred,axis=1)[:,0] codes = classes[(classes!=0) & (roll(classes,1)==0)] chars = [chr(h5["codec"][c]) for c in codes] return "".join(chars) decode1(pred)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Here is another idea for decoding: look for minima in the posterior of the epsilon class and then return characters at those locations:
from scipy.ndimage import filters def decode2(pred,threshold=.5): eps = filters.gaussian_filter(pred[:,0,0],2,mode='nearest') loc = (roll(eps,-1)>eps) & (roll(eps,1)>eps) & (eps<threshold) classes = argmax(pred,axis=1)[:,0] codes = classes[loc] chars = [chr(h5["codec"][c]) for c in codes] return...
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
It's often useful to look at this in the log domain. We see that the classifier still has considerable uncertainty.
imshow(log10max(pred.reshape(-1,noutput)[:200].T))
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
The aligned output looks much cleaner.
imshow(aligned.reshape(-1,noutput)[:200].T) imshow(log10max(aligned.reshape(-1,noutput)[:200].T))
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
We can also decode the aligned outut directly.
print decode1(aligned) print decode2(aligned,0.9)
misc/lstm-uw3-py.ipynb
MichalBusta/clstm
apache-2.0
Model Creation An EBM model instance is created through
# model creation ebm_boltz = climlab.EBM(D=0.8, Tf=-2)
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
The model is set up by default with a linearized OLR parametrization (A+BT).
# print model states and suprocesses print(ebm_boltz)
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Create new subprocess The creation of a subprocess needs some information from the model, especially on which model state the subprocess should be defined on.
# create Boltzmann subprocess LW_boltz = climlab.radiation.Boltzmann(eps=0.65, tau=0.95, state=ebm_boltz.state, **ebm_boltz.param)
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Note that the model's whole state dictionary is given as input to the subprocess. In case only the temperature field ebm_boltz.state['Ts'] would be given, a new state dictionary would be created which holds the surface temperature with the key 'default'. That raises an error as the Boltzmann process refers the temperat...
# remove the old longwave subprocess ebm_boltz.remove_subprocess('LW') # add the new longwave subprocess ebm_boltz.add_subprocess('LW',LW_boltz)
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Note that the new OLR subprocess has to have the same key 'LW' as the old one, as the model refers to this key for radiation balance computation. That is why the old process has to be removed before the new one is added.
print(ebm_boltz)
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Model integration & Plotting To visualize the model state at beginning of integration we first integrate the model only for one timestep:
# integrate model for a single timestep ebm_boltz.step_forward()
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
The following code plots the current surface temperature, albedo and energy budget:
# creating plot figure fig = plt.figure(figsize=(15,10)) # Temperature plot ax1 = fig.add_subplot(221) ax1.plot(ebm_boltz.lat,ebm_boltz.Ts) ax1.set_xticks([-90,-60,-30,0,30,60,90]) ax1.set_xlim([-90,90]) ax1.set_title('Surface Temperature', fontsize=14) ax1.set_ylabel('(degC)', fontsize=12) ax1.grid() # Albedo plot ...
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
The two right sided plots show that the model is not in equilibrium. The net radiation reveals that the model currently gains heat and therefore warms up at the poles and loses heat at the equator. From the Energy plot we can see that latitudinal energy balance is not met. Now we integrate the model as long there are n...
# integrate model until solution converges ebm_boltz.integrate_converge()
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
We run the same code as above to plot the results:
# creating plot figure fig = plt.figure(figsize=(15,10)) # Temperature plot ax1 = fig.add_subplot(221) ax1.plot(ebm_boltz.lat,ebm_boltz.Ts) ax1.set_xticks([-90,-60,-30,0,30,60,90]) ax1.set_xlim([-90,90]) ax1.set_title('Surface Temperature', fontsize=14) ax1.set_ylabel('(degC)', fontsize=12) ax1.grid() # Albedo plot ...
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Now we can see that the latitudinal energy balance is statisfied. Each latitude gains as much heat (net radiation) as is transported out of it (diffusion transport). There is a net radiation surplus in the equator region, so more shortwave radiation is absorbed there than is emitted through longwave radiation. At the p...
print('The global mean temperature is %.2f deg C.' %climlab.global_mean(ebm_boltz.Ts)) print('The modeled ice edge is at %.2f deg latitude.' %np.max(ebm_boltz.icelat))
docs/source/courseware/Boltzmann_EBM.ipynb
cjcardinale/climlab
mit
Import Libs and configure Plotly
import IPython import plotly import plotly.offline as py import plotly.graph_objs as go import math import json import numpy as np import pandas as pd import re from scipy import spatial from scipy.spatial import distance from sklearn.cluster import KMeans from google.colab import drive from google.colab import auth fr...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
Mount Drive and read the Customer Match Insights CSVs
if (isUsingGDrive): drive.mount('/gdrive') df_1 = pd.read_csv(audience1_file_location,usecols=['Dimension','Audience','List distribution']) df_1['List distribution'] = round(df_1['List distribution']*audience1_size) df_2 = pd.read_csv(audience2_file_location,usecols=['Dimension','Audience','List distribution']) df_2[...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
Define TF-IDF Function
def scalarToSigmod(scalar):#0-1 input x = (scalar-.5)*8 return 1 / (1 + math.exp(-x)) def scalarToTanh(scalar): x = (scalar-.5)*6 return (math.tanh(x)+1)/2 def calc_tfidf(df, label_col_name, transformation='tanh'): transformer = TfidfTransformer(smooth_idf=True, norm='l1', use_idf=False) X = df.copy() ...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
Define GA API reporting functions
def process_report(report): data=[] columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) metricHeaders = [header['name'] for header in metricHeaders] df_headers = dimensionHeade...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
Run TF-IDF
df_1['Segmento'] = audience1_name df_2['Segmento'] = audience2_name if (audience3_enabled): df_3['Segmento'] = audience3_name df_list = [df_1,df_2,df_3] else: df_list = [df_1,df_2] df = pd.concat(df_list) df = df.loc[df['Dimension'] != 'City'] df = df.loc[df['Dimension'] != 'Country'] df['Audience'] = df['Dimensi...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
Plot the results
def plot_3d(cmi_df): configure_plotly_browser_state() y = list(cmi_df.drop(['COMPARED_USERLIST_FULL_NAME'],axis=1).columns) plot3d(cmi_df,'COMPARED_USERLIST_FULL_NAME',list(y)) def print_ordered_list(cmi_df): vecs = [[1,0,0], [0,1,0], [0,0,1]] segments = list(cmi_df.columns[1:]) cmi_df['vector'] = cmi_df[[...
pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb
google/data-pills
apache-2.0
comment data 가져오기 및 전처리
episode_comment = pd.read_csv("data/webnovel/episode_comments.csv", index_col=0, encoding="cp949") episode_comment["ID"] = episode_comment["object_id"].apply(lambda x: x.split("-")[0]) episode_comment["volume"] = episode_comment["object_id"].apply(lambda x: x.split("-")[1]).astype("int") episode_comment["writer_nickna...
Recommand System.ipynb
kmsmoo/Webnovel
mit
user dataframe 만들기
user_df = pd.concat([episode_comment, main_comment]).groupby(["user_id", "ID"], as_index=False).agg({"volume":np.size}) len(user_df) df = pd.read_csv("data/webnovel/main_df.csv", encoding="cp949", index_col=0) df["ID"] = df["ID"].astype("str") df = user_df.merge(df, on="ID")[["user_id", "genre", "volume"]].drop_dupl...
Recommand System.ipynb
kmsmoo/Webnovel
mit
user, book 인덱스 및 처리
user_size = len(user_df["user_id"].unique()) users = user_df["user_id"].unique() users_index = { user:index for index, user in enumerate(users) } book_df = pd.read_csv("data/webnovel/main_df.csv", encoding="cp949", index_col=0) book_size = len(book_df.ID.unique()) books = book_df.ID.unique() len(books) b...
Recommand System.ipynb
kmsmoo/Webnovel
mit
user * book matrix 만들기
empty_matrix = np.zeros((user_size, book_size)) for index, i in user_df.iterrows(): empty_matrix[i["user_index"], i["book_index"]] = i["volume"] user_book_matrix = pd.DataFrame(empty_matrix, columns=books) user_book_matrix.index = users user_book_matrix
Recommand System.ipynb
kmsmoo/Webnovel
mit
user * user cosine similarity 매트릭스 만들기 1 권 169464 명 1분 59초 2 권 57555 명 40.6초 3 권 31808 명 22.4초 4 권 20470 명 14.5초 5 권 14393 명 10.2초 6 권 10630 명 7.58초 7 권 8074 명 5.8초 8 권 6306 명 4.54초 9 권 4995 명 3.56초 10 권 4052 명 2.91초
for i in range(15): print(i+1, "권 이상 읽은 사람은",len(user_book_matrix[user_book_matrix.sum(axis=1)>i]), "명 입니다.") from scipy.spatial import distance def cosine_distance(a, b): return 1 - distance.cosine(a, b) def make_score(books): """ MAE 스코어 계산 """ user_books_matrix_two = user_book_matrix[user_b...
Recommand System.ipynb
kmsmoo/Webnovel
mit
Set your Processor Variables
# TODO(developer): Fill these variables with your values before running the sample PROJECT_ID = "YOUR_PROJECT_ID_HERE" LOCATION = "us" # Format is 'us' or 'eu' PROCESSOR_ID = "PROCESSOR_ID" # Create processor in Cloud Console DOCUMENT_PATH = "../resources/general/form.tiff" # Path of target document
general/form_parser.ipynb
GoogleCloudPlatform/documentai-notebooks
apache-2.0
The following code calls the synchronous API and parses the form fields and values.
def process_document_sample(): # Instantiates a client client_options = {"api_endpoint": "{}-documentai.googleapis.com".format(LOCATION)} client = documentai.DocumentProcessorServiceClient(client_options=client_options) # The full resource name of the processor, e.g.: # projects/project-id/loc...
general/form_parser.ipynb
GoogleCloudPlatform/documentai-notebooks
apache-2.0
Draw the bounding boxes We will now download the pdf above a jpg and use the spatial data to mark our values.
document_image = Image.open(DOCUMENT_PATH) draw = ImageDraw.Draw(document_image) for form_field in doc.pages[0].form_fields: # Draw the bounding box around the form_fields # First get the co-ords of the field name vertices = [] for vertex in form_field.field_name.bounding_poly.normalized_vertices: ...
general/form_parser.ipynb
GoogleCloudPlatform/documentai-notebooks
apache-2.0
Note que a imagem possui 174 linhas e 314 colunas, totalizando mais de 54 mil pixels. A representação do pixel é pelo tipo uint8, isto é, valores de 8 bits sem sinal, de 0 a 255. Note também que a impressão de todos os pixels é feita de forma especial. Se todos os 54 mil pixels tivessem que ser impressos, o resultado d...
plt.imshow(f,cmap='gray')
master/tutorial_img_ds.ipynb
robertoalotufo/ia898
mit
O segundo tipo de imagem que o adshow visualiza é a imagem com pixels do tipo booleano. Como ilustração, faremos uma operação comparando cada pixel da imagem cookies com o valor 128 gerando assim uma nova imagem f_bin onde cada pixel será True ou False dependendo do resultado da comparação. O adshow mapeia os pixels ve...
f_bin = f > 128 print('Tipo do pixel:', f_bin.dtype) plt.imshow(f_bin,cmap='gray') plt.colorbar() print(f_bin.min(), f_bin.max()) f_f = f_bin.astype(np.float) f_i = f_bin.astype(np.int) print(f_f.min(),f_f.max()) print(f_i.min(),f_i.max())
master/tutorial_img_ds.ipynb
robertoalotufo/ia898
mit
Por fim, além destes dois modos de exibição, o adshow pode também exibir imagens coloridas no formato RGB e tipo de pixel uint8. No NumPy a imagem RGB é representada como três images armazenadas na dimensão profundidade. Neste caso o array tem 3 dimensões e seu shape tem o formato (3,H,W).
f_cor = mpimg.imread('../data/boat.tif') print('Dimensões: ', f_cor.shape) print('Tipo do pixel:', f_cor.dtype) plt.imshow(f_cor) f_roi = f_cor[:2,:3,:] print(f_roi)
master/tutorial_img_ds.ipynb
robertoalotufo/ia898
mit
Neste curso, por motivos didáticos, o adshow somente visualiza estes 3 tipos de imagens. Qualquer outro tipo de imagem, seja de valores maiores que 255, negativos ou complexos, precisam ser explicitamente convertidos para os valores entre 0 e 255 ou True e False. Maiores informações no uso do adshow podem ser vistas em...
f= mpimg.imread('../data/gull.pgm') plt.imshow(f,cmap='gray') g = f[:7,:10] print('g=') print(g)
master/tutorial_img_ds.ipynb
robertoalotufo/ia898
mit
Read nino3 SSTA time series, Plot and Save the image In this noteboo, we will finish the following operations * read time series data produced bya previous notebook * have a quick plot * decorate plots * save image 1. Load basic libraries
%matplotlib inline import numpy as np import matplotlib.pyplot as plt # to generate plots
ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
2. Load nino3 SSTA series Please keep in mind that the nino3 SSTA series lies between 1970 and 1999 <br> Recall ex2
npzfile = np.load('data/ssta.nino3.30y.npz') npzfile.files ssta_series = npzfile['ssta_series'] ssta_series.shape
ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
3. Have a quick plot
plt.plot(ssta_series)
ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
4. Make it beautiful 4.1 Add Year ticks and grid lines, etc. More info can be found from https://matplotlib.org/users/pyplot_tutorial.html
fig = plt.figure(figsize=(15, 6)) ax = fig.add_subplot(111) plt.plot(ssta_series, 'g-', linewidth=2) plt.xlabel('Years') plt.ylabel('[$^oC$]') plt.title('nino3 SSTA 30-year (1970-1999)', fontsize=12) ax.set_xlim(0,361) ax.set_ylim(-3.5,3.5) ax.set_xticklabels(range(1970,2000,1*4)) ax.axhline(0, color='r') plt.grid(...
ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
4.2 More professional Just like the image from https://www.esrl.noaa.gov/psd/enso/mei/
fig = plt.figure(figsize=(15, 6)) ax = fig.add_subplot(111) xtime = np.linspace(1,360,360) ssta_series = ssta_series.reshape((360)) ax.plot(xtime, ssta_series, 'black', alpha=1.00, linewidth=2) ax.fill_between(xtime, 0., ssta_series, ssta_series> 0., color='red', alpha=.75) ax.fill_between(xtime, 0., ssta_serie...
ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb
royalosyin/Python-Practical-Application-on-Climate-Variability-Studies
mit
Load trajectories
from evo.tools import file_interface from evo.core import sync
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
Load KITTI files with entries of the first three rows of $\mathrm{SE}(3)$ matrices per line (no timestamps):
traj_ref = file_interface.read_kitti_poses_file("../test/data/KITTI_00_gt.txt") traj_est = file_interface.read_kitti_poses_file("../test/data/KITTI_00_ORB.txt")
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
...or load a ROS bagfile with geometry_msgs/PoseStamped, geometry_msgs/TransformStamped, geometry_msgs/PoseWithCovarianceStamped or nav_msgs/Odometry topics:
from rosbags.rosbag1 import Reader as Rosbag1Reader with Rosbag1Reader("../test/data/ROS_example.bag") as reader: traj_ref = file_interface.read_bag_trajectory(reader, "groundtruth") traj_est = file_interface.read_bag_trajectory(reader, "ORB-SLAM") traj_ref, traj_est = sync.associate_trajectories(traj_ref, traj...
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
... or load TUM files with 3D position and orientation quaternion per line ($x$ $y$ $z$ $q_x$ $q_y$ $q_z$ $q_w$):
traj_ref = file_interface.read_tum_trajectory_file("../test/data/fr2_desk_groundtruth.txt") traj_est = file_interface.read_tum_trajectory_file("../test/data/fr2_desk_ORB_kf_mono.txt") traj_ref, traj_est = sync.associate_trajectories(traj_ref, traj_est) print(traj_ref) print(traj_est)
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
APE Algorithm and API explanation: see here Interactive APE Demo Run the code below, configure the parameters in the GUI and press the update button. (uses the trajectories loaded above)
import evo.main_ape as main_ape import evo.common_ape_rpe as common count = 0 results = [] def callback_ape(pose_relation, align, correct_scale, plot_mode, show_plot): global results, count est_name="APE Test #{}".format(count) result = main_ape.ape(traj_ref, traj_est, est_name=est_name, ...
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
RPE Algorithm and API explanation: see here Interactive RPE Demo Run the code below, configure the parameters in the GUI and press the update button. (uses the trajectories loaded above, alignment only useful for visualization here)
import evo.main_rpe as main_rpe count = 0 results = [] def callback_rpe(pose_relation, delta, delta_unit, all_pairs, align, correct_scale, plot_mode, show_plot): global results, count est_name="RPE Test #{}".format(count) result = main_rpe.rpe(traj_ref, traj_est, est_name=est_name, ...
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
Do stuff with the result objects:
import pandas as pd from evo.tools import pandas_bridge df = pd.DataFrame() for result in results: df = pd.concat((df, pandas_bridge.result_to_df(result)), axis="columns") df df.loc["stats"]
notebooks/metrics_interactive.ipynb
MichaelGrupp/evo
gpl-3.0
Aiyagari Economy The economy can be represented by the following system of equations which we aim to solve numerically: $$ \begin{align} \rho v_1(a) &= \max_c \ u(c) + v_1'(a)(wz_1 + ra - c) + \lambda_1(v_2(a) - v_1(a))\ \rho v_2(a) &= \max_c \ u(c) + v_2'(a)(wz_2 + ra - c) + \lambda_2(v_1(a) - v_2(a))\ 0 &= - \frac{...
class Household(object): def __init__(self, r=0.03, # interest rate w=1, # wages rho=0.04, # discount factor a_min=1e-10, # minimum asset amount pi=[[-0.1, 0.1], [0.1, -0.1]], # poisson Jumps ...
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
For example, if interest rate is 0.05 and wage is 1, we can initialize a household, solve it decision problem, and find the stationary distribution by running
am=Household(r=0.05,w=1) am.solve_bellman() am.compute_stationary_distribution()
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
Once, a household object is created, the object can be reused to solve a different problem by changing parameters. For example, if the interest rate were to change to 0.03 and wage to 0.9, the new problem can be solved by setting parameters directly by
am.r=0.03 am.w=0.9
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
Given the household class, solving for the steady state becomes really simple. To find the equilibrium, we solve for the capital level that is consistent with household's decisions. Before solving for the actual steady state, we can visualize the capital demand and capital supply.
A = 2.5 N = 0.05 alpha = 0.33 def r_to_w(r): return A * (1 - alpha) * (alpha / (1 + r))**(alpha / (1 - alpha)) def rd(K): return A * alpha * (N / K)**(1 - alpha) def prices_to_capital_stock(am, r): """ Map prices to the induced level of capital stock. Parameters: ---------- am : Hous...
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
We make a grid of interest rate points, and plot the resulting capital.
num_points = 20 r_vals = np.linspace(0.0, 0.04, num_points) # Compute supply of capital k_vals = np.empty(num_points) for i, r in enumerate(r_vals): k_vals[i] = prices_to_capital_stock(am,r) # Plot supply and demand of capital fig, ax = plt.subplots(figsize=(11, 8)) ax.plot(k_vals, r_vals, lw=2, alpha=0.6, label=...
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
Finally, the equilibrium interest rate can be found by using the bisection method, and we can see the equilibrium distribution of assets.
# Set parameters for bisection method crit = 1e-6 r_min = 0.02 r_max = 0.04 r = 0.03 # Bisection loop for i in range(100): am.set_prices(r,r_to_w(r)) r_new = rd(am.compute_stationary_distribution()) if np.absolute(r_new-r)<crit: break elif r_new > r: r_min = r r = (r_max+r_min)/...
other/aiyagari_continuous_time.ipynb
supergis/git_notebook
gpl-3.0
Гистограмма выборки:
plt.hist(sample, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$')
1 Mathematics and Python/Lectures notebooks/12 sample distribution evaluation/sample_distribution_evaluation.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Попробуем задавать число карманов гистограммы вручную:
plt.hist(sample, bins=3, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$') plt.hist(sample, bins=40, normed=True) plt.ylabel('fraction of samples') plt.xlabel('$x$')
1 Mathematics and Python/Lectures notebooks/12 sample distribution evaluation/sample_distribution_evaluation.ipynb
maxis42/ML-DA-Coursera-Yandex-MIPT
mit
Explore the Data MNIST As you're aware, the MNIST dataset contains images of handwritten digits. You can view the first number of examples by changing show_n_images.
show_n_images = 25 """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline import os from glob import glob from matplotlib import pyplot mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L') pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gra...
udacity-dl/GAN/dlnd_face_generation.ipynb
arasdar/DL
unlicense