markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
With respect to receivers, the number of receivers is the same number of discrete points in the $x$ direction. So, we position these receivers along the direction $x$, at height $\bar{z}$ = 10m. In this way, our variables are chosen as:
nrec = nptx nxpos = np.linspace(x0,x1,nrec) nzpos = hzv
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
As we know, receivers are generated by the command Receiver. Thus, we use the parameters listed above and using the Receiver command, we create and position the receivers:
rec = Receiver(name='rec',grid=grid,npoint=nrec,time_range=time_range,staggered=NODE,dtype=np.float64) rec.coordinates.data[:, 0] = nxpos rec.coordinates.data[:, 1] = nzpos
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The displacement field u is a second order field in time and space, which uses points of type non-staggered. In this way, we construct the displacement field u with the command TimeFunction:
u = TimeFunction(name="u",grid=grid,time_order=2,space_order=2,staggered=NODE,dtype=np.float64)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The velocity field, the source term and receivers are defined as in the previous notebook:
vel0 = Function(name="vel0",grid=grid,space_order=2,staggered=NODE,dtype=np.float64) vel0.data[:,:] = v0[:,:] src_term = src.inject(field=u.forward,expr=src*dt**2*vel0**2) rec_term = rec.interpolate(expr=u)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The next step is to create the sequence of structures that reproduce the function $\zeta(x,z)$. Initially, we define the region $\Omega_{0}$, since the damping function uses the limits of that region. We previously defined the limits of the $\Omega$ region to be x0, x1, z0 and z1. Now, we define the limits of the regio...
x0pml = x0 + npmlx*hxv x1pml = x1 - npmlx*hxv z0pml = z0 z1pml = z1 - npmlz*hzv
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Having built the $\Omega$ limits, we then create a function, which we will call fdamp, which computationally represents the $\zeta(x,z)$ function. In the fdamp function, we highlight the following elements: quibar represents a constant choice for $\bar{\zeta_{1}}(x,z)$ and $\bar{\zeta_{2}}(x,z)$, satisfying $\bar{\zet...
def fdamp(x,z): quibar = 1.5*np.log(1.0/0.001)/(40) cte = 1./vmax a = np.where(x<=x0pml,(np.abs(x-x0pml)/lx),np.where(x>=x1pml,(np.abs(x-x1pml)/lx),0.)) b = np.where(z<=z0pml,(np.abs(z-z0pml)/lz),np.where(z>=z1pml,(np.abs(z-z1pml)/lz),0.)) adamp = quibar*(a-(1./(2.*np.pi))*np.sin(2.*np.pi*...
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Created the damping function, we define an array that loads the damping information in the entire domain $\Omega$. The objective is to assign this array to a Function and use it in the composition of the equations. To generate this array, we will use the function generatemdamp. In summary, this function generates a non...
def generatemdamp(): X0 = np.linspace(x0,x1,nptx) Z0 = np.linspace(z0,z1,nptz) X0grid,Z0grid = np.meshgrid(X0,Z0) D0 = np.zeros((nptx,nptz)) D0 = np.transpose(fdamp(X0grid,Z0grid)) return D0
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Built the function generatemdamp we will execute it using the command:
D0 = generatemdamp();
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Below we include a routine to plot the damping field.
def graph2damp(D): plot.figure() plot.figure(figsize=(16,8)) fscale = 1/10**(-3) fscale = 10**(-3) scale = np.amax(D) extent = [fscale*x0,fscale*x1, fscale*z1, fscale*z0] fig = plot.imshow(np.transpose(D), vmin=0.,vmax=scale, cmap=cm.seismic, extent=extent) plot.gca().xaxis.set_maj...
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Below we include the plot of damping field.
# NBVAL_IGNORE_OUTPUT graph2damp(D0)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Like the velocity function $c(x,z)$, the damping function $\zeta(x,z)$ is constant in time. Therefore, the damping function will be a second-order Function in space, which uses points of the non-staggered type and which we will evaluate with the D0 array. The symbolic name damp will be assigned to this field.
damp = Function(name="damp",grid=grid,space_order=2,staggered=NODE,dtype=np.float64) damp.data[:,:] = D0
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The expressions for the acoustic equation with damping can be separeted between the white and blue regions. Translating these expressions in terms of an eq that can be inserted in a Devito code, we have that in the white region the equation takes the form: eq1 = u.dt2 - vel0 * vel0 * u.laplace, and in the blue region...
pde0 = Eq(u.dt2 - u.laplace*vel0**2) pde1 = Eq(u.dt2 - u.laplace*vel0**2 + vel0**2*damp*u.dtc)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
As we did on the notebook <a href="introduction.ipynb">Introduction to Acoustic Problem</a>, we define the stencils for each of the pdes that we created previously. In the case of pde0 it is defined only in the white region, which is represented by subdomain d0. Then, we define the stencil0 which resolves pde0 in d0 an...
stencil0 = Eq(u.forward, solve(pde0,u.forward),subdomain = grid.subdomains['d0'])
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The pde1 will be applied in the blue region, the union of the subdomains d1, d2 and d3. In this way, we create a vector called subds that comprises these three subdomains, and we are ready to set the corresponding stencil
subds = ['d1','d2','d3'] stencil1 = [Eq(u.forward, solve(pde1,u.forward),subdomain = grid.subdomains[subds[i]]) for i in range(0,len(subds))]
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
The boundary conditions of the problem are kept the same as the notebook <a href="1_introduction.ipynb">Introduction to Acoustic Problem</a>. So these are placed in the term bc and have the following form:
bc = [Eq(u[t+1,0,z],0.),Eq(u[t+1,nptx-1,z],0.),Eq(u[t+1,x,nptz-1],0.),Eq(u[t+1,x,0],u[t+1,x,1])]
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
We then define the operator (op) that join the acoustic equation, source term, boundary conditions and receivers. The acoustic wave equation in the d0 region: [stencil0]; The acoustic wave equation in the d1, d2 and d3 region: [stencil1]; Source term: src_term; Boundary conditions: bc; Receivers: rec...
# NBVAL_IGNORE_OUTPUT op = Operator([stencil0,stencil1] + src_term + bc + rec_term,subs=grid.spacing_map)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
We reset the field u:
u.data[:] = 0.
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
We assign in op the number of time steps it must execute and the size of the time step in the local variables time and dt, respectively.
# NBVAL_IGNORE_OUTPUT op(time=nt,dt=dt0)
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
To view the result of the displacement field at the end time, we use the graph2d routine given by:
def graph2d(U): plot.figure() plot.figure(figsize=(16,8)) fscale = 1/10**(3) scale = np.amax(U[npmlx:-npmlx,0:-npmlz])/10. extent = [fscale*x0pml,fscale*x1pml,fscale*z1pml,fscale*z0pml] fig = plot.imshow(np.transpose(U[npmlx:-npmlx,0:-npmlz]),vmin=-scale, vmax=scale, cmap=cm.seismic, exten...
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Note that the solution obtained here has a reduction in noise when compared to the results displayed on the notebook <a href="01_introduction.ipynb">Introduction to Acoustic Problem</a>. To plot the result of the Receivers we use the graph2drec routine.
def graph2drec(rec): plot.figure() plot.figure(figsize=(16,8)) fscaled = 1/10**(3) fscalet = 1/10**(3) scale = np.amax(rec[:,npmlx:-npmlx])/10. extent = [fscaled*x0pml,fscaled*x1pml, fscalet*tn, fscalet*t0] fig = plot.imshow(rec[:,npmlx:-npmlx], vmin=-scale...
examples/seismic/abc_methods/02_damping.ipynb
opesci/devito
mit
Finetuning and Training
%cd $DATA_HOME_DIR #Set path to sample/ path if desired path = DATA_HOME_DIR + '/' #'/sample/' test_path = DATA_HOME_DIR + '/test1/' #We use all the test data # FloydHub # data needs to be output under /output # if results_path cannot be created, execute mkdir directly in the terminal results_path = OUTPUT_HOME_DIR +...
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
Use a pretrained VGG model with our Vgg16 class
# As large as you can, but no larger than 64 is recommended. #batch_size = 8 batch_size = 64 no_of_epochs=3
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
The original pre-trained Vgg16 class classifies images into one of the 1000 categories. This number of categories depends on the dataset which Vgg16 was trained with. (http://image-net.org/challenges/LSVRC/2014/browse-synsets) In order to classify images into the categories which we prepare (2 categories of dogs/cats, ...
vgg = Vgg16() # Grab a few images at a time for training and validation. batches = vgg.get_batches(train_path, batch_size=batch_size) val_batches = vgg.get_batches(valid_path, batch_size=batch_size*2) # Finetune: note that the vgg model is compiled inside the finetune method. vgg.finetune(batches) # Fit: note that w...
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
Generate Predictions
# OUTPUT_HOME_DIR, not DATA_HOME_DIR due to FloydHub restriction %cd $OUTPUT_HOME_DIR %mkdir -p test1/unknown %cd $OUTPUT_HOME_DIR/test1 %cp $test_path/*.jpg unknown/ # rewrite test_path test_path = OUTPUT_HOME_DIR + '/test1/' #We use all the test data batches, preds = vgg.test(test_path, batch_size = batch_size*2) ...
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
Validate Predictions Calculate predictions on validation set, so we can find correct and incorrect examples:
vgg.model.load_weights(results_path+latest_weights_filename) val_batches, probs = vgg.test(valid_path, batch_size = batch_size) filenames = val_batches.filenames expected_labels = val_batches.classes #0 or 1 #Round our predictions to 0/1 to generate labels our_predictions = probs[:,0] our_labels = np.round(1-our_pre...
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
(TODO) look at data to improve model confusion matrix
from sklearn.metrics import confusion_matrix cm = confusion_matrix(expected_labels, our_labels) plot_confusion_matrix(cm, val_batches.class_indices)
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
Submit Predictions to Kaggle! This section also depends on which dataset you use (and which Kaggle competition you are participating)
#Load our test predictions from file preds = load_array(results_path + 'test_preds.dat') filenames = load_array(results_path + 'filenames.dat') #Grab the dog prediction column isdog = preds[:,1] print("Raw Predictions: " + str(isdog[:5])) print("Mid Predictions: " + str(isdog[(isdog < .6) & (isdog > .4)])) print("Edge...
fast.ai/lesson1/dogscats_run.ipynb
kazuhirokomoda/deep_learning
mit
Steps to use the TF Experiment APIs Define dataset metadata Define data input function to read the data from csv files + feature processing Create TF feature columns based on metadata + extended feature columns Define an estimator (DNNRegressor) creation function with the required feature columns & parameters Define a...
MODEL_NAME = 'reg-model-03' TRAIN_DATA_FILES_PATTERN = 'data/train-*.csv' VALID_DATA_FILES_PATTERN = 'data/valid-*.csv' TEST_DATA_FILES_PATTERN = 'data/test-*.csv' RESUME_TRAINING = False PROCESS_FEATURES = True EXTEND_FEATURE_COLUMNS = True MULTI_THREADING = True
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
1. Define Dataset Metadata CSV file header and defaults Numeric and categorical feature names Target feature name Unused columns
HEADER = ['key','x','y','alpha','beta','target'] HEADER_DEFAULTS = [[0], [0.0], [0.0], ['NA'], ['NA'], [0.0]] NUMERIC_FEATURE_NAMES = ['x', 'y'] CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY = {'alpha':['ax01', 'ax02'], 'beta':['bx01', 'bx02']} CATEGORICAL_FEATURE_NAMES = list(CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY....
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
2. Define Data Input Function Input csv files name pattern Use TF Dataset APIs to read and process the data Parse CSV lines to feature tensors Apply feature processing Return (features, target) tensors a. parsing and preprocessing logic
def parse_csv_row(csv_row): columns = tf.decode_csv(csv_row, record_defaults=HEADER_DEFAULTS) features = dict(zip(HEADER, columns)) for column in UNUSED_FEATURE_NAMES: features.pop(column) target = features.pop(TARGET_NAME) return features, target def process_features(featur...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
b. data pipeline input function
def csv_input_fn(files_name_pattern, mode=tf.estimator.ModeKeys.EVAL, skip_header_lines=0, num_epochs=None, batch_size=200): shuffle = True if mode == tf.estimator.ModeKeys.TRAIN else False print("") print("* data input_fn:") print("=======...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
3. Define Feature Columns The input numeric columns are assumed to be normalized (or have the same scale). Otherise, a normlizer_fn, along with the normlisation params (mean, stdv) should be passed to tf.feature_column.numeric_column() constructor.
def extend_feature_columns(feature_columns): # crossing, bucketizing, and embedding can be applied here feature_columns['alpha_X_beta'] = tf.feature_column.crossed_column( [feature_columns['alpha'], feature_columns['beta']], 4) return feature_columns def get_feature_columns(): ...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
4. Define an Estimator Creation Function Get dense (numeric) columns from the feature columns Convert categorical columns to indicator columns Create Instantiate a DNNRegressor estimator given dense + indicator feature columns + params
def create_estimator(run_config, hparams): feature_columns = list(get_feature_columns().values()) dense_columns = list( filter(lambda column: isinstance(column, feature_column._NumericColumn), feature_columns ) ) categorical_columns = list( filter(lambda...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
5. Define Serving Funcion
def csv_serving_input_fn(): SERVING_HEADER = ['x','y','alpha','beta'] SERVING_HEADER_DEFAULTS = [[0.0], [0.0], ['NA'], ['NA']] rows_string_tensor = tf.placeholder(dtype=tf.string, shape=[None], name='csv_rows') ...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
6. Run Experiment a. Define Experiment Function
def generate_experiment_fn(**experiment_args): def _experiment_fn(run_config, hparams): train_input_fn = lambda: csv_input_fn( files_name_pattern=TRAIN_DATA_FILES_PATTERN, mode = tf.contrib.learn.ModeKeys.TRAIN, num_epochs=hparams.num_epochs, batch_size=hpar...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
b. Set HParam and RunConfig
TRAIN_SIZE = 12000 NUM_EPOCHS = 1000 BATCH_SIZE = 500 NUM_EVAL = 10 CHECKPOINT_STEPS = int((TRAIN_SIZE/BATCH_SIZE) * (NUM_EPOCHS/NUM_EVAL)) hparams = tf.contrib.training.HParams( num_epochs = NUM_EPOCHS, batch_size = BATCH_SIZE, hidden_units=[8, 4], dropout_prob = 0.0) model_dir = 'trained_models/{}...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
c. Run Experiment via learn_runner
if not RESUME_TRAINING: print("Removing previous artifacts...") shutil.rmtree(model_dir, ignore_errors=True) else: print("Resuming training...") tf.logging.set_verbosity(tf.logging.INFO) time_start = datetime.utcnow() print("Experiment started at {}".format(time_start.strftime("%H:%M:%S"))) print(".......
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
7. Evaluate the Model
TRAIN_SIZE = 12000 VALID_SIZE = 3000 TEST_SIZE = 5000 train_input_fn = lambda: csv_input_fn(files_name_pattern= TRAIN_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.EVAL, batch_size= TRAIN_SIZE) valid_input_fn = lambda: csv_input_fn(files_n...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
8. Prediction
import itertools predict_input_fn = lambda: csv_input_fn(files_name_pattern=TEST_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.PREDICT, batch_size= 5) predictions = estimator.predict(input_fn=predict_input_fn) values = list(map(lambda item...
01_Regression/04.0 - TF Regression Model - Dataset Input.ipynb
GoogleCloudPlatform/tf-estimator-tutorials
apache-2.0
Pure Sinusoid Sliding Window In this first experiment, you will alter the extent of the sliding window of a pure sinusoid and examine how the geometry of a 2-D embedding changes. First, setup and plot a pure sinusoid in NumPy:
# Step 1: Setup the signal T = 40 # The period in number of samples NPeriods = 4 # How many periods to go through N = T*NPeriods #The total number of samples t = np.linspace(0, 2*np.pi*NPeriods, N+1)[:N] # Sampling indices in time x = np.cos(t) # The final signal plt.plot(x);
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Sliding Window Code The code below performs a sliding window embedding on a 1D signal. The parameters are as follows: | | | |:-:|---| |$x$ | The 1-D signal (numpy array) | |dim|The dimension of the embedding| |$\tau$ | The skip between samples in a given window | |$dT$ | The distance to slide from one window ...
def getSlidingWindow(x, dim, Tau, dT): """ Return a sliding window of a time series, using arbitrary sampling. Use linear interpolation to fill in values in windows not on the original grid Parameters ---------- x: ndarray(N) The original time series dim: int Dimension o...
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Sliding Window Result We will now perform a sliding window embedding with various choices of parameters. Principal component analysis will be performed to project the result down to 2D for visualization. The first two eigenvalues computed by PCA will be printed. The closer these eigenvalues are to each other, the r...
def on_value_change(change): execute_computation1() dimslider = widgets.IntSlider(min=1,max=40,value=20,description='Dimension:',continuous_update=False) dimslider.observe(on_value_change, names='value') Tauslider = widgets.FloatSlider(min=0.1,max=5,step=0.1,value=1,description=r'\(\tau :\)' ,continuous_updat...
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Questions For fixed $\tau$: What does varying the dimension do to the extent (the length of the window)? what dimensions give eigenvalues nearest each other? (Note: dimensions! Plural!) Explain why this is the case. Explain how you might use this information to deduce the period of a signal. <br><br> What does varying...
noise = 0.05*np.random.randn(400) def on_value_change(change): execute_computation2() dimslider = widgets.IntSlider(min=1,max=40,value=20,description='Dimension:',continuous_update=False) dimslider.observe(on_value_change, names='value') Tauslider = widgets.FloatSlider(min=0.1,max=5,step=0.1,value=1,descript...
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Questions Notice how changing the window extent doesn't have the same impact as it did in the periodic example above. Why might this be? <br><br> Why is the second eigenvalue always tiny? Multiple Sines Sliding Window We will now go back to periodic signals, but this time we will increase the complexity by adding tw...
def on_value_change(change): execute_computation3() embeddingdimbox = widgets.Dropdown(options=[2, 3],value=3,description='Embedding Dimension:',disabled=False) embeddingdimbox.observe(on_value_change,names='value') secondfreq = widgets.Dropdown(options=[2, 3, np.pi],value=3,description='Second Frequency:',disabl...
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Questions Comment on the relationship between the eigenvalues and the extent (width) of the window. <br><br> When are the eigenvalues near each other? When are they not? <br><br> Comment on the change in geometry when the second sinusoid is incommensurate to the first. Specifically, comment on the intrinsic dimension ...
T = 20 #The period of the first sine in number of samples NPeriods = 10 #How many periods to go through, relative to the faster sinusoid N = T*NPeriods*3 #The total number of samples t = np.arange(N) #Time indices #Make the harmonic signal cos(t) + cos(3t) xH = np.cos(2*np.pi*(1.0/T)*t) + np.cos(2*np.pi*(1.0/(3*T)*t))...
SlidingWindow1-Basics.ipynb
ctralie/TUMTopoTimeSeries2016
apache-2.0
Render with nupic.frameworks.viz.NetworkVisualizer, which takes as input any nupic.engine.Network instance:
from nupic.frameworks.viz import NetworkVisualizer # Initialize Network Visualizer viz = NetworkVisualizer(network) # Render to dot (stdout) viz.render()
src/nupic/frameworks/viz/examples/Demo.ipynb
pulinagrawal/nupic
agpl-3.0
That's interesting, but not necessarily useful if you don't understand dot. Let's capture that output and do something else:
from nupic.frameworks.viz import DotRenderer from io import StringIO outp = StringIO() viz.render(renderer=lambda: DotRenderer(outp))
src/nupic/frameworks/viz/examples/Demo.ipynb
pulinagrawal/nupic
agpl-3.0
outp now contains the rendered output, render to an image with graphviz:
# Render dot to image from graphviz import Source from IPython.display import Image Image(Source(outp.getvalue()).pipe("png"))
src/nupic/frameworks/viz/examples/Demo.ipynb
pulinagrawal/nupic
agpl-3.0
In the example above, each three-columned rectangle is a discrete region, the user-defined name for which is in the middle column. The left-hand and right-hand columns are respective inputs and outputs, the names for which, e.g. "bottumUpIn" and "bottomUpOut", are specific to the region type. The arrows indicate link...
from nupic.frameworks.opf.modelfactory import ModelFactory # Note: parameters copied from examples/opf/clients/hotgym/simple/model_params.py model = ModelFactory.create({'aggregationInfo': {'hours': 1, 'microseconds': 0, 'seconds': 0, 'fields': [('consumption', 'sum')], 'weeks': 0, 'months': 0, 'minutes': 0, 'days': 0...
src/nupic/frameworks/viz/examples/Demo.ipynb
pulinagrawal/nupic
agpl-3.0
Same deal as before, create a NetworkVisualizer instance, render to a buffer, then to an image, and finally display it inline.
# New network, new NetworkVisualizer instance viz = NetworkVisualizer(model._netInfo.net) # Render to Dot output to buffer outp = StringIO() viz.render(renderer=lambda: DotRenderer(outp)) # Render Dot to image, display inline Image(Source(outp.getvalue()).pipe("png"))
src/nupic/frameworks/viz/examples/Demo.ipynb
pulinagrawal/nupic
agpl-3.0
The constants module Before going further in explaining Maybrain's functionalities, it is important to briefly refer the constants module. This module has some constants which can be used elsewhere, rather than writing the values by hand everywhere being prone to typos. In further notebooks you will see this module be...
from maybrain import constants as ct # Printing some of the constants print(ct.WEIGHT) print(ct.ANAT_LABEL)
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
The resources package Maybrain also have another package that can be useful for different things. In its essence, it is just a package with access to files like matrices, properties, etc. When importing this package, you will have access to different variables in the path for the file in your system. Farther in the doc...
from maybrain import resources as rr
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Importing an Adjacency Matrix Firstly, create a Brain object:
a = mbt.Brain() print("Nodes: ", a.G.nodes()) print("Edges: ", a.G.edges()) print("Adjacency matrix: ", a.adjMat)
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
This creates a brain object, where a graph (from the package NetworkX) is stored as a.G, initially empty. Then import the adjacency matrix. The import_adj_file() function imports the adjacency matrix to form the nodes of your graph, but does not create any edges (connections), as you can check from the following outpu...
a.import_adj_file(rr.DUMMY_ADJ_FILE_500) print("Number of nodes:\n", a.G.number_of_nodes()) print("First 5 nodes (notice labelling starting with 0):\n", list(a.G.nodes())[0:5]) print("Edges:\n", a.G.edges()) print("Size of Adjacency matrix:\n", a.adjMat.shape)
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
If you wish to create a fully connected graph with all the available values in the adjacency matrix, it is necessary to threshold it, which is explained in the next section. Thresholding There are a few ways to apply a threshold, either using an absolute threshold across the whole graph to preserve a specified number o...
# Bring everything from the adjacency matrix to a.G a.apply_threshold() print("Number of edges (notice it corresponds to the upper half edges of adjacency matrix):\n", a.G.number_of_edges()) print("Size of Adjacency matrix after 1st threshold:\n", a.adjMat.shape) # Retain the most strongly connected 1000 edges a.apply...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
The options for local thresholding are similar. Note that a local thresholding always yield a connected graph, and in the case where no arguments are passed, the graph will be the Minimum Spanning Tree. Local thresholding can be very slow for bigger matrices because in each step it is adding successive N-nearest neighb...
a.local_thresholding() print("Is the graph connected? ", mbt.nx.is_connected(a.G)) a.local_thresholding(threshold_type="edgePC", value = 5) print("Is the graph connected? ", mbt.nx.is_connected(a.G)) a.local_thresholding(threshold_type="totalEdges", value = 10000) print("Is the graph connected? ", mbt.nx.is_connected...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Absolute Thresholding In a real brain network, an edge with high negative value is as strong as an edge with a high positive value. So, if you want to threshold in order to get the most strongly connected edges (both negative and positive), you just have to pass an argument use_absolute=True to apply_threshold(). In th...
# Thresholding the 80% most strongly connected edges a.apply_threshold(threshold_type="edgePC", value=80) for e in a.G.edges(data=True): # Printing the edges with negative weight if e[2][ct.WEIGHT] < 0: print(e) # This line is never executed because a negative weighted edge is not strong enough # Absol...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Binary and Absolute Graphs If necessary the graph can be binarised so that weights are removed. You can see that essentially this means that each edge will have a weight of 1.
a.binarise() print("Do all the edges have weight of 1?", all(e[2][ct.WEIGHT] == 1 for e in a.G.edges(data=True)))
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Also, you can make all the weights to have an absolute value, instead of negative and positive values:
# Applying threshold again because of last changes a.apply_threshold() print("Do all the edges have a positive weight before?", all(e[2][ct.WEIGHT] >= 0 for e in a.G.edges(data=True))) a.make_edges_absolute() print("Do all the edges have a positive weight?", all(e[2][ct.WEIGHT] >= 0 for e in a.G.edges(data=True)))
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Importing 3D Spatial Information You can add spatial info to each node of your graph. You need this information if you want to use the visualisation tools of Maybrain. To do so, provide Maybrain with a file that has 4 columns: an anatomical label, and x, y and z coordinates. e.g.: 0 70.800000 30.600000 53.320000 1 32.0...
# Initially, you don't have anatomical/spatial attributes in each node: print("Attributes: ", mbt.nx.get_node_attributes(a.G, ct.ANAT_LABEL), "/", mbt.nx.get_node_attributes(a.G, ct.XYZ)) #After calling import_spatial_info(), you can see the node's attributes a.import_spatial_info(rr.MNI_SPACE_COORDINATES_500) print("...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Properties in Nodes and Edges We have seen already that nodes can have properties about spatial information after calling import_spatial_info(), and edges can have properties about weight after calling applying thresholds. You can add properties to nodes or edges from a text file. The format should be as follows: prop...
# Creating a new Brain and importing the shorter adjacency matrix b = mbt.Brain() b.import_adj_file("data/3d_grid_adj.txt") b.apply_threshold() print("Edges and nodes information:") for e in b.G.edges(data=True): print(e) for n in b.G.nodes(data=True): print(n) # Importing properties and showing again edges a...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
You can notice that if we threshold our brain again, edges are created from scratch and thus properties are lost. The same doesn't happen with nodes as they are always present in our G object. By default, properties of the edges are not imported everytime you threshold the brain. However, you can change that behaviour ...
# Rethresholding the brain, thus loosing information b.apply_threshold(threshold_type="totalEdges", value=0) b.apply_threshold() print("Edges information:") for e in b.G.edges(data=True): print(e) # Setting field to allow automatic importing of properties after a threshold print("\nSetting b.update_properties_aft...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
You can also import the properties from a dictionary, both for nodes and edges. In the following example there are two dictionaries being created with the values of a certain property, named own_property, that will be added to brain:
nodes_props = {0: "val1", 1: "val2"} edges_props = {(0, 1): "edge_val1", (2,3): "edge_val2"} b.import_edge_props_from_dict("own_property", edges_props) b.import_node_props_from_dict("own_property", nodes_props) print("\nEdges information:") for e in b.G.edges(data=True): print(e) print("\nNodes information:"...
docs/01 - Simple Usage.ipynb
RittmanResearch/maybrain
apache-2.0
Load the Dataset Here, we create a directory called usahousing. This directory will hold the dataset that we copy from Google Cloud Storage.
if not os.path.isdir("../data/explore"): os.makedirs("../data/explore")
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Next, we copy the Usahousing dataset from Google Cloud Storage.
!gsutil cp gs://cloud-training-demos/feat_eng/housing/housing_pre-proc.csv ../data/explore
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Then we use the "ls" command to list files in the directory. This ensures that the dataset was copied.
!ls -l ../data/explore
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Next, we read the dataset into a Pandas dataframe.
df_USAhousing = # TODO 1: Your code goes here
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Inspect the Data
# Show the first five row. df_USAhousing.head()
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Let's check for any null values.
df_USAhousing.isnull().sum() df_stats = df_USAhousing.describe() df_stats = df_stats.transpose() df_stats df_USAhousing.info()
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Let's take a peek at the first and last five rows of the data for all columns.
print("Rows : ", df_USAhousing.shape[0]) print("Columns : ", df_USAhousing.shape[1]) print("\nFeatures : \n", df_USAhousing.columns.tolist()) print("\nMissing values : ", df_USAhousing.isnull().sum().values.sum()) print("\nUnique values : \n", df_USAhousing.nunique())
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Explore the Data Let's create some simple plots to check out the data!
_ = sns.heatmap(df_USAhousing.corr())
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Create a distplot showing "median_house_value".
# TODO 2a: Your code goes here sns.set_style("whitegrid") df_USAhousing["median_house_value"].hist(bins=30) plt.xlabel("median_house_value") x = df_USAhousing["median_income"] y = df_USAhousing["median_house_value"] plt.scatter(x, y) plt.show()
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Create a jointplot showing "median_income" versus "median_house_value".
# TODO 2b: Your code goes here sns.countplot(x="ocean_proximity", data=df_USAhousing) # takes numeric only? # plt.figure(figsize=(20,20)) g = sns.FacetGrid(df_USAhousing, col="ocean_proximity") _ = g.map(plt.hist, "households") # takes numeric only? # plt.figure(figsize=(20,20)) g = sns.FacetGrid(df_USAhousing, col=...
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
You can see below that this is the state of California!
x = df_USAhousing["latitude"] y = df_USAhousing["longitude"] plt.scatter(x, y) plt.show()
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is muc...
%%bigquery SELECT FORMAT_TIMESTAMP( "%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount # TODO 3: Set correct BigQuery public dataset for nyc...
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
<h3> Exploring data </h3> Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering.
# TODO 4: Visualize your dataset using the Seaborn library. # Plot the distance of the trip as X and the fare amount as Y. ax = sns.regplot( x="", y="", fit_reg=False, ci=None, truncate=True, data=trips, ) ax.figure.set_size_inches(10, 8)
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Hmm ... do you see something wrong with the data that needs addressing? It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer...
%%bigquery trips SELECT FORMAT_TIMESTAMP( "%Y-%m-%d %H:%M:%S %Z", pickup_datetime) AS pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` ...
notebooks/launching_into_ml/labs/supplemental/python.BQ_explore_data.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
遍历 前序 中序 后序
def preorder(tree): if tree: print tree.get_root() preorder(tree.get_left_child()) preorder(tree.get_right_child()) def postorder(tree): if tree: postorder(tree.get_left_child()) postorder(tree.get_right_child()) print tree.get_root() def inorder(tree): if t...
algorithms/tree.ipynb
namco1992/algorithms_in_python
mit
二叉堆实现优先队列 二叉堆是队列的一种实现方式。 二叉堆可以用完全二叉树来实现。所谓完全二叉树(complete binary tree),有定义如下: A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. 除叶节点外,所有层都是填满的,叶节点则按照从左至右的顺序填满。 完全二叉树的一个重要性质: 当以列表表示完全二叉树时,位置 p 的父节点,其 left child 位于 2p ...
class BinHeap(object): def __init__(self): self.heap_list = [0] self.current_size = 0
algorithms/tree.ipynb
namco1992/algorithms_in_python
mit
二叉搜索树 Binary Search Trees 其性质与字典非常相近。 Operations Map() Create a new, empty map. put(key,val) Add a new key-value pair to the map. If the key is already in the map then replace the old value with the new value. get(key) Given a key, return the value stored in the map or None otherwise. del Delete the key-value pair fro...
class BinarySearchTree(object): def __init__(self): self.root = None self.size = 0 def length(self): return self.size def __len__(self): return self.size def __iter__(self): return self.root.__iter__() def put(self, key, val): if se...
algorithms/tree.ipynb
namco1992/algorithms_in_python
mit
An integration engineer might prefer to copy system-of-records data into pandas.DataFrame objects. Note that pandas is itself capable of reading directly from various SQL databases, although it usually needs a supporting package like cx_Oracle.
from pandas import DataFrame arcs = DataFrame({"Source": ["Denver", "Denver", "Denver", "Detroit", "Detroit", "Detroit",], "Destination": ["Boston", "New York", "Seattle", "Boston", "New York", "Seattle"], "Capacity": [120, 120, 120, 100, 80, 120]}) ...
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Next we create a PanDat input data object from the list-of-lists/DataFrame representations.
%env PATH = PATH:/Users/petercacioppi/ampl/ampl from netflow import input_schema, solve, solution_schema dat = input_schema.PanDat(commodities=commodities, nodes=nodes, cost=cost, arcs=arcs, inflow=inflow)
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
We now create a PanDat solution data object by calling solve.
sln = solve(dat)
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
We now create a list-of-lists representation of the solution data object.
sln_lists = {t: list(map(list, getattr(sln, t).itertuples(index=False))) for t in solution_schema.all_tables}
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Here we demonstrate that sln_lists is a dictionary mapping table name to list-of-lists of solution report data.
import pprint for sln_table_name, sln_table_data in sln_lists.items(): print "\n\n**\nSolution Table %s\n**"%sln_table_name pprint.pprint(sln_table_data)
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Of course the solution data object itself contains DataFrames, if that representation is preferred.
sln.flow
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Using ticdat to build robust engines The preceding section demonstrated how we can use ticdat to build modular engines. We now demonstrate how we can use ticdat to build engines that check solve pre-conditions, and are thus robust with respect to data integrity problems. First, lets violate our (somewhat artificial) ru...
dat.commodities.loc[dat.commodities["Name"] == "Pencils", "Volume"] = 0 dat.commodities
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
The input_schema can not only flag this problem, but give us a useful data structure to examine.
data_type_failures = input_schema.find_data_type_failures(dat) data_type_failures data_type_failures['commodities', 'Volume']
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Next, lets add a Cost record for a non-existent commodity and see how input_schema flags this problem.
dat.cost = dat.cost.append({'Commodity':'Crayons', 'Source': 'Detroit', 'Destination': 'Seattle', 'Cost': 10}, ignore_index=True) fk_failures = input_schema.find_foreign_key_failures(dat, verbosity="Low") fk_failures fk_failures['cost', 'commodities', ('Commodit...
examples/amplpy/netflow/netflow_other_data_sources.ipynb
opalytics/opalytics-ticdat
bsd-2-clause
Create a sampling layer
class Sampling(layers.Layer): """Uses (z_mean, z_log_var) to sample z, the vector encoding a digit.""" def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) r...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Build the encoder
latent_dim = 2 encoder_inputs = keras.Input(shape=(28, 28, 1)) x = layers.Conv2D(32, 3, activation="relu", strides=2, padding="same")(encoder_inputs) x = layers.Conv2D(64, 3, activation="relu", strides=2, padding="same")(x) x = layers.Flatten()(x) x = layers.Dense(16, activation="relu")(x) z_mean = layers.Dense(latent...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Build the decoder
latent_inputs = keras.Input(shape=(latent_dim,)) x = layers.Dense(7 * 7 * 64, activation="relu")(latent_inputs) x = layers.Reshape((7, 7, 64))(x) x = layers.Conv2DTranspose(64, 3, activation="relu", strides=2, padding="same")(x) x = layers.Conv2DTranspose(32, 3, activation="relu", strides=2, padding="same")(x) decoder_...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Define the VAE as a Model with a custom train_step
class VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder self.total_loss_tracker = keras.metrics.Mean(name="total_loss") self.reconstruction_loss_tracker = keras.metrics.Mean( ...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Train the VAE
(x_train, _), (x_test, _) = keras.datasets.mnist.load_data() mnist_digits = np.concatenate([x_train, x_test], axis=0) mnist_digits = np.expand_dims(mnist_digits, -1).astype("float32") / 255 vae = VAE(encoder, decoder) vae.compile(optimizer=keras.optimizers.Adam()) vae.fit(mnist_digits, epochs=30, batch_size=128)
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Display a grid of sampled digits
import matplotlib.pyplot as plt def plot_latent_space(vae, n=30, figsize=15): # display a n*n 2D manifold of digits digit_size = 28 scale = 1.0 figure = np.zeros((digit_size * n, digit_size * n)) # linearly spaced coordinates corresponding to the 2D plot # of digit classes in the latent space ...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
Display how the latent space clusters different digit classes
def plot_label_clusters(vae, data, labels): # display a 2D plot of the digit classes in the latent space z_mean, _, _ = vae.encoder.predict(data) plt.figure(figsize=(12, 10)) plt.scatter(z_mean[:, 0], z_mean[:, 1], c=labels) plt.colorbar() plt.xlabel("z[0]") plt.ylabel("z[1]") plt.show(...
examples/generative/ipynb/vae.ipynb
keras-team/keras-io
apache-2.0
set parameter
#parameter: searchterm="big data" #lowecase! colorlist=["#01be70","#586bd0","#c0aa12","#0183e6","#f69234","#0095e9","#bd8600","#007bbe","#bb7300","#63bcfc","#a84a00","#01bedb","#82170e","#00c586","#a22f1f","#3fbe57","#3e4681","#9bc246","#9a9eec","#778f00","#00aad9","#fc9e5e","#01aec1","#832c1e","#55c99a","#dd715b","#01...
1-number of papers over time/Creating overview bar-plots.ipynb
MathiasRiechert/BigDataPapers
gpl-3.0
load data from SQL database:
dsn_tns=cx_Oracle.makedsn('127.0.0.1','6025',service_name='bibliodb01.fiz.karlsruhe') #due to licence requirements, # access is only allowed for members of the competence center of bibliometric and cooperation partners. You can still # continue with the resulting csv below. #open connection: db=cx_Oracle.connect(<use...
1-number of papers over time/Creating overview bar-plots.ipynb
MathiasRiechert/BigDataPapers
gpl-3.0
merging data
dfWOS=pd.read_csv("all_big_data_titles_year_wos.csv",sep=";") dfSCOPUS=pd.read_csv("all_big_data_titles_year_scopus.csv",sep=";") df=pd.merge(dfWOS,dfSCOPUS,on='ARTICLE_TITLE',how='outer') #get PUBYEAR in one column: df.loc[df['wos'] == 1, 'PUBYEAR_y'] = df['PUBYEAR_x'] #save resulting csv again: df=df[['ARTICLE_TITLE...
1-number of papers over time/Creating overview bar-plots.ipynb
MathiasRiechert/BigDataPapers
gpl-3.0
grouping data
grouped=df.groupby(['PUBYEAR_y']) df2=grouped.agg('count').reset_index() df2
1-number of papers over time/Creating overview bar-plots.ipynb
MathiasRiechert/BigDataPapers
gpl-3.0