markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Imports
from __future__ import print_function import warnings warnings.filterwarnings("ignore", category=FutureWarning) import random import six import numpy as np import thinc.extra.datasets import spacy from spacy.util import minibatch, compounding
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Helper Functions
def load_data(limit=0, split=0.8): """Load data from the IMDB dataset.""" # Partition off part of the dataset to train and test train_data, _ = thinc.extra.datasets.imdb() random.shuffle(train_data) train_data = train_data[-limit:] texts, labels = zip(*train_data) cats = [{"POSITIVE": bo...
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Train Model
hyperparams = { 'model':'en', 'n_iter': 2, # epochs 'n_texts': 500, # num of training samples 'architecture': 'simple_cnn', 'num_samples': 1000, 'train_test_split': 0.8, 'dropout': 0.2 } run.log_hyperparameters(hyperparams) # using the basic en model try: nlp = spacy.load(hyperparams['m...
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Log for Deployment Create Wrapper Class Verta deployment expects a particular interface for its models. They must expose a predict() function, so we'll create a thin wrapper class around our spaCy pipeline.
class TextClassifier: def __init__(self, nlp): self.nlp = nlp def predict(self, input_list): # param must be a list/batch of inputs predictions = [] for text in input_list: scores = self.nlp(text).cats if scores['POSITIVE'] > scores['NEGATIVE']: ...
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Create Deployment Artifacts Verta deployment also needs a couple more details about the model. What do its inputs and outputs look like?
from verta.utils import ModelAPI # Verta-provided utility class model_api = ModelAPI( input_list, # example inputs model.predict(input_list), # example outputs )
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
What PyPI-installable packages (with version numbers) are required to deserialize and run the model?
requirements = ["numpy", "spacy", "thinc"] # this could also have been a path to a requirements.txt file on disk run.log_requirements(requirements)
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Log Model
# test the trained model test_text = 'The Lion King was very entertaining. The movie was visually spectacular.' doc = nlp(test_text) print(test_text) print(doc.cats) run.log_model( model, model_api=model_api, )
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Deployment
run
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Click the link above to view your Experiment Run in the Verta Web App, and deploy it. Once it's ready, you can make predictions against the deployed model.
from verta._demo_utils import DeployedModel deployed_model = DeployedModel(HOST, run.id) deployed_model.predict(["I would definitely watch this again!"])
client/workflows/examples/text_classification_spacy.ipynb
mitdbg/modeldb
mit
Loading the data In this folder there are 83 subjects data in nifti format (.nii). The dada for each subject is a volume of (70x256x256) voxels and composed of 3 eigenvalues, 3 eigenvectors, and FA volume.
#subjects folder BASE_PATH = 'G:/DTI_DS/original' #subject number # subject_number = 84 # very inclined subject subject_number = 1 if(subject_number < 10): subject_dir = str(BASE_PATH)+str('/subject00')+str(subject_number) else: subject_dir = str(BASE_PATH)+str('/subject0')+str(subject_number) #load...
dev/.ipynb_checkpoints/DTI_open_01-05-17_GRP-checkpoint.ipynb
GustavoRP/IA369Z
gpl-3.0
Data visualization FA MD is a 3D scalar map that shows the difusion assimetry for each voxel, so each one is associated with an intensity value. Inline image of FA in three different viels (Axial, coronal, and sagittal viels).
# Show FA %matplotlib inline # %matplotlib notebook from matplotlib.widgets import Slider sz, sy, sx = FA.shape # set up figure fig = plt.figure(figsize=(15,15)) xy = fig.add_subplot(1,3,1) plt.title("Axial Slice") xz = fig.add_subplot(1,3,2) plt.title("Coronal Slice") yz = fig.add_subplot(1,3,3) plt.title("Sagittal S...
dev/.ipynb_checkpoints/DTI_open_01-05-17_GRP-checkpoint.ipynb
GustavoRP/IA369Z
gpl-3.0
MD MD is a 3D scalar map that shows the mean difusion for each voxel, so each one is associated with an intensity value. Inline image of slices of the MD in three different viels (Axial, coronal, and sagittal viels).
# Show MD %matplotlib inline # %matplotlib notebook from matplotlib.widgets import Slider sz, sy, sx = MD.shape # set up figure fig = plt.figure(figsize=(15,15)) xy = fig.add_subplot(1,3,1) plt.title("Axial Slice") xz = fig.add_subplot(1,3,2) plt.title("Coronal Slice") yz = fig.add_subplot(1,3,3) plt.title("Sagittal S...
dev/.ipynb_checkpoints/DTI_open_01-05-17_GRP-checkpoint.ipynb
GustavoRP/IA369Z
gpl-3.0
First vector (main tensor direction) This is a 3D vecotr field, so each voxel is associated with a vector. Inline image of slices of the FA in three different viels (Axial, coronal, and sagittal viels).
# Show Vector Field %matplotlib inline # %matplotlib notebook from matplotlib.widgets import Slider evt_d = evt[0]*evt[0] nv, sz, sy, sx = evl.shape fig = plt.figure(figsize=(15,15)) xy = fig.add_subplot(1,3,1) plt.title("Axial Slice") plt.axis("off") xz = fig.add_subplot(1,3,2) plt.title("Coronal Slice") plt.axis...
dev/.ipynb_checkpoints/DTI_open_01-05-17_GRP-checkpoint.ipynb
GustavoRP/IA369Z
gpl-3.0
DataAccessLayer.getAvailableLocationNames() Now create a new data request, and set the data type to grid to request all available grids with getAvailableLocationNames()
request = DataAccessLayer.newDataRequest() request.setDatatype("grid") available_grids = DataAccessLayer.getAvailableLocationNames(request) available_grids.sort() list(available_grids)
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
DataAccessLayer.getAvailableParameters() After datatype and model name (locationName) are set, you can query all available parameters with getAvailableParameters()
request.setLocationNames("RAP13") availableParms = DataAccessLayer.getAvailableParameters(request) availableParms.sort() list(availableParms)
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
DataAccessLayer.getAvailableLevels() Selecting "T" for temperature.
request.setParameters("T") availableLevels = DataAccessLayer.getAvailableLevels(request) for level in availableLevels: print(level)
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
0.0SFC is the Surface level FHAG stands for Fixed Height Above Ground (in meters) NTAT stands for Nominal Top of the ATmosphere BL stands for Boundary Layer, where 0.0_30.0BL reads as 0-30 mb above ground level TROP is the Tropopause level request.setLevels() For this example we will use Surface Temperature
request.setLevels("2.0FHAG")
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
DataAccessLayer.getAvailableTimes() getAvailableTimes(request, True) will return an object of run times - formatted as YYYY-MM-DD HH:MM:SS getAvailableTimes(request) will return an object of all times - formatted as YYYY-MM-DD HH:MM:SS (F:ff) getForecastRun(cycle, times) will return a DataTime array for a single forec...
cycles = DataAccessLayer.getAvailableTimes(request, True) times = DataAccessLayer.getAvailableTimes(request) fcstRun = DataAccessLayer.getForecastRun(cycles[-1], times)
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
DataAccessLayer.getGridData() Now that we have our request and DataTime fcstRun arrays ready, it's time to request the data array from EDEX.
response = DataAccessLayer.getGridData(request, [fcstRun[-1]]) for grid in response: data = grid.getRawData() lons, lats = grid.getLatLonCoords() print('Time :', str(grid.getDataTime())) print('Model:', str(grid.getLocationName())) print('Parm :', str(grid.getParameter())) print('Unit :', str(grid.getUnit(...
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
Plotting with Matplotlib and Cartopy 1. pcolormesh
%matplotlib inline import matplotlib.pyplot as plt import matplotlib import cartopy.crs as ccrs import cartopy.feature as cfeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import numpy as np import numpy.ma as ma from scipy.io import loadmat def make_map(bbox, projection=ccrs.PlateCarre...
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
2. contourf
fig2, ax2 = make_map(bbox=bbox) cs2 = ax2.contourf(lons, lats, data, 80, cmap=cmap, vmin=data.min(), vmax=data.max()) cbar2 = fig2.colorbar(cs2, extend='both', shrink=0.5, orientation='horizontal') cbar2.set_label(grid.getLocationName().decode('UTF-8') +" " \ + grid.getLevel().decode('...
notebooks/AWIPS/Grid_Levels_and_Parameters.ipynb
julienchastang/unidata-python-workshop
mit
Procedure with steps Here we post to a procedure with multiple steps. The steps are displayed as soon as the procedure starts running and are updated accordingly.
print mldb.post_and_track('/v1/procedures', { 'type' : 'mock', 'params' : {'durationMs' : 8000, "refreshRateMs" : 500} }, 0.5)
container_files/tutorials/Using pymldb Progress Bar and Cancel Button Tutorial.ipynb
mldbai/mldb
apache-2.0
Procedure with no steps A procedure with no inner steps will simply display its progress. This one is an example where the "initializing" phase sticks for some time, so the "Cancel" button is shown alone and eventually, when the "executing" phase is reached, the progress bar is displayed.
print mldb.put_and_track('/v1/procedures/embedded_imagess', { 'type' : 'import.text', 'params' : { 'dataFileUrl' : 'https://s3.amazonaws.com/benchm-ml--main/train-1m.csv', 'outputDataset' : { 'id' : 'embedded_images_realestate', 'type' : 'sparse.mutable' } } }...
container_files/tutorials/Using pymldb Progress Bar and Cancel Button Tutorial.ipynb
mldbai/mldb
apache-2.0
Serial procedure When using post_and_track along with a serial procedure, a progress bar is displayed for each step. They will only take the value of 0/1 and 1/1.
prefix = 'file://mldb/mldb_test_data/dataset-builder' print mldb.post_and_track('/v1/procedures', { 'type' : 'serial', 'params' : { 'steps' : [ { 'type' : 'mock', 'params' : {'durationMs' : 2000, "refreshRateMs" : 500} }, { 'type' :...
container_files/tutorials/Using pymldb Progress Bar and Cancel Button Tutorial.ipynb
mldbai/mldb
apache-2.0
Language Detection
text = Text("Bonjour, Mesdames.") print("Language Detected: Code={}, Name={}\n".format(text.language.code, text.language.name))
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Tokenization
zen = Text("Beautiful is better than ugly. " "Explicit is better than implicit. " "Simple is better than complex.") print(zen.words) print(zen.sentences)
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Part of Speech Tagging
text = Text(u"O primeiro uso de desobediência civil em massa ocorreu em setembro de 1906.") print("{:<16}{}".format("Word", "POS Tag")+"\n"+"-"*30) for word, tag in text.pos_tags: print(u"{:<16}{:>2}".format(word, tag))
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Named Entity Recognition
text = Text(u"In Großbritannien war Gandhi mit dem westlichen Lebensstil vertraut geworden") print(text.entities)
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Polarity
print("{:<16}{}".format("Word", "Polarity")+"\n"+"-"*30) for w in zen.words[:6]: print("{:<16}{:>2}".format(w, w.polarity))
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Embeddings
word = Word("Obama", language="en") print("Neighbors (Synonms) of {}".format(word)+"\n"+"-"*30) for w in word.neighbors: print("{:<16}".format(w)) print("\n\nThe first 10 dimensions out the {} dimensions\n".format(word.vector.shape[0])) print(word.vector[:10])
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Morphology
word = Text("Preprocessing is an essential step.").words[0] print(word.morphemes)
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Transliteration
from polyglot.transliteration import Transliterator transliterator = Transliterator(source_lang="en", target_lang="ru") print(transliterator.transliterate(u"preprocessing"))
notebooks/README.ipynb
iamtrask/polyglot
gpl-3.0
Problem 1: A Time Series Model Consider the time series model $$ x_{t+1} = \alpha x_t (1 - x_t) $$ Let's set $\alpha = 4$
α = 4
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Here's a typical time series:
n = 200 x = np.empty(n) x[0] = 0.2 for t in range(n-1): x[t+1] = α * x[t] * (1 - x[t]) plt.plot(x) plt.show()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Here's a function that simulates for n periods, starting from x0, and returns only the final value:
def quad(x0, n): x = x0 for i in range(1, n): x = α * x * (1 - x) return x
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Let's see how fast this runs:
n = 10_000_000 tic() x = quad(0.2, n) toc()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Now let's try this in FORTRAN. Note --- this step is intended to be a demo and will only execute if you have the file fastquad.f90 in your pwd you have a FORTRAN compiler installed and modify the compilation code below appropriately
!cat fastquad.f90 !gfortran -O3 fastquad.f90 !./a.out
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Now let's do the same thing in Python using Numba's JIT compilation:
quad_jitted = jit(quad) tic() x = quad_jitted(0.2, n) toc() tic() x = quad_jitted(0.2, n) toc()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
After JIT compilation, function execution speed is about the same as FORTRAN. But remember, JIT compilation for Python is still limited --- see here If these limitations frustrate you, then try Julia. Problem 2: Brute Force Optimization The problem is to maximize the function $$ f(x, y) = \frac{\cos \left(x^2 + y^2 \r...
def f(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) + 1 from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib import cm gridsize = 50 gmin, gmax = -3, 3 xgrid = np.linspace(gmin, gmax, gridsize) ygrid = xgrid x, y = np.meshgrid(xgrid, ygrid) # === plot value function === # fig = plt.figure(figs...
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Vectorized code
grid = np.linspace(-3, 3, 10000) x, y = np.meshgrid(grid, grid) tic() np.max(f(x, y)) toc()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
JITTed code A jitted version
@jit def compute_max(): m = -np.inf for x in grid: for y in grid: z = np.cos(x**2 + y**2) / (1 + x**2 + y**2) + 1 if z > m: m = z return m compute_max() tic() compute_max() toc()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Numba for vectorization with automatic parallelization - even faster:
@vectorize('float64(float64, float64)', target='parallel') def f_par(x, y): return np.cos(x**2 + y**2) / (1 + x**2 + y**2) + 1 x, y = np.meshgrid(grid, grid) np.max(f_par(x, y)) tic() np.max(f_par(x, y)) toc()
John/numba.ipynb
QuantEcon/phd_workshops
bsd-3-clause
Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates will be used to determine the adjacency between sensors. This serves as a spatial prior to the clustering. Spatiotemporal clusters...
# Authors: Denis Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from mne.viz import plot_topomap import mne from mne.stats import spatio_...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Set parameters
data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' event_id = {'Aud/L': 1, 'Aud/R': 2, 'Vis/L': 3, 'Vis/R': 4} tmin = -0.2 tmax = 0.5 # Setup for reading the raw data raw = mne.io.read_raw_fif(...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Read epochs for the channel of interest
picks = mne.pick_types(raw.info, meg='mag', eog=True) reject = dict(mag=4e-12, eog=150e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=None, reject=reject, preload=True) epochs.drop_channels(['EOG 061']) epochs.equalize_event_counts(event_id) X = [epochs[k].get_da...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Find the FieldTrip neighbor definition to setup sensor connectivity
connectivity, ch_names = find_ch_connectivity(epochs.info, ch_type='mag') print(type(connectivity)) # it's a sparse matrix! plt.imshow(connectivity.toarray(), cmap='gray', origin='lower', interpolation='nearest') plt.xlabel('{} Magnetometers'.format(len(ch_names))) plt.ylabel('{} Magnetometers'.format(len...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute permutation statistic How does it work? We use clustering to bind together features which are similar. Our features are the magnetic fields measured over our sensor array at different times. This reduces the multiple comparison problem. To compute the actual test-statistic, we first sum all F-values in all clus...
# set cluster threshold threshold = 50.0 # very high, but the test is quite sensitive on this data # set family-wise p-value p_accept = 0.01 cluster_stats = spatio_temporal_cluster_test(X, n_permutations=1000, threshold=threshold, tail=1, ...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Note. The same functions work with source estimate. The only differences are the origin of the data, the size, and the connectivity definition. It can be used for single trials or for groups of subjects. Visualize clusters
# configure variables for visualization colors = {"Aud": "crimson", "Vis": 'steelblue'} linestyles = {"L": '-', "R": '--'} # get sensor positions via layout pos = mne.find_layout(epochs.info).pos # organize data for plotting evokeds = {cond: epochs[cond].average() for cond in event_id} # loop over clusters for i_clu...
0.17/_downloads/1b26761ba88c6441bd13afd5730965a4/plot_stats_spatio_temporal_cluster_sensors.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Airbnb Data First we read in the data
url1 = "http://data.insideairbnb.com/united-states/" url2 = "ny/new-york-city/2016-02-02/data/listings.csv.gz" full_df = pd.read_csv(url1+url2, compression="gzip") full_df.head()
Code/Lab/Airbnb.ipynb
DaveBackus/Data_Bootcamp
mit
We don't want all data, so let's focus on a few variables.
df = full_df[["id", "price", "number_of_reviews", "review_scores_rating"]] df.head()
Code/Lab/Airbnb.ipynb
DaveBackus/Data_Bootcamp
mit
Need to convert prices to floats
df.replace({'price': {'\$': ''}}, regex=True, inplace=True) df.replace({'price': {'\,': ''}}, regex=True, inplace=True) df['price'] = df['price'].astype('float64', copy=False)
Code/Lab/Airbnb.ipynb
DaveBackus/Data_Bootcamp
mit
We might think that better apartments get rented more often, let's plot a scatter (or multiple boxes?) plot of the number of reviews vs the review score
df.plot.scatter(x="number_of_reviews", y="review_scores_rating", figsize=(10, 8), alpha=0.2) bins = [0, 5, 10, 25, 50, 100, 350] boxplot_vecs = [] fig, ax = plt.subplots(figsize=(10, 8)) for i in range(1, 7): lb = bins[i-1] ub = bins[i] foo = df["review_scores_rating"][df["number_of_reviews"].apply(lambd...
Code/Lab/Airbnb.ipynb
DaveBackus/Data_Bootcamp
mit
Better reviews also are correlated with higher prices
df.plot.scatter(x="review_scores_rating", y="price", figsize=(10, 8), alpha=0.2)
Code/Lab/Airbnb.ipynb
DaveBackus/Data_Bootcamp
mit
1 Example The following demonstrates how to instantiate a graph and a filter, the two main objects of the package.
G = graphs.Logo() G.estimate_lmax() g = filters.Heat(G, tau=100)
examples/playground.ipynb
epfl-lts2/pygsp
bsd-3-clause
Let's now create a graph signal: a set of three Kronecker deltas for that example. We can now look at one step of heat diffusion by filtering the deltas with the above defined filter. Note how the diffusion follows the local structure!
DELTAS = [20, 30, 1090] s = np.zeros(G.N) s[DELTAS] = 1 s = g.filter(s) G.plot(s, highlight=DELTAS, backend='matplotlib')
examples/playground.ipynb
epfl-lts2/pygsp
bsd-3-clause
2 Tutorials and examples Try our tutorials or examples.
# Your code here.
examples/playground.ipynb
epfl-lts2/pygsp
bsd-3-clause
3 Playground Try something of your own! The API reference is your friend.
# Your code here.
examples/playground.ipynb
epfl-lts2/pygsp
bsd-3-clause
If you miss a package, you can install it with:
%pip install numpy
examples/playground.ipynb
epfl-lts2/pygsp
bsd-3-clause
Make a grid and set boundary conditions:
mg = RasterModelGrid( (20, 20), xy_spacing=50.0 ) # raster grid with 20 rows, 20 columns and dx=50m z = np.random.rand(mg.size("node")) # random noise for initial topography mg.add_field("topographic__elevation", z, at="node") mg.set_closed_boundaries_at_grid_edges( False, True, False, True ) # N and S boun...
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Set the initial and run conditions:
total_t = 2000000.0 # total run time (yr) dt = 1000.0 # time step (yr) nt = int(total_t // dt) # number of time steps uplift_rate = 0.0001 # uplift rate (m/yr) kappa = 0.001 # erodibility (m/yr) Sc = 0.6 # critical slope
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Instantiate the components: The hillslope diffusion component must be used together with a flow router/director that provides the steepest downstream slope for each node, with a D4 method (creates the field topographic__steepest_slope at nodes).
fdir = FlowDirectorSteepest(mg) tl_diff = TransportLengthHillslopeDiffuser(mg, erodibility=kappa, slope_crit=Sc)
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Run the components for 2 Myr and trace an East-West cross-section of the topography every 100 kyr:
for t in range(nt): fdir.run_one_step() tl_diff.run_one_step(dt) z[mg.core_nodes] += uplift_rate * dt # add the uplift # add some output to let us see we aren't hanging: if t % 100 == 0: print(t * dt) # plot east-west cross-section of topography: x_plot = range(0, 1000, 50...
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
And plot final topography:
figure("final topography") im = imshow_grid( mg, "topographic__elevation", grid_units=["m", "m"], var_name="Elevation (m)" )
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
This behaviour corresponds to the evolution observed using a classical non-linear diffusion model. Example 2: In this example, we show that when the slope is steep ($S \ge S_c$), the transport-length hillsope diffusion simulates mass wasting, with long transport distances. First, we create a grid: the western half of t...
# Create grid and topographic elevation field: mg2 = RasterModelGrid((20, 20), xy_spacing=50.0) z = np.zeros(mg2.number_of_nodes) z[mg2.node_x > 500] = mg2.node_x[mg2.node_x > 500] / 10 mg2.add_field("topographic__elevation", z, at="node") # Set boundary conditions: mg2.set_closed_boundaries_at_grid_edges(False, True...
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Set the run conditions:
total_t = 1000000.0 # total run time (yr) dt = 1000.0 # time step (yr) nt = int(total_t // dt) # number of time steps
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Instantiate the components:
fdir = FlowDirectorSteepest(mg2) tl_diff = TransportLengthHillslopeDiffuser(mg2, erodibility=0.001, slope_crit=0.6)
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Run for 1 Myr, plotting the cross-section regularly:
for t in range(nt): fdir.run_one_step() tl_diff.run_one_step(dt) # add some output to let us see we aren't hanging: if t % 100 == 0: print(t * dt) z_plot = z[100:120] figure(2) plot(x_plot, z_plot)
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
The material is diffused from the top and along the slope and it accumulates at the bottom, where the topography flattens. As a comparison, the following code uses linear diffusion on the same slope:
# Import Linear diffuser: from landlab.components import LinearDiffuser # Create grid and topographic elevation field: mg3 = RasterModelGrid((20, 20), xy_spacing=50.0) z = np.ones(mg3.number_of_nodes) z[mg.node_x > 500] = mg.node_x[mg.node_x > 500] / 10 mg3.add_field("topographic__elevation", z, at="node") # Set boun...
notebooks/tutorials/hillslope_geomorphology/transport-length_hillslope_diffuser/TLHDiff_tutorial.ipynb
landlab/landlab
mit
Multinomial distribution: bags of marbles Written by: Deebul Nair (2016) Edited by: Jaakko Luttinen (2016) Inspired by https://probmods.org/hierarchical-models.html Using multinomial distribution There are several bags of coloured marbles, each bag containing different amounts of each color. Marbles are drawn at random...
n_colors = 5 # number of possible colors n_bags = 3 # number of bags n_trials = 20 # number of draws from each bag
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Generate randomly a color distribution for each bag:
from bayespy import nodes import numpy as np p_colors = nodes.Dirichlet(n_colors * [0.5], plates=(n_bags,)).random()
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
The concentration parameter $\begin{bmatrix}0.5 & \ldots & 0.5\end{bmatrix}$ makes the distributions very non-uniform within each bag, that is, the amount of each color can be very different. We can visualize the probability distribution of the colors in each bag:
import bayespy.plot as bpplt bpplt.hinton(p_colors) bpplt.pyplot.title("Original probability distributions of colors in the bags");
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
As one can see, the color distributions aren't very uniform in any of the bags because of the small concentration parameter. Next, make the ball draws:
marbles = nodes.Multinomial(n_trials, p_colors).random() print(marbles)
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Model We will use the same generative model for estimating the color distributions in the bags as we did for generating the data: $$ \theta_i \sim \mathrm{Dirichlet}\left(\begin{bmatrix} 0.5 & \ldots & 0.5 \end{bmatrix}\right) $$ $$ y_i | \theta_i \sim \mathrm{Multinomial}(\theta_i) $$ The simple graphical model can be...
%%tikz -f svg \usetikzlibrary{bayesnet} \node [latent] (theta) {$\theta$}; \node [below=of theta, obs] (y) {$y$}; \edge {theta} {y}; \plate {trials} {(y)} {trials}; \plate {bags} {(theta)(y)(trials)} {bags};
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
The model is constructed equivalently to the generative model (except we don't use the nodes to draw random samples):
theta = nodes.Dirichlet(n_colors * [0.5], plates=(n_bags,)) y = nodes.Multinomial(n_trials, theta)
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Data is provided by using the observe method:
y.observe(marbles)
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Performing Inference
from bayespy.inference import VB Q = VB(y, theta) Q.update(repeat=1000) import bayespy.plot as bpplt bpplt.hinton(theta) bpplt.pyplot.title("Learned distribution of colors") bpplt.pyplot.show()
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Using categorical Distribution The same problem can be solved with categorical distirbution. Categorical distribution is similar to the Multinomical distribution expect for the output it produces. Multinomial and Categorical infer the number of colors from the size of the probability vector (p_theta) Categorical data i...
from bayespy import nodes import numpy as np #The marbles drawn based on the distribution for 10 trials # Using same p_color distribution as in the above example draw_marbles = nodes.Categorical(p_colors, plates=(n_trials, n_bags)).random()
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Model
from bayespy import nodes import numpy as np p_theta = nodes.Dirichlet(np.ones(n_colors), plates=(n_bags,), name='p_theta') bag_model = nodes.Categorical(p_theta, plates=(n_trials, n_bags), name='bag_model')
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Inference
bag_model.observe(draw_marbles) from bayespy.inference import VB Q = VB(bag_model, p_theta) Q.update(repeat=1000) %matplotlib inline import bayespy.plot as bpplt bpplt.hinton(p_theta) bpplt.pyplot.tight_layout() bpplt.pyplot.title("Learned Distribution of colors using Categorical Distribution") bpplt.pyplot.show()
doc/source/examples/multinomial.ipynb
jluttine/bayespy
mit
Word counting Write a function tokenize that takes a string of English text returns a list of words. It should also remove stop words, which are common short words that are often removed before natural language processing. Your function should have the following logic: Split the string into lines using splitlines. Spl...
def tokenize(s, stop_words=None, punctuation='`~!@#$%^&*()_-+={[}]|\:;"<,>.?/}\t'): """Split a string into a list of words, removing punctuation and stop words.""" if type(stop_words)==str: stopwords=list(stop_words.split(" ")) else: stopwords=stop_words lines = s.splitlines() words...
assignments/assignment07/AlgorithmsEx01.ipynb
CalPolyPat/phys202-2015-work
mit
Write a function count_words that takes a list of words and returns a dictionary where the keys in the dictionary are the unique words in the list and the values are the word counts.
def count_words(data): """Return a word count dictionary from the list of words in data.""" wordcount={} for d in data: if d in wordcount: wordcount[d] += 1 else: wordcount[d] = 1 return wordcount assert count_words(tokenize('this and the this from and a a a')) =...
assignments/assignment07/AlgorithmsEx01.ipynb
CalPolyPat/phys202-2015-work
mit
Write a function sort_word_counts that return a list of sorted word counts: Each element of the list should be a (word, count) tuple. The list should be sorted by the word counts, with the higest counts coming first. To perform this sort, look at using the sorted function with a custom key and reverse argument.
def sort_word_counts(wc): """Return a list of 2-tuples of (word, count), sorted by count descending.""" def getkey(item): return item[1] sortedwords = [(i,wc[i]) for i in wc] return sorted(sortedwords, key=getkey, reverse=True) assert sort_word_counts(count_words(tokenize('this and a the this t...
assignments/assignment07/AlgorithmsEx01.ipynb
CalPolyPat/phys202-2015-work
mit
Perform a word count analysis on Chapter 1 of Moby Dick, whose text can be found in the file mobydick_chapter1.txt: Read the file into a string. Tokenize with stop words of 'the of and a to in is it that as'. Perform a word count, the sort and save the result in a variable named swc.
f = open('mobydick_chapter1.txt', 'r') swc = sort_word_counts(count_words(tokenize(f.read(), stop_words='the of and a to in is it that as'))) print(len(swc)) assert swc[0]==('i',43) assert len(swc)==849 #I changed the assert to length 849 instead of 848. I wasn't about to search through the first chapter of moby dic...
assignments/assignment07/AlgorithmsEx01.ipynb
CalPolyPat/phys202-2015-work
mit
Create a "Cleveland Style" dotplot of the counts of the top 50 words using Matplotlib. If you don't know what a dotplot is, you will have to do some research...
words50 = np.array(swc) f=plt.figure(figsize=(25,5)) plt.plot(np.linspace(0,50,50), words50[:50,1], 'ko') plt.xlim(0,50) plt.xticks(np.linspace(0,50,50),words50[:50,0]); assert True # use this for grading the dotplot
assignments/assignment07/AlgorithmsEx01.ipynb
CalPolyPat/phys202-2015-work
mit
如何使用和开发微信聊天机器人的系列教程 A workshop to develop & use an intelligent and interactive chat-bot in WeChat WeChat is a popular social media app, which has more than 800 million monthly active users. <img src='https://www.iss.nus.edu.sg/images/default-source/About-Us/7.6.1-teaching-staff/sam-website.tmb-.png' width=8% style="flo...
# Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); # !pip install --upgrade google-api-python-client
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
<span style="color:blue">Virtual Worker: When Chat-bot meets RPA-bot</span> 虚拟员工: 贷款填表申请审批一条龙自动化流程 (Mortgage loan application automation) Synchronous processing when triggering RPA-Bot
# Library/Function to use operating system's shell script command, e.g. bash, echo, cd, pwd, etc import subprocess, time # Funciton to trigger RPA-Bot (TagUI script: mortgage loan application automation) from VA-Bot (python script) # Trigger RPA-Bot [ Synchronous ] # def didi_invoke_rpa_bot(rpa_bot_file, rpa_bot = 'r...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Asynchronous processing when triggering RPA-Bot
# Trigger RPA-Bot [ Asynchronous ] # http://docs.dask.org/en/latest/_downloads/daskcheatsheet.pdf from dask.distributed import Client def didi_invoke_rpa_bot_async(rpa_bot_file): client = Client(processes=False) ipa_task = client.submit(didi_invoke_rpa_bot, rpa_bot_file) ipa_task.add_done_callback(didi_inv...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
<span style="color:blue">Wrap RPA-Bot into Functions() for conversational virtual assistant (VA):</span> Reuse above defined Functions(). 虚拟员工: 文字指令交互(Conversational automation using text/message command)
parm_msg = {} # Define a global variable to hold current msg # Define "keywords intention command -> automation action" lookup to invoke RPA-Bot process automation functions parm_bot_intention_action = { '#apply_loan': '../reference/S-IPA-Workshop/workshop2/KIE-Loan-Application-WeChat/VA-KIE-Loan-Application.txt...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Retrieve rpa_bot_file based on received Chat-Bot command
# Retrieve rpa_bot_file based on received Chat-Bot command def didi_retrieve_rpa_bot_file(chat_bot_command): print('[ W I P ] Retrieve rpa_bot_file based on received Chat-Bot command : {} -> {}'.format( chat_bot_command, chat_bot_command.lower())) if chat_bot_command.lower() in parm_bot_intention_a...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
虚拟员工: 语音指令交互(Conversational automation using speech/voice command) <span style="color:blue">Use local AI module in native forms</span> for Speech Recognition: Speech-to-Text 导入需要用到的一些功能程序库: Local AI Module Speech-to-Text
# Local AI Module for Speech Synthesis: Speech-to-Text # Install library into computer storage: # !pip install SpeechRecognition # !pip install pocketsphinx # Load library into computer memory: import speech_recognition as sr
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
IF !pip install pocketsphinx failed, THEN: sudo apt-get install python python-dev python-pip build-essential swig libpulse-dev https://stackoverflow.com/questions/36523705/python-pocketsphinx-requesterror-missing-pocketsphinx-module-ensure-that-pocke Supported Languages https://github.com/Uberi/speech_recognition/blob/...
# Flag to indicate the environment to run this program: # Uncomment to run the code on Google Cloud Platform # parm_runtime_env_GCP = True # Uncomment to run the code in local machine parm_runtime_env_GCP = False import subprocess # Utility function to convert mp3 file to target GCP audio file type: # audio_type...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Calling Local AI Module: speech_recognition.Recognizer().recognize_sphinx()
# Running Local AI Module Speech-to-Text def didi_speech2text_local(AUDIO_FILE, didi_language_code='en-US'): # Python 2 # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # read the entire audio file trans...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Fuzzy match from 'transcribed audio command' to predefined 'chat_bot_command' Automatically create a new lookup, by converting text-based intention command to voice-based intention command. Example: from '#apply_loan' to 'voice command apply loan'
# import json # Prints the nicely formatted dictionary # print(json.dumps(parm_bot_intention_action, indent=4, sort_keys=True)) import re parm_bot_intention_action_fuzzy_match = {} for intention, action in parm_bot_intention_action.items(): # print(intention) intention_fuzzy_match = " ".join(re.split('#|_', in...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Fuzzy match function: Compare similarity between two text strings
# Compare similarity between two text strings def did_fuzzy_match_score(string1, string2): print('\n[ Inside FUNCTION ] did_fuzzy_match_score') string1_list = string1.lower().split() # split by space string2_list = string2.lower().split() # split by space print('string1_list : ', string1_list) p...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Retrieve rpa_bot_file based on received Chat-Bot command ( fuzzy match for voice/speech2text )
# Retrieve rpa_bot_file based on received Chat-Bot command ( fuzzy match for voice/speech2text ) def didi_retrieve_rpa_bot_file_fuzzy_match(speech2text_chat_bot_command, didi_confidence_threshold=0.8): print('\n[ Inside FUNCTION ] didi_retrieve_rpa_bot_file_fuzzy_match') matched_intention = [0.0, {}] # a lis to...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Control Parm
# Control of asynchronous or synchronous processing when triggering RPA-Bot parm_asynchronous_process = True # Control of asynchronous or synchronous processing when triggering RPA-Bot parm_voice_command_confidence_threshold = 0.05 # low value for demo only
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
<span style="color:blue">Start interactive conversational virtual assistant (VA):</span> Import ItChat, etc. 导入需要用到的一些功能程序库:
import itchat from itchat.content import *
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
Log in using QR code image / 用微信App扫QR码图片来自动登录
# Running in Jupyther Notebook: # itchat.auto_login(hotReload=True) # hotReload=True: 退出程序后暂存登陆状态。即使程序关闭,一定时间内重新开启也可以不用重新扫码。 # or # itchat.auto_login(enableCmdQR=-2) # enableCmdQR=-2: Jupyter Notebook 命令行显示QR图片 # Running in Terminal: itchat.auto_login(enableCmdQR=2) # enableCmdQR=2: 命令行显示QR图片
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
虚拟员工: 文字指令交互(Conversational automation using text/message command)
# Trigger RPA-Bot when command received / 如果收到[TEXT]的信息: @itchat.msg_register([TEXT]) # 文字 def didi_ipa_text_command(msg): global parm_msg parm_msg = msg if msg['Text'][0] == '#': # Retrieve rpa_bot_file based on received Chat-Bot command rpa_bot_file = didi_retrieve_rpa_bot_file( msg['Text'...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit
虚拟员工: 语音指令交互(Conversational automation using speech/voice command)
# 1. 语音转换成消息文字 (Speech recognition: voice to text) @itchat.msg_register([RECORDING], isGroupChat=True) @itchat.msg_register([RECORDING]) def download_files(msg): msg.download(msg.fileName) print('\nDownloaded audio file name is: %s' % msg['FileName']) #############################################...
wechat_tool_py3_local/terminal-script-py/lesson_6_terminal_py3.ipynb
telescopeuser/workshop_blog
mit