markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Como pueden ver, en la variable usos_suelo tenemos ya calculadas todas nuestras variables de interés, ahora lo que necesitamos es, para cada fila de nuestro GeoDataFrame, saber cuáles son los polígnos vecinos. Para esto, vamos a utilizar la librería PySal, que provee un conjunto de métodos de análisis espacial. En part...
import pysal w = pysal.weights.Queen.from_dataframe(usos_suelo) print(w.n) print(w.weights[0]) print(w.neighbors[0]) print(w.neighbors[5]) print(w.histogram)
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Lo primero que hicimos fue importar la librería PySal. A continuación, claculamos la matriz de pesos w usando vecindades de tipo Reina (en la documentación de PySal pueden consultar los diferentes tipos de vecindades y las fuentes de datos que pueden usar). w.n nos dice la cantidad de renglones de la matriz w.weights[...
freqs = pd.DataFrame(w.histogram, columns=['vecinos', 'cuenta']) freqs.head()
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Y luego lo graficamos:
%matplotlib inline import seaborn as sns sns.barplot(x='vecinos', y='cuenta', data=freqs)
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Intensidad Después de este intermedio, ahora sí vamos a hacer nuestro primer cómputo en vecindades. Vamos a comenzar por la intensidad. La intensidad es simplemente la cantidad de actividades en un área determinada. En nuestro caso, vamos a calcular el total de actividades (de cualquier tipo) que hay en la vecindad inm...
usos_suelo = usos_suelo.drop(usos_suelo.index[[1224]]) usos_suelo.reset_index(drop=True, inplace=True) w = pysal.weights.Queen.from_dataframe(usos_suelo)
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Ahora sí, recorremos la lista de vecinos y calculamos la intensidad para cada elemento:
usos_suelo.iloc[[0]][['clase_comercio', 'clase_ocio', 'clase_oficinas']].as_matrix() import numpy as np intensidad =[] for i in range(0, w.n): vecinos = w.neighbors[i] total = 0.0 suma = np.zeros((3),dtype=np.float) valores = usos_suelo.iloc[[i]][['clase_comercio', 'clase_ocio', 'clase_oficinas']].as_...
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Al parecer lo que estamos haciendo es muy complicado, sin embargo, una vez más, si lo vemos con detenimiento es relativamente simple: Primero estamos definiendo una lista vacía intensidad que nos va a servir para guardar los resultados Luego, en el for externo, estamos recorriendo la matriz de adyacencia, entonces el ...
intensidad_df = pd.DataFrame(intensidad, columns=['gid', 'intensidad']) datos_intensidad = usos_suelo.merge(intensidad_df, left_index=True, right_on='gid', how='inner') datos_intensidad.head()
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
Ejercicio Hagan un mapa que destaque las diferencias en intensidad. Entropía La entropía es una medida de la mezcla de usos de suelo, está basada en la forma en la que se calcula la entropía en mecánica estadística: $$ E = \sum\limits_{j}{\frac{p_{j}*ln(p_{j})}{ln(J)}} $$ Donde $p_{j}$ representa la proporción del $j-é...
entropia =[] for i in range(0, w.n): vecinos = w.neighbors[i] total = 0.0 suma = np.zeros((3),dtype=np.float) valores = usos_suelo.iloc[[i]][['clase_comercio', 'clase_ocio', 'clase_oficinas']].as_matrix() for j in range(0,len(vecinos)): data = usos_suelo.iloc[[j]][['clase_comercio', 'cla...
vecindades_python/vecindades_2.ipynb
CentroGeo/geoinformatica
gpl-3.0
We'll be running the provided LeNet example (make sure you've downloaded the data and created the databases, as below).
# Download and prepare data !data/mnist/get_mnist.sh !examples/mnist/create_mnist.sh
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
We need two external files to help out: * the net prototxt, defining the architecture and pointing to the train/test data * the solver prototxt, defining the learning parameters We start with the net. We'll write the net in a succinct and natural way as Python code that serializes to Caffe's protobuf model format. This...
from caffe import layers as L from caffe import params as P def lenet(lmdb, batch_size): # our version of LeNet: a series of linear and simple nonlinear transformations n = caffe.NetSpec() n.data, n.label = L.Data(batch_size=batch_size, backend=P.Data.LMDB, source=lmdb, transfo...
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
The net has been written to disk in more verbose but human-readable serialization format using Google's protobuf library. You can read, write, and modify this description directly. Let's take a look at the train net.
!cat examples/mnist/lenet_auto_train.prototxt
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Now let's see the learning parameters, which are also written as a prototxt file. We're using SGD with momentum, weight decay, and a specific learning rate schedule.
!cat examples/mnist/lenet_auto_solver.prototxt
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Let's pick a device and load the solver. We'll use SGD (with momentum), but Adagrad and Nesterov's accelerated gradient are also available.
caffe.set_device(0) caffe.set_mode_gpu() solver = caffe.SGDSolver('examples/mnist/lenet_auto_solver.prototxt')
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
To get an idea of the architecture of our net, we can check the dimensions of the intermediate features (blobs) and parameters (these will also be useful to refer to when manipulating data later).
# each output is (batch size, feature dim, spatial dim) [(k, v.data.shape) for k, v in solver.net.blobs.items()] # just print the weight sizes (not biases) [(k, v[0].data.shape) for k, v in solver.net.params.items()]
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Before taking off, let's check that everything is loaded as we expect. We'll run a forward pass on the train and test nets and check that they contain our data.
solver.net.forward() # train net solver.test_nets[0].forward() # test net (there can be more than one) # we use a little trick to tile the first eight images imshow(solver.net.blobs['data'].data[:8, 0].transpose(1, 0, 2).reshape(28, 8*28), cmap='gray') print solver.net.blobs['label'].data[:8] imshow(solver.test_net...
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Both train and test nets seem to be loading data, and to have correct labels. Let's take one step of (minibatch) SGD and see what happens.
solver.step(1)
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Do we have gradients propagating through our filters? Let's see the updates to the first layer, shown here as a $4 \times 5$ grid of $5 \times 5$ filters.
imshow(solver.net.params['conv1'][0].diff[:, 0].reshape(4, 5, 5, 5) .transpose(0, 2, 1, 3).reshape(4*5, 5*5), cmap='gray')
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Something is happening. Let's run the net for a while, keeping track of a few things as it goes. Note that this process will be the same as if training through the caffe binary. In particular: * logging will continue to happen as normal * snapshots will be taken at the interval specified in the solver prototxt (here, e...
%%time niter = 200 test_interval = 25 # losses will also be stored in the log train_loss = zeros(niter) test_acc = zeros(int(np.ceil(niter / test_interval))) output = zeros((niter, 8, 10)) # the main solver loop for it in range(niter): solver.step(1) # SGD by Caffe # store the train loss train_loss[i...
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
Let's plot the train loss and test accuracy.
_, ax1 = subplots() ax2 = ax1.twinx() ax1.plot(arange(niter), train_loss) ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r') ax1.set_xlabel('iteration') ax1.set_ylabel('train loss') ax2.set_ylabel('test accuracy')
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
The loss seems to have dropped quickly and coverged (except for stochasticity), while the accuracy rose correspondingly. Hooray! Since we saved the results on the first test batch, we can watch how our prediction scores evolved. We'll plot time on the $x$ axis and each possible label on the $y$, with lightness indicati...
for i in range(8): figure(figsize=(2, 2)) imshow(solver.test_nets[0].blobs['data'].data[i, 0], cmap='gray') figure(figsize=(10, 2)) imshow(output[:50, i].T, interpolation='nearest', cmap='gray') xlabel('iteration') ylabel('label')
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
We started with little idea about any of these digits, and ended up with correct classifications for each. If you've been following along, you'll see the last digit is the most difficult, a slanted "9" that's (understandably) most confused with "4". Note that these are the "raw" output scores rather than the softmax-co...
for i in range(8): figure(figsize=(2, 2)) imshow(solver.test_nets[0].blobs['data'].data[i, 0], cmap='gray') figure(figsize=(10, 2)) imshow(exp(output[:50, i].T) / exp(output[:50, i].T).sum(0), interpolation='nearest', cmap='gray') xlabel('iteration') ylabel('label')
examples/01-learning-lenet.ipynb
wangg12/caffe
bsd-2-clause
'y' is travel time in seconds. Extract Features Represent time as a decimal fraction of a day, so that we can more easily use it for prediction.
def frac_day(time): """ Convert time to fraction of a day (0.0 to 1.0) Can also pass this function a datetime object """ return time.hour*(1./24) + time.minute*(1./(24*60)) + time.second*(1./(24*60*60))
jupyter_notebooks/traveltime_lineartime.ipynb
anjsimmo/simple-ml-pipeline
mit
We create the features $time^1$, $time^2$, ... in order to allow the regression algorithm to find polynomial fits.
def extract_features(data): # Turn list into a n*1 design matrix. At this stage, we only have a single feature in each row. t = np.array([frac_day(_t) for _t in data['t']])[:, np.newaxis] # Add t^2, t^3, ... to allow polynomial regression xs = np.hstack([t, t**2, t**3, t**4, t**5, t**6, t**7, t**8]) ...
jupyter_notebooks/traveltime_lineartime.ipynb
anjsimmo/simple-ml-pipeline
mit
Model Train model, plot regression curve.
%matplotlib inline import matplotlib.pyplot as plt from sklearn import linear_model regr = linear_model.LinearRegression() regr.fit(xs, y) y_pred = regr.predict(xs) plt.figure(figsize=(8,8)) plt.scatter(t, y, color='black', label='actual') plt.plot(t, y_pred, color='blue', label='regression curve') plt.title("Travel...
jupyter_notebooks/traveltime_lineartime.ipynb
anjsimmo/simple-ml-pipeline
mit
Evaluate
test = datatables.traveltime.read('data/traveltime.task.test') # Traffic on Wed 27 Aug 2015 test_xs = extract_features(test) test['pred'] = regr.predict(test_xs) test['error'] = test['y'] - test['pred'] # todo: ensure data is a real number (complex numbers could be used to cheat) rms_error = math.sqrt(sum(test['error']...
jupyter_notebooks/traveltime_lineartime.ipynb
anjsimmo/simple-ml-pipeline
mit
Getting started with The Joker The Joker (pronounced Yo-kurr) is a highly specialized Monte Carlo (MC) sampler that is designed to generate converged posterior samplings for Keplerian orbital parameters, even when your data are sparse, non-uniform, or very noisy. This is not a general MC sampler, and this is not a Mark...
import astropy.table as at from astropy.time import Time import astropy.units as u from astropy.visualization.units import quantity_support import matplotlib.pyplot as plt import numpy as np %matplotlib inline import thejoker as tj # set up a random generator to ensure reproducibility rnd = np.random.default_rng(seed...
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Loading radial velocity data To start, we need some radial velocity data to play with. Our ultimate goal is to construct or read in a thejoker.RVData instance, which is the main data container object used in The Joker. For this tutorial, we will use a simulated RV curve that was generated using a separate script and sa...
data_tbl = at.QTable.read('data.ecsv') data_tbl[:2]
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
The full simulated data table has many rows (256), so let's randomly grab 4 rows to work with:
sub_tbl = data_tbl[rnd.choice(len(data_tbl), size=4, replace=False)] sub_tbl
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
It looks like the time column is given in Barycentric Julian Date (BJD), so in order to create an RVData instance, we will need to create an astropy.time.Time object from this column:
t = Time(sub_tbl['bjd'], format='jd', scale='tcb') data = tj.RVData(t=t, rv=sub_tbl['rv'], rv_err=sub_tbl['rv_err'])
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
We now have an RVData object, so we could continue on with the tutorial. But as a quick aside, there is an alternate, more automatic (automagical?) way to create an RVData instance from tabular data: RVData.guess_from_table. This classmethod attempts to guess the time format and radial velocity column names from the co...
data = tj.RVData.guess_from_table(sub_tbl)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
One of the handy features of RVData is the .plot() method, which generates a quick view of the data:
_ = data.plot()
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
The data are clearly variable! But what orbits are consistent with these data? I suspect many, given how sparse they are! Now that we have the data in hand, we need to set up the sampler by specifying prior distributions over the parameters in The Joker. Specifying the prior distributions for The Joker parameters The p...
prior = tj.JokerPrior.default( P_min=2*u.day, P_max=1e3*u.day, sigma_K0=30*u.km/u.s, sigma_v=100*u.km/u.s)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Once we have the prior instance, we need to generate some prior samples that we will then use The Joker to rejection sample down to a set of posterior samples. To generate prior samples, use the JokerSamples.sample() method. Here, we'll generate a lare number of samples to use:
prior_samples = prior.sample(size=250_000, random_state=rnd) prior_samples
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
This object behaves like a Python dictionary in that the parameter values can be accessed via their key names:
prior_samples['P'] prior_samples['e']
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
They can also be written to disk or re-loaded using this same class. For example, to save these prior samples to the current directory to the file "prior_samples.hdf5":
prior_samples.write("prior_samples.hdf5", overwrite=True)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
We could then load the samples from this file using:
tj.JokerSamples.read("prior_samples.hdf5")
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Running The Joker Now that we have a set of prior samples, we can create an instance of The Joker and use the rejection sampler:
joker = tj.TheJoker(prior, random_state=rnd) joker_samples = joker.rejection_sample(data, prior_samples, max_posterior_samples=256)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
This works by either passing in an instance of JokerSamples containing the prior samples, or by passing in a filename that contains JokerSamples written to disk. So, for example, this is equivalent:
joker_samples = joker.rejection_sample(data, "prior_samples.hdf5", max_posterior_samples=256)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
The max_posterior_samples argument above specifies the maximum number of posterior samples to return. It is often helpful to set a threshold here in cases when your data are very uninformative to avoid generating huge numbers of samples (which can slow down the sampler considerably). In either case above, the joker_sam...
joker_samples
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Plotting The Joker orbit samples over the input data With posterior samples in Keplerian orbital parameters in hand for our data set, we can now plot the posterior samples over the input data to get a sense for how constraining the data are. The Joker comes with a convenience plotting function, plot_rv_curves, for doin...
_ = tj.plot_rv_curves(joker_samples, data=data)
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
It has various options to allow customizing the style of the plot:
fig, ax = plt.subplots(1, 1, figsize=(8, 4)) _ = tj.plot_rv_curves(joker_samples, data=data, plot_kwargs=dict(color='tab:blue'), data_plot_kwargs=dict(color='tab:red'), relative_to_t_ref=True, ax=ax) ax.set_xlabel(f'BMJD$ - {data.t.tcb.mjd.min():.3f}$')
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Another way to visualize the samples is to plot 2D projections of the sample values, for example, to plot period against eccentricity:
fig, ax = plt.subplots(1, 1, figsize=(8, 5)) with quantity_support(): ax.scatter(joker_samples['P'], joker_samples['e'], s=20, lw=0, alpha=0.5) ax.set_xscale('log') ax.set_xlim(prior.pars['P'].distribution.a, prior.pars['P'].distribution.b) ax.set_ylim(0, 1) ax....
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
But is the true period value included in those distinct period modes returned by The Joker? When generating the simulated data, I also saved the true orbital parameters used to generate the data, so we can load and over-plot it:
import pickle with open('true-orbit.pkl', 'rb') as f: truth = pickle.load(f) fig, ax = plt.subplots(1, 1, figsize=(8, 5)) with quantity_support(): ax.scatter(joker_samples['P'], joker_samples['e'], s=20, lw=0, alpha=0.5) ax.axvline(truth['P'], zorder=-1, color='tab:gree...
docs/examples/1-Getting-started.ipynb
adrn/thejoker
mit
Review Inputs In addition to a working ActivitySim model setup, estimation mode requires an ActivitySim format household travel survey. An ActivitySim format household travel survey is very similar to ActivitySim's simulation model tables: households persons tours joint_tour_participants trips Examples of the Activ...
pd.read_csv("../data_sf/survey_data/override_households.csv")
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Survey persons
pd.read_csv("../data_sf/survey_data/override_persons.csv")
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Survey joint tour participants
pd.read_csv("../data_sf/survey_data/override_joint_tour_participants.csv")
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Survey tours
pd.read_csv("../data_sf/survey_data/override_tours.csv")
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Survey trips
pd.read_csv("../data_sf/survey_data/override_trips.csv")
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Example Setup if Needed To avoid duplication of inputs, especially model settings and expressions, the example_estimation depends on the example. The following commands create an example setup for use. The location of these example setups (i.e. the folders) are important because the paths are referenced in this noteb...
!activitysim create -e example_estimation_sf -d test
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
Run the Estimation Example The next step is to run the model with an estimation.yaml settings file with the following settings in order to output the EDB for all submodels: ``` enable=True bundles: - school_location - workplace_location - auto_ownership - free_parking - cdap - mandatory_tour_frequency - m...
%cd test !activitysim run -c configs_estimation/configs -c configs -o output -d data_sf
activitysim/examples/example_estimation/notebooks/01_estimation_mode.ipynb
synthicity/activitysim
agpl-3.0
What's going on in cells 11 & 14 ?
greet = functools.partial(hello_doctor) greet("Dr.Susan Calvin") welcome = functools.partial(hello_doctor) welcome("Dr.Susan Calvin") def numpower(base, exponent): return base ** exponent def square(base): return numpower(base, 2) def cube(base): return numpower(base, 3) print square(25) print cube...
functools_partial_usage.ipynb
mramanathan/pydiary_notes
gpl-3.0
In this chapter, we compare our PQk-means to k-means in the faiss library. Faiss provides one of the most efficient implementations of nearest neighbor algorithms for both CPU(s) and GPU(s). It also provides an implementation of vanilla k-means, which we will compare to. The core part of faiss is implemented by C++, an...
Xt, X = pqkmeans.evaluation.get_sift1m_dataset() # Xt: the training data. X: the testing data to be clusterd
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
First, you can download the data by a helper script. This would take several minutes, and consume 168 MB of the disk space.
Xt = Xt.astype(numpy.float32) X = X.astype(numpy.float32) D = X.shape[1] print("Xt.shape:{}\nX.shape:{}".format(Xt.shape, X.shape))
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Because faiss takes 32-bit float vectors as inputs, the data is converted to float32. 2. Small-scale comparison: N=10^5, K=10^3 (k-means with faiss-CPU v.s. k-means with sklearn) First, let us compare the k-means implementation of faiss and sklearn using 100K vectors from SIFT1M. Then we show that faiss is much faster ...
K_small = 1000 N_small = 100000 # Setup clustering instances. We stop each algorithm with 10 iterations kmeans_faiss_cpu_small = faiss.Kmeans(d=D, k=K_small, niter=10) kmeans_sklearn_small = KMeans(n_clusters=K_small, n_jobs=-1, max_iter=10)
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Let's run each algorithm
%%time print("faiss-cpu:") kmeans_faiss_cpu_small.train(X[:N_small]) _, ids_faiss_cpu_small = kmeans_faiss_cpu_small.index.search(X[:N_small], 1) %%time print("sklearn:") ids_sklearn_small = kmeans_sklearn_small.fit_predict(X[:N_small]) _, faiss_cpu_small_error, _ = pqkmeans.evaluation.calc_error(ids_faiss_cpu_small....
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
We observed that - k-means with faiss-CPU (2 sec) is surprisingly faster than k-means with sklearn (3 min) with almost the same error. This speedup would be due to the highly optimized implementation of the nearest neighbor search in faiss with Intel MKL BLAS. This suggests that faiss-CPU is a better option for the exa...
# Setup GPUs for faiss-gpu # In my environment, the first GPU (id=0) is for rendering, and the second (id=1) and the third (id=2) GPUs are GPGPU (GTX1080). # We activate only the second and the third GPU import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # make sure the order is identical to the result of nvidia...
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Next, let us compare PQk-meas with faiss-CPU and faiss-GPU using the whole dataset (N=10^6, K=10^4). Note that this is 100x larter setting compared to Sec 2 (NK=10^8 vs NK=10^10). First, as pre-processing for PQk-means, let's train a PQencoder and encode all data. It will take around 10 sec.
%%time # Train the encoder encoder = pqkmeans.encoder.PQEncoder(num_subdim=4, Ks=256) encoder.fit(Xt) # Encode the vectors to PQ-codes X_code = encoder.transform(X)
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Note that X_code is 128x more memory efficient than X:
print("X.shape: {}, X.dtype: {}, X.nbytes: {} MB".format(X.shape, X.dtype, X.nbytes / 10**6)) print("X_code.shape: {}, X_code.dtype: {}, X_code.nbytes: {} MB".format(X_code.shape, X_code.dtype, X_code.nbytes / 10**6))
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Then each algorithms are instantiated as follows
K = 10000 # Set larger K # Setup k-means instances. The number of iteration is set as 20 for all methods # PQ-kmeans kmeans_pqkmeans = pqkmeans.clustering.PQKMeans(encoder=encoder, k=K, iteration=20) # Faiss-cpu kmeans_faiss_cpu = faiss.Kmeans(d=D, k=K, niter=20) kmeans_faiss_cpu.cp.max_points_per_centroid = 100000...
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Because some configurations are required for GPU, we wrap up the gpu clustering as one function:
def run_faiss_gpu(X, K, ngpu): # This code is based on https://github.com/facebookresearch/faiss/blob/master/benchs/kmeans_mnist.py D = X.shape[1] clus = faiss.Clustering(D, K) # otherwise the kmeans implementation sub-samples the training set clus.max_points_per_centroid = 10000000 ...
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Run each method and see the computational cost.
%%time print("PQk-means:") ids_pqkmeans = kmeans_pqkmeans.fit_predict(X_code) %%time print("faiss-cpu:") kmeans_faiss_cpu.train(X) _, ids_faiss_cpu = kmeans_faiss_cpu.index.search(X, 1) %%time print("faiss with GPU:") ids_faiss_gpu = run_faiss_gpu(X, K, ngpu=2) # Please adjust ngpu for your environment _, pqkmeans_e...
tutorial/4_comparison_to_faiss.ipynb
DwangoMediaVillage/pqkmeans
mit
Of course, we need a better way to figure out how well we’ve fit the data than staring at the graph. A common measure is the coefficient of determination (or R-squared), which measures the fraction of the total variation in the dependent variable that is captured by the model. Multiple Regression using Matrix Method M...
# https://github.com/computational-class/machinelearninginaction/blob/master/Ch08/regression.py import pandas as pd import random dat = pd.read_csv('../data/ex0.txt', sep = '\t', names = ['x1', 'x2', 'y']) dat['x3'] = [yi*.3 + .5*random.random() for yi in dat['y']] dat.head() from numpy import mat, linalg, corrcoef ...
code/08.06-regression.ipynb
computational-class/cjc2016
mit
Doing Statistics with statsmodels http://www.statsmodels.org/stable/index.html statsmodels is a Python module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration.
import statsmodels.api as sm import statsmodels.formula.api as smf dat = pd.read_csv('ex0.txt', sep = '\t', names = ['x1', 'x2', 'y']) dat['x3'] = [yi*.3 - .1*random.random() for yi in y] dat.head() results = smf.ols('y ~ x2 + x3', data=dat).fit() results.summary() fig = plt.figure(figsize=(12,8)) fig = sm.graphics...
code/08.06-regression.ipynb
computational-class/cjc2016
mit
Resit Assignment part A Deadline: Friday, November 13, 2020 before 17:00 Please name your files: ASSIGNMENT-RESIT-A.ipynb utils.py (from part B) raw_text_to_coll.py (from part B) Please name your zip file as follows: RESIT-ASSIGNMENT.zip and upload it via Canvas (Resit Assignment). - Please submit your assignmen...
import spacy
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Please make sure you can load the English spaCy model:
nlp = spacy.load('en_core_web_sm')
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 1: get paths Define a function called get_paths that has the following parameter: * input_folder: a string The function: * stores all paths to .txt files in the input_folder in a list * returns a list of strings, i.e., each string is a file path
# your code here
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Please test your function using the following function call
paths = get_paths(input_folder='../Data/Dreams') print(paths)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 2: load text Define a function called load_text that has the following parameter: * txt_path: a string The function: * opens the txt_path for reading and loads the contents of the file as a string * returns a string, i.e., the content of the file
# your code here
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 3: return the longest Define a function called return_the_longest that has the following parameter: * list_of_strings: a list of strings The function: * returns the string with the highest number of characters. If multiple strings have the same length, return one of them.
def return_the_longest(list_of_strings): """ given a list of strings, return the longest string if multiple strings have the same length, return one of them. :param str list_of_strings: a list of strings """
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Please test you function by running the following cell:
a_list_of_strings = ["this", "is", "a", "sentence"] longest_string = return_the_longest(a_list_of_strings) error_message = f'the longest string should be "sentence", you provided {longest_string}' assert longest_string == 'sentence', error_message
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 4: extract statistics We are going to use spaCy to extract statistics from Vickie's dreams! Here are a few tips below about how to use spaCy: tip 1: process text with spaCy
a_text = 'this is one sentence. this is another.' doc = nlp(a_text)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
tip 2: the number of characters is the length of the document
num_chars = len(doc.text) print(num_chars)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
tip 3: loop through the sentences of a document
for sent in doc.sents: sent = sent.text print(sent)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
tip 4: loop through the words of a document
for token in doc: word = token.text print(word)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Define a function called extract_statistics that has the following parameters: * nlp: the result of calling spacy.load('en_core_web_sm') * txt_path: path to a txt file, e.g., '../Data/Dreams/vickie8.txt' The function: * loads the content of the file using the function load_text * processes the content of the file usin...
def extract_statistics(nlp, txt_path): """ given a txt_path -use the load_text function to load the text -process the text using spaCy :param nlp: loaded spaCy model (result of calling spacy.load('en_core_web_sm')) :param str txt_path: path to txt file :rtype: dict :return: a d...
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 5: process all txt files tip 1: how to obtain the basename of a file
import os basename = os.path.basename('../Data/Dreams/vickie1.txt')[:-4] print(basename)
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Define a function called process_all_txt_files that has the following parameters: * nlp: the result of calling spacy.load('en_core_web_sm') * input_folder: a string (we will test it using '../Data/Dreams') The function: * obtains a list of txt paths using the function get_paths with input_folder as an argument * loops...
def process_all_txt_files(nlp, input_folder): """ given a list of txt_paths -process each with the extract_statistics function :param nlp: loaded spaCy model (result of calling spacy.load('en_core_web_sm')) :param list txt_paths: list of paths to txt files :rtype: dict :return: dic...
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
Exercise 6: write to disk In this exercise, you are going to write our results to our computer. Please loop through basename_to_stats and create one JSON file for each dream. the path is f'{basename}.json', i.e., 'vickie1.json', 'vickie2.json', etc. (please write them to the same folder as this notebook) the content o...
import json for basename, stats in basename_to_stats.items(): pass
Assignments-colab/ASSIGNMENT_RESIT_A.ipynb
evanmiltenburg/python-for-text-analysis
apache-2.0
The result is a NumPy Record Array where the fields of the array correspond to the properties of a VesselTubeSpatialObjectPoint.
print(type(tubes)) print(tubes.dtype)
examples/TubeNumPyArrayAndPropertyHistograms.ipynb
KitwareMedical/ITKTubeTK
apache-2.0
The length of the array corresponds to the number of points that make up the tubes.
print(len(tubes)) print(tubes.shape)
examples/TubeNumPyArrayAndPropertyHistograms.ipynb
KitwareMedical/ITKTubeTK
apache-2.0
Individual points can be sliced, or views can be created on individual fields.
print('Entire points 0, 2:') print(tubes[:4:2]) print('\nPosition of points 0, 2') print(tubes['PositionInWorldSpace'][:4:2])
examples/TubeNumPyArrayAndPropertyHistograms.ipynb
KitwareMedical/ITKTubeTK
apache-2.0
We can easily create a histogram of the radii or visualize the point positions.
%pylab inline from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure(figsize=(16, 6)) ax = fig.add_subplot(1, 2, 1) ax.hist(tubes['RadiusInWorldSpace'], bins=100) ax.set_xlabel('Radius') ax.set_ylabel('Count') ax = fig.add_subplot(1, 2, 2, projection='3d') subsample = 100 position =...
examples/TubeNumPyArrayAndPropertyHistograms.ipynb
KitwareMedical/ITKTubeTK
apache-2.0
Finally, let's code the models! The tf.keras API accepts an array of layers into a model object, so we can create a dictionary of layers based on the different model types we want to use. The below file has two functions: get_layers and create_and_train_model. We will build the structure of our model in get_layers. Las...
%%writefile mnist_models/trainer/model.py import os import shutil import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import ( Conv2D, Dense, Dropout, Flatten, MaxPooling2D...
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Now that we know that our models are working as expected, let's run it on the Google Cloud AI Platform. We can run it as a python module locally first using the command line. The below cell transfers some of our variables to the command line as well as create a job directory including a timestamp. This is where our mod...
current_time = datetime.now().strftime("%y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "mnist_models/models/{}_{}/".format( model_type, current_time)
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Training on the cloud Since we're using an unreleased version of TensorFlow on AI Platform, we can instead use a Deep Learning Container in order to take advantage of libraries and applications not normally packaged with AI Platform. Below is a simple Dockerlife which copies our code to be used in a TF2 environment.
%%writefile mnist_models/Dockerfile FROM gcr.io/deeplearning-platform-release/tf2-cpu COPY mnist_models/trainer /mnist_models/trainer ENTRYPOINT ["python3", "-m", "mnist_models.trainer.task"]
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Finally, we can kickoff the AI Platform training job. We can pass in our docker image using the master-image-uri flag.
current_time = datetime.now().strftime("%y%m%d_%H%M%S") model_type = 'cnn' os.environ["MODEL_TYPE"] = model_type os.environ["JOB_DIR"] = "gs://{}/mnist_{}_{}/".format( BUCKET, model_type, current_time) os.environ["JOB_NAME"] = "mnist_{}_{}".format( model_type, current_time) %%bash echo $JOB_DIR $REGION $JOB_N...
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Can't wait to see the results? Run the code below and copy the output into the Google Cloud Shell to follow along with TensorBoard. Look at the web preview on port 6006.
!echo "tensorboard --logdir $JOB_DIR"
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Deploying and predicting with model Once you have a model you're proud of, let's deploy it! All we need to do is give AI Platform the location of the model. Below uses the keras export path of the previous job, but ${JOB_DIR}keras_export/ can always be changed to a different path. Even though we're using a 1.14 runtime...
%%bash MODEL_NAME="mnist" MODEL_VERSION=${MODEL_TYPE} MODEL_LOCATION=${JOB_DIR}keras_export/ echo "Deleting and deploying $MODEL_NAME $MODEL_VERSION from $MODEL_LOCATION ... this will take a few minutes" #yes | gcloud ai-platform versions delete ${MODEL_VERSION} --model ${MODEL_NAME} #yes | gcloud ai-platform models de...
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
To predict with the model, let's take one of the example images. TODO 4: Write a .json file with image data to send to an AI Platform deployed model
import json, codecs import tensorflow as tf import matplotlib.pyplot as plt from mnist_models.trainer import util HEIGHT = 28 WIDTH = 28 IMGNO = 12 mnist = tf.keras.datasets.mnist.load_data() (x_train, y_train), (x_test, y_test) = mnist test_image = x_test[IMGNO] jsondata = test_image.reshape(HEIGHT, WIDTH, 1).tolis...
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Finally, we can send it to the prediction service. The output will have a 1 in the index of the corresponding digit it is predicting. Congrats! You've completed the lab!
%%bash gcloud ai-platform predict \ --model=mnist \ --version=${MODEL_TYPE} \ --json-instances=./test.json
courses/machine_learning/deepdive2/image_classification/labs/2_mnist_models.ipynb
turbomanage/training-data-analyst
apache-2.0
Otto Product Classification Data Training and test data is available here. Go ahead and download the data. Inspecting it, you will see that the provided csv files consist of an id column, 93 integer feature columns. train.csv has an additional column for labels, which test.csv is missing. The challenge is to accurately...
data_path = "./" # <-- Make sure to adapt this to where your csv files are.
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Loading data is relatively simple, but we have to take care of a few things. First, while you can shuffle rows of an RDD, it is generally not very efficient. But since data in train.csv is sorted by category, we'll have to shuffle in order to make the model perform well. This is what the function shuffle_csv below is ...
from pyspark.sql import SQLContext from pyspark.ml.linalg import Vectors import numpy as np import random sql_context = SQLContext(sc) def shuffle_csv(csv_file): lines = open(csv_file).readlines() random.shuffle(lines) open(csv_file, 'w').writelines(lines) def load_data_frame(csv_file, shuffle=True, trai...
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Let's load both train and test data and print a few rows of data using the convenient show method.
train_df = load_data_frame("train.csv") test_df = load_data_frame("test.csv", shuffle=False, train=False) # No need to shuffle test data print("Train data frame:") train_df.show(10) print("Test data frame (note the dummy category):") test_df.show(10)
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Preprocessing: Defining Transformers Up until now, we basically just read in raw data. Luckily, Spark ML has quite a few preprocessing features available, so the only thing we will ever have to do is define transformations of data frames. To proceed, we will first transform category strings to double values. This is do...
from pyspark.ml.feature import StringIndexer string_indexer = StringIndexer(inputCol="category", outputCol="index_category") fitted_indexer = string_indexer.fit(train_df) indexed_df = fitted_indexer.transform(train_df)
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Next, it's good practice to normalize the features, which is done with a StandardScaler.
from pyspark.ml.feature import StandardScaler scaler = StandardScaler(inputCol="features", outputCol="scaled_features", withStd=True, withMean=True) fitted_scaler = scaler.fit(indexed_df) scaled_df = fitted_scaler.transform(indexed_df) print("The result of indexing and scaling. Each transformation adds new columns to...
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Keras Deep Learning model Now that we have a data frame with processed features and labels, let's define a deep neural net that we can use to address the classification problem. Chances are you came here because you know a thing or two about deep learning. If so, the model below will look very straightforward to you. W...
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation from tensorflow.keras.utils import to_categorical, generic_utils nb_classes = train_df.select("category").distinct().count() input_dim = len(train_df.select("features").first()[0]) model = Sequential() model....
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Distributed Elephas model To lift the above Keras model to Spark, we define an Estimator on top of it. An Estimator is Spark's incarnation of a model that still has to be trained. It essentially only comes with only a single (required) method, namely fit. Once we call fit on a data frame, we get back a Model, which is ...
from elephas.ml_model import ElephasEstimator from tensorflow.keras import optimizers adam = optimizers.Adam(lr=0.01) opt_conf = optimizers.serialize(adam) # Initialize SparkML Estimator and set all relevant properties estimator = ElephasEstimator() estimator.setFeaturesCol("scaled_features") # These two...
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
SparkML Pipelines Now for the easy part: Defining pipelines is really as easy as listing pipeline stages. We can provide any configuration of Transformers and Estimators really, but here we simply take the three components defined earlier. Note that string_indexer and scaler and interchangable, while estimator somewhat...
from pyspark.ml import Pipeline pipeline = Pipeline(stages=[string_indexer, scaler, estimator])
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Fitting and evaluating the pipeline The last step now is to fit the pipeline on training data and evaluate it. We evaluate, i.e. transform, on training data, since only in that case do we have labels to check accuracy of the model. If you like, you could transform the test_df as well.
from pyspark.mllib.evaluation import MulticlassMetrics fitted_pipeline = pipeline.fit(train_df) # Fit model to data prediction = fitted_pipeline.transform(train_df) # Evaluate on train data. # prediction = fitted_pipeline.transform(test_df) # <-- The same code evaluates test data. pnl = prediction.select("index_categ...
examples/Spark_ML_Pipeline.ipynb
maxpumperla/elephas
mit
Load an interaction history
history_path = os.path.join('data', 'assistments_2009_2010.pkl') with open(history_path, 'rb') as f: history = pickle.load(f) df = history.data
nb/model_explorations.ipynb
rddy/lentil
apache-2.0
Train an embedding model on the interaction history and visualize the results
embedding_dimension = 2 model = models.EmbeddingModel( history, embedding_dimension, using_prereqs=True, using_lessons=True, using_bias=True, learning_update_variance_constant=0.5) estimator = est.EmbeddingMAPEstimator( regularization_constant=1e-3, using_scipy=True, verify_gradie...
nb/model_explorations.ipynb
rddy/lentil
apache-2.0