markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Model evaluation
Calculate the F1 score given the target vector and the model output. | def calculate_f1_score(y_test, y_output):
print 'Calculating F1 score'
tags = ['part-time-job', 'full-time-job', 'hourly-wage', 'salary', 'associate-needed', 'bs-degree-needed',
'ms-or-phd-needed', 'licence-needed', '1-year-experience-needed', '2-4-years-experience-needed',
'5-plus-... | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Evaluate model with 5-fold cross-validation using the F1 score metric: | from sklearn.model_selection import KFold
from sklearn.metrics import f1_score
scores = []
k_fold = KFold(n_splits=5)
for i, (train, validation) in enumerate(k_fold.split(X)):
X_train, X_validation, y_train, y_validation = X[train], X[validation], y[train], y[validation]
fit_models(models, X_preprocessor, y_... | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Model usage
Load the data: | def load_test_data(filename):
with open(filename) as fd:
reader = csv.reader(fd, delimiter='\t')
next(reader, None) # ignore header row
X = [row[0] for row in reader]
return np.array(X)
X_train, y_train = load_train_data('data/train.tsv')
X_test = load_test_data('data/test.tsv') | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Train the model with all training data: | fit_models(models, X_preprocessor, y_preprocessors, X_train, y_train) | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Predict output from test data: | y_output = predict_models(models, X_preprocessor, y_preprocessors, X_test) | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Show some output data: | print y_output[:10] | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Save output data: | def save_output(filename, output):
with open(filename, 'w') as fd:
fd.write('tags\n')
for i, tags in enumerate(output):
fd.write(' '.join(tags))
fd.write('\n')
save_output('data/tags.tsv', y_output) | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Save preprocessors and model: | import pickle
def save(filename, obj):
pickle.dump(obj, open(filename, 'w'))
save('models/X_preprocessor.pickle', X_preprocessor)
save('models/y_preprocessor.pickle', y_preprocessors)
save('models/clf_{0:.3f}_f1_score.pickle'.format(f1_score), models) | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Load saved model | def load(filename):
return pickle.load(open(filename))
models = load('models/clf_0.461_f1_score.pickle')
X_preprocessors = load('models/X_preprocessor.pickle')
y_preprocessors = load('models/y_preprocessor.pickle') | indeed.ipynb | matheusportela/indeed-ml-codesprint | mit |
Create an independence bivariate copula | pv.Bicop() | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Create a Gaussian copula
See help(pv.BicopFamily) for the available families | pv.Bicop(family=pv.BicopFamily.gaussian) | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Create a 90 degrees rotated Clayon copula with parameter = 3 | pv.Bicop(family=pv.BicopFamily.clayton, rotation=90, parameters=[3]) | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Create a t copula with correlation of 0.5 and 4 degrees of freedom
and showcase some methods | cop = pv.Bicop(family=pv.BicopFamily.student, rotation=0, parameters=[0.5, 4])
u = cop.simulate(n=10, seeds=[1, 2, 3])
fcts = [cop.pdf, cop.cdf,
cop.hfunc1, cop.hfunc2,
cop.hinv1, cop.hinv2,
cop.loglik, cop.aic, cop.bic]
[f(u) for f in fcts] | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Different ways to fit a copula... | u = cop.simulate(n=1000, seeds=[1, 2, 3])
# Create a new object an sets its parameters by fitting afterwards
cop2 = pv.Bicop(pv.BicopFamily.student)
cop2.fit(data=u)
print(cop2)
# Otherwise, define first an object to control the fits:
# - pv.FitControlsBicop objects store the controls
# - here, we only restrict... | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Similarly, when the family is unkown,
there are two ways to also do model selection... | # Create a new object an selects both its family and parameters afterwards
cop3 = pv.Bicop()
cop3.select(data=u)
print(cop3)
# Or create directly from data
cop3 = pv.Bicop(data=u)
print(cop3) | examples/bivariate_copulas.ipynb | vinecopulib/pyvinecopulib | mit |
Neutral atom device class
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://quantumai.google/cirq/tutorials/educators/neutral_atom"><img src="https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png" />View on QuantumAI</a>
</td>
<td>
<a target="_blan... | try:
import cirq
except ImportError:
print("installing cirq...")
!pip install cirq --quiet
import cirq
print("installed cirq.")
from math import pi | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Defining a NeutralAtomDevice
To define a NeutralAtomDevice, we specify
The set of qubits in the device.
The maximum duration of gates and measurements.
max_parallel_z: The maximum number of single qubit $Z$ rotations that can be applied in parallel.
max_parallel_xy: The maximum number of single qubit $XY$ rotations th... | """Defining a NeutralAtomDevice."""
# Define milliseconds and microseconds for convenience.
ms = cirq.Duration(nanos=10**6)
us = cirq.Duration(nanos=10**3)
# Create a NeutralAtomDevice
neutral_atom_device = cirq.NeutralAtomDevice(
qubits=cirq.GridQubit.rect(2, 3),
measurement_duration=5 * ms,
gate_duration... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Note that all above arguments are required to instantiate a NeutralAtomDevice. The example device above has the following properties:
The device is defined on a $3 \times 3$ grid of qubits.
Measurements take $5$ milliseconds.
Gates may take as long as $100$ microseconds if we utilize global microwave gates. Otherwise,... | """View some properties of the device."""
# Display the neutral atom device.
print("Neutral atom device:", neutral_atom_device, sep="\n")
# Get the neighbors of a qubit.
qubit = cirq.GridQubit(0, 1)
print(f"\nNeighbors of qubit {qubit}:")
print(neutral_atom_device.neighbors_of(qubit)) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Native gate set
The gates supported by the NeutralAtomDevice class can be placed into three categories:
Single-qubit rotations about the $Z$ axis.
Single-qubit rotations about an arbitrary axis in the $X$-$Y$ plane. We refer to these as $XY$ gates in this tutorial.
Controlled gates: CZ, CNOT, CCZ, and CCNOT (TOFFOLI).... | # Examine metadata gateset info.
for gate_family in neutral_atom_device.metadata.gateset.gates:
print(gate_family)
print('-' * 80)
"""Examples of valid single-qubit gates."""
# Single qubit Z rotations with any angle are valid.
neutral_atom_device.validate_gate(cirq.rz(pi / 5))
# Single qubit rotations about the ... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
A Hadamard gate is invalid because it is a rotation in the $X$-$Z$ plane instead of the $X$-$Y$ plane. | """Example of an invalid single-qubit gate."""
invalid_gate = cirq.H
try:
neutral_atom_device.validate_gate(invalid_gate)
except ValueError as e:
print(f"As expected, {invalid_gate} is invalid!", e) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
For controlled gates, the rotation must be a multiple of $\pi$ due to the physical implementation of the gates. In Cirq, this means the exponent of a controlled gate must be an integer. The next cell shows two examples of valid controlled gates. | """Examples of valid multi-qubit gates."""
# Controlled gates with integer exponents are valid.
neutral_atom_device.validate_gate(cirq.CNOT)
# Controlled NOT gates with two controls are valid.
neutral_atom_device.validate_gate(cirq.TOFFOLI) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Any controlled gate with non-integer exponent is invalid. | """Example of an invalid controlled gate."""
invalid_gate = cirq.CNOT ** 1.5
try:
neutral_atom_device.validate_gate(invalid_gate)
except ValueError as e:
print(f"As expected, {invalid_gate} is invalid!", e) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Multiple controls are allowed as long as every pair of atoms (qubits) acted on by the controlled gate are close enough to each other. We can see this by using the validate_operation (or validate_circuit) method, as follows. | """Examples of valid and invalid multi-controlled gates."""
# This TOFFOLI is valid because all qubits involved are close enough to each other.
valid_toffoli = cirq.TOFFOLI.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2))
neutral_atom_device.validate_operation(valid_toffoli)
# This TOFFOLI is inval... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
NeutralAtomDevices do not currently support gates with more than two controls although these are in principle allowed by the physical realizations. | """Any gate with more than two controls is invalid."""
invalid_gate = cirq.ControlledGate(cirq.TOFFOLI)
try:
neutral_atom_device.validate_gate(invalid_gate)
except ValueError as e:
print(f"As expected, {invalid_gate} is invalid!", e) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Finally, we note that the duration of any operation can be determined via the duration_of method. | """Example of getting the duration of a valid operation."""
neutral_atom_device.duration_of(valid_toffoli) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Moment and circuit rules
In addition to consisting of valid operations as discussed above, valid moments on a NeutralAtomDevice must satisfy the following criteria:
Only max_parallel_c gates of the same category may be performed in the same moment.
All instances of gates in the same category in the same moment must be... | """Example of a valid moment with single qubit gates."""
qubits = sorted(neutral_atom_device.qubits)
# Get a valid moment.
valid_moment = cirq.Moment(cirq.Z.on_each(qubits[:3]) + cirq.X.on_each(qubits[3:6]))
# Display it.
print("Example of a valid moment with single-qubit gates:", cirq.Circuit(valid_moment), sep="\n\... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Recall that we defined max_parallel_z = 3 in our device. Thus, if we tried to do 4 $Z$ gates in the same moment, this would be invalid. | """Example of an invalid moment with single qubit gates."""
# Get an invalid moment.
invalid_moment = cirq.Moment(cirq.Z.on_each(qubits[:4]))
# Display it.
print("Example of an invalid moment with single-qubit gates:", cirq.Circuit(invalid_moment), sep="\n\n")
# Uncommenting raises ValueError: Too many simultaneous Z... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
This is also true for 4 $XY$ gates since we set max_parallel_xy = 3. However, there is an exception for $XY$ gates acting on every qubit, as illustrated below. | """An XY gate can be performed on every qubit in the device simultaneously.
If the XY gate does not act on every qubit, it must act on <= max_parallel_xy qubits.
"""
valid_moment = cirq.Moment(cirq.X.on_each(qubits))
neutral_atom_device.validate_moment(valid_moment) | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Although both $Z$ and $Z^{1.5}$ are valid gates, they cannot be performed simultaneously because all gates "of the same type" must be identical in the same moment. | """Example of an invalid moment with single qubit gates."""
# Get an invalid moment.
invalid_moment = cirq.Moment(cirq.Z(qubits[0]), cirq.Z(qubits[1]) ** 1.5)
# Display it.
print("Example of an invalid moment with single-qubit gates:", cirq.Circuit(invalid_moment), sep="\n\n")
# Uncommenting raises ValueError: Non-id... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Exercise: Multiple controlled gates in the same moment
Construct a NeutralAtomDevice which is capable of implementing two CNOTs in the same moment. Verify that these operations can indeed be performed in parallel by calling the validate_moment method or showing that Cirq inserts the operations into the same moment. | # Your code here! | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Solution | """Example solution for creating a device which allows two CNOTs in the same moment."""
# Create a NeutralAtomDevice.
device = cirq.NeutralAtomDevice(
qubits=cirq.GridQubit.rect(2, 3),
measurement_duration=5 * cirq.Duration(nanos=10**6),
gate_duration=100 * cirq.Duration(nanos=10**3),
max_parallel_z=4,
... | docs/tutorials/educators/neutral_atom.ipynb | quantumlib/Cirq | apache-2.0 |
Built-in dataset modules
Some dataset format is already implemented in chainer.datasets
TupleDataset | from chainer.datasets import TupleDataset
x = np.arange(10)
t = x * x
data = TupleDataset(x, t)
print('data type: {}, len: {}'.format(type(data), len(data)))
# Unlike numpy, it does not have shape property.
data.shape | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
i-th data can be accessed by data[i]
which is a tuple of format ($x_i$, $t_i$, ...) | # get forth data -> x=3, t=9
data[3] | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
Slice accessing
When TupleDataset is accessed by slice indexing, e.g. data[i:j], returned value is list of tuple
$[(x_i, t_i), ..., (x_{j-1}, t_{j-1})]$ | # Get 1st, 2nd, 3rd data at the same time.
examples = data[0:4]
print(examples)
print('examples type: {}, len: {}'
.format(type(examples), len(examples))) | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
To convert examples into minibatch format, you can use concat_examples function in chainer.dataset.
Its return value is in format ([x_array], [t array], ...) | from chainer.dataset import concat_examples
data_minibatch = concat_examples(examples)
#print(data_minibatch)
#print('data_minibatch type: {}, len: {}'
# .format(type(data_minibatch), len(data_minibatch)))
x_minibatch, t_minibatch = data_minibatch
# Now it is array format, which has shape
print('x_minibatch = {... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
DictDataset
TBD | from chainer.datasets import DictDataset
x = np.arange(10)
t = x * x
# To construct `DictDataset`, you can specify each key-value pair by passing "key=value" in kwargs.
data = DictDataset(x=x, t=t)
print('data type: {}, len: {}'.format(type(data), len(data)))
# Get 3rd data at the same time.
example = data[2]
... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
ImageDataset
This is util class for image dataset.
If the number of dataset becomes very big (for example ImageNet dataset),
it is not practical to load all the images into memory unlike CIFAR-10 or CIFAR-100.
In this case, ImageDataset class can be used to open image from storage everytime of minibatch creation.
[Not... | import os
from chainer.datasets import ImageDataset
# print('Current direcotory: ', os.path.abspath(os.curdir))
filepath = './data/images.dat'
image_dataset = ImageDataset(filepath, root='./data/images')
print('image_dataset type: {}, len: {}'.format(type(image_dataset), len(image_dataset))) | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
We have created the image_dataset above, however, images are not expanded into memory yet.
Image data will be loaded into memory from storage every time when you access via index, for efficient memory use. | # Access i-th image by image_dataset[i].
# image data is loaded here. for only 0-th image.
img = image_dataset[0]
# img is numpy array, already aligned as (channels, height, width),
# which is the standard shape format to feed into convolutional layer.
print('img', type(img), img.shape) | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
LabeledImageDataset
This is util class for image dataset.
It is similar to ImageDataset to allow load the image file from storage into memory at runtime of training.
The difference is that it contains label information, which is usually used for image classification task.
You need to create a text file which contains t... | import os
from chainer.datasets import LabeledImageDataset
# print('Current direcotory: ', os.path.abspath(os.curdir))
filepath = './data/images_labels.dat'
labeled_image_dataset = LabeledImageDataset(filepath, root='./data/images')
print('labeled_image_dataset type: {}, len: {}'.format(type(labeled_image_dataset),... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
We have created the labeled_image_dataset above, however, images are not expanded into memory yet.
Image data will be loaded into memory from storage every time when you access via index, for efficient memory use. | # Access i-th image and label by image_dataset[i].
# image data is loaded here. for only 0-th image.
img, label = labeled_image_dataset[0]
print('img', type(img), img.shape)
print('label', type(label), label) | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
SubDataset
TBD
It can be used for cross validation. | datasets.split_dataset_n_random() | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
Implement your own custom dataset
You can define your own dataset by implementing a sub class of DatasetMixin in chainer.dataset
DatasetMixin
If you want to define custom dataset, DatasetMixin provides the base function to make compatible with other dataset format.
Another important usage for DatasetMixin is to preproc... | from chainer.dataset import DatasetMixin
print_debug = True
class SimpleDataset(DatasetMixin):
def __init__(self, values):
self.values = values
def __len__(self):
return len(self.values)
def get_example(self, i):
if print_debug:
print('get_example, i = {}'.fo... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
Important function in DatasetMixin is get_examples(self, i) function.
This function is called when they access data[i] | simple_data = SimpleDataset([0, 1, 4, 9, 16, 25])
# get_example(self, i) is called when data is accessed by data[i]
simple_data[3]
# data can be accessed using slice indexing as well
simple_data[1:3] | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
The important point is that get_example function is called every time when the data is accessed by [] indexing.
Thus you may put random value generation for data augmentation code in get_example. | import numpy as np
from chainer.dataset import DatasetMixin
print_debug = False
def calc(x):
return x * x
class SquareNoiseDataset(DatasetMixin):
def __init__(self, values):
self.values = values
def __len__(self):
return len(self.values)
def get_example(self, i):
i... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
Below SimpleNoiseDataset adds small Gaussian noise to the original value,
and every time the value is accessed, get_example is called and differenct noise is added even if you access to the data with same index. | # Accessing to the same index, but the value is different!
print('Accessing square_noise_data[3]', )
print('1st: ', square_noise_data[3])
print('2nd: ', square_noise_data[3])
print('3rd: ', square_noise_data[3])
# Same applies for slice index accessing.
print('Accessing square_noise_data[0:4]')
print('1st: ', square_n... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
To convert examples into minibatch format, you can use concat_examples function in chainer.dataset in the sameway explained at TupleDataset. | from chainer.dataset import concat_examples
examples = square_noise_data[0:4]
print('examples = {}'.format(examples))
data_minibatch = concat_examples(examples)
x_minibatch, t_minibatch = data_minibatch
# Now it is array format, which has shape
print('x_minibatch = {}, type: {}, shape: {}'.format(x_minibatch, type(x_... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
TransformDataset
Transform dataset can be used to create/modify dataset from existing dataset.
New (modified) dataset can be created by TransformDataset(original_data, transform_function).
Let's see a concrete example to create new dataset from original tuple dataset by adding a small noise. | from chainer.datasets import TransformDataset
x = np.arange(10)
t = x * x - x
original_dataset = TupleDataset(x, t)
def transform_function(in_data):
x_i, t_i = in_data
new_t_i = t_i + np.random.normal(0, 0.1)
return x_i, new_t_i
transformed_dataset = TransformDataset(original_dataset, transform_function... | src/01_chainer_intro/dataset_introduction.ipynb | corochann/chainer-hands-on-tutorial | mit |
Built-in RNN layers: a simple example
There are three built-in RNN layers in Keras:
keras.layers.SimpleRNN, a fully-connected RNN where the output from previous
timestep is to be fed to next timestep.
keras.layers.GRU, first proposed in
Cho et al., 2014.
keras.layers.LSTM, first proposed in
Hochreiter & Schmidhub... | model = keras.Sequential()
# Add an Embedding layer expecting input vocab of size 1000, and
# output embedding dimension of size 64.
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# Add a LSTM layer with 128 internal units.
# TODO -- your code goes here
# Add a Dense layer with 10 units.
# TODO -- your c... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Built-in RNNs support a number of useful features:
Recurrent dropout, via the dropout and recurrent_dropout arguments
Ability to process an input sequence in reverse, via the go_backwards argument
Loop unrolling (which can lead to a large speedup when processing short sequences on
CPU), via the unroll argument
...and ... | model = keras.Sequential()
model.add(layers.Embedding(input_dim=1000, output_dim=64))
# The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256)
model.add(layers.GRU(256, return_sequences=True))
# The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128)
model.add(layers.SimpleRNN(128)... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
In addition, a RNN layer can return its final internal state(s). The returned states
can be used to resume the RNN execution later, or
to initialize another RNN.
This setting is commonly used in the
encoder-decoder sequence-to-sequence model, where the encoder final state is used as
the initial state of the decoder.
To... | encoder_vocab = 1000
decoder_vocab = 2000
encoder_input = layers.Input(shape=(None,))
encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(
encoder_input
)
# Return states in addition to output
output, state_h, state_c = layers.LSTM(64, return_state=True, name="encoder")(
encoder_embedd... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
RNN layers and RNN cells
In addition to the built-in RNN layers, the RNN API also provides cell-level APIs.
Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only
processes a single timestep.
The cell is the inside of the for loop of a RNN layer. Wrapping a cell inside a
keras.layers.RNN... | paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
output = lstm_layer(pa... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
RNN State Reuse
<a id="rnn_state_reuse"></a>
The recorded states of the RNN layer are not included in the layer.weights(). If you
would like to reuse the state from a RNN layer, you can retrieve the states value by
layer.states and use it as the
initial state for a new layer via the Keras functional API like new_layer(... | paragraph1 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph2 = np.random.random((20, 10, 50)).astype(np.float32)
paragraph3 = np.random.random((20, 10, 50)).astype(np.float32)
lstm_layer = layers.LSTM(64, stateful=True)
output = lstm_layer(paragraph1)
output = lstm_layer(paragraph2)
existing_state = lstm... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Bidirectional RNNs
For sequences other than time series (e.g. text), it is often the case that a RNN model
can perform better if it not only processes sequence from start to end, but also
backwards. For example, to predict the next word in a sentence, it is often useful to
have the context around the word, not only jus... | model = keras.Sequential()
# Add Bidirectional layers
# TODO -- your code goes here
model.summary() | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Under the hood, Bidirectional will copy the RNN layer passed in, and flip the
go_backwards field of the newly copied layer, so that it will process the inputs in
reverse order.
The output of the Bidirectional RNN will be, by default, the concatenation of the forward layer
output and the backward layer output. If you ne... | batch_size = 64
# Each MNIST image batch is a tensor of shape (batch_size, 28, 28).
# Each input sequence will be of size (28, 28) (height is treated like time).
input_dim = 28
units = 64
output_size = 10 # labels are from 0 to 9
# Build the RNN model
def build_model(allow_cudnn_kernel=True):
# CuDNN is only ava... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Let's load the MNIST dataset: | mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
sample, sample_label = x_train[0], y_train[0] | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Let's create a model instance and train it.
We choose sparse_categorical_crossentropy as the loss function for the model. The
output of the model has shape of [batch_size, 10]. The target for the model is an
integer vector, each of the integer is in the range of 0 to 9. | model = build_model(allow_cudnn_kernel=True)
# Compile the model
# TODO -- your code goes here
model.fit(
x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1
) | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Now, let's compare to a model that does not use the CuDNN kernel: | noncudnn_model = build_model(allow_cudnn_kernel=False)
noncudnn_model.set_weights(model.get_weights())
noncudnn_model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer="sgd",
metrics=["accuracy"],
)
noncudnn_model.fit(
x_train, y_train, validation_data=(x_test, y_test... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
When running on a machine with a NVIDIA GPU and CuDNN installed,
the model built with CuDNN is much faster to train compared to the
model that uses the regular TensorFlow kernel.
The same CuDNN-enabled model can also be used to run inference in a CPU-only
environment. The tf.device annotation below is just forcing the ... | import matplotlib.pyplot as plt
with tf.device("CPU:0"):
cpu_model = build_model(allow_cudnn_kernel=True)
cpu_model.set_weights(model.get_weights())
result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1)
print(
"Predicted result is: %s, target result is: %s" % (result... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
RNNs with list/dict inputs, or nested inputs
Nested structures allow implementers to include more information within a single
timestep. For example, a video frame could have audio and video input at the same
time. The data shape in this case could be:
[batch, timestep, {"video": [height, width, channel], "audio": [freq... | class NestedCell(keras.layers.Layer):
def __init__(self, unit_1, unit_2, unit_3, **kwargs):
self.unit_1 = unit_1
self.unit_2 = unit_2
self.unit_3 = unit_3
self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])]
self.output_size = [tf.TensorShape([unit_1... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Build a RNN model with nested input/output
Let's build a Keras model that uses a keras.layers.RNN layer and the custom cell
we just defined. | unit_1 = 10
unit_2 = 20
unit_3 = 30
i1 = 32
i2 = 64
i3 = 32
batch_size = 64
num_batches = 10
timestep = 50
cell = NestedCell(unit_1, unit_2, unit_3)
rnn = keras.layers.RNN(cell)
input_1 = keras.Input((None, i1))
input_2 = keras.Input((None, i2, i3))
outputs = rnn((input_1, input_2))
model = keras.models.Model([inp... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Train the model with randomly generated data
Since there isn't a good candidate dataset for this model, we use random Numpy data for
demonstration. | input_1_data = np.random.random((batch_size * num_batches, timestep, i1))
input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3))
target_1_data = np.random.random((batch_size * num_batches, unit_1))
target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3))
input_data = [input_1_... | courses/machine_learning/deepdive2/text_classification/labs/rnn.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Load the WNA profile from Campbell (2003). | with open("../tests/data/qwl_tests.json") as fp:
data = json.load(fp)[1]
thickness = np.diff(data["site"]["depth"])
profile = pysra.site.Profile()
for i, (thick, vel_shear, density) in enumerate(
zip(thickness, data["site"]["velocity"], data["site"]["density"])
):
profile.append(
pysra.site.Layer(... | examples/example-09.ipynb | arkottke/pysra | mit |
Create simple point source motion | motion = pysra.motion.SourceTheoryRvtMotion(magnitude=6.5, distance=20, region="cena")
motion.calc_fourier_amps(data["freqs"])
calc = pysra.propagation.QuarterWaveLenCalculator(site_atten=0.04)
input_loc = profile.location("outcrop", index=-1)
calc(motion, profile, input_loc)
fig, ax = plt.subplots()
ax.plot(motion.... | examples/example-09.ipynb | arkottke/pysra | mit |
The quarter-wavelength calculation is tested against the WNA and CENA crustal amplification models provided by Campbell (2003). The test of the CENA model passes, but the WNA model fails. Below is a comparison of the two crustal amplifications. | fig, ax = plt.subplots()
ax.plot(motion.freqs, calc.crustal_amp, label="Calculated")
ax.plot(data["freqs"], data["crustal_amp"], label="Campbell (03)")
ax.set(
xlabel="Frequency (Hz)",
xscale="log",
ylabel="Amplitude",
yscale="linear",
)
ax.legend()
fig.tight_layout(); | examples/example-09.ipynb | arkottke/pysra | mit |
Adjust the profile to match the target crustal amplification -- no consideration of the site attenuation paramater although this can also be done. First, the adjustment is only performed on the velocity. Second set of plots adjusts velocity and thickness. | for adjust_thickness in [False, True]:
calc.fit(
target_type="crustal_amp",
target=data["crustal_amp"],
adjust_thickness=adjust_thickness,
)
fig, ax = plt.subplots()
ax.plot(motion.freqs, calc.crustal_amp, label="Calculated")
ax.plot(data["freqs"], data["crustal_amp"], label... | examples/example-09.ipynb | arkottke/pysra | mit |
Load credentials | # %load getCredentialsFromFile.py
def getCredentials():
from oauth2client import file
import httplib2
import ipywidgets as widgets
print("Getting the credentials from file...")
storage = file.Storage("oauth2.dat")
credentials=storage.get()
if credentials is None or credentials.invalid:
... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Create services | compute_service = build('compute', 'v1', credentials=credentials)
resource_service = build('cloudresourcemanager', 'v1', credentials=credentials) | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Choose projectId and zone | # %load chooseProjectId.py
#projectId is the variable that will contains the projectId that will be used in the API calls
projectId=None
#list the existing projects
projects=resource_service.projects().list().execute()
#we create a dictionaray name:projectId foe a dropdown list widget
projectsList={project['name']:pr... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Create a new instance
- choosing the disk image | image_response = compute_service.images().getFromFamily(
project='debian-cloud', family='debian-8').execute()
source_disk_image = image_response['selfLink'] | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
- choosing the machineType | machineType=None
machineTypes=compute_service.machineTypes().list(project=projectId,zone=zone).execute()
machineTypesList=[item['name'] for item in machineTypes['items']]
machineTypesList.append('none')
machineTypesWidget=widgets.Dropdown(options=machineTypesList,value='none',description='Choose your MachineType:')
... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
- choose an instance name | instanceName=None
# instanceName have to validates this regexp
instanceNameControl=re.compile(r'^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$')
#the widgets
instanceNameWidget=widgets.Text(description="Name for the new instance:")
valid=widgets.Valid(value=False,description='',disabled=False)
display(widgets.Box([instanceN... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
- creating the config for the new instance
The name, machineType and disk are set accordingly to the previous steps.
With scheduling.preemptible to true we choose a preemptible instance (cheaper ;-) )
You can adjust labels to your needs. | config= {'name':instanceName,
'machineType': "zones/%(zone)s/machineTypes/%(machineType)s" %{'zone':zone,'machineType':machineType},
'disks':[
{
'boot':True,
'autoDelete':True,
'initializeParams':{
'sourc... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
- executing the API call | #a progress widget will present the progress of the operation
progress=widgets.IntProgress(value=0,min=0,max=3,step=1,description=':',bar_style='warning')
display(progress)
#executing the insert operation
operation = compute_service.instances().insert(project=projectId,
zone=zone,
... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Listing the instance and their status | result = compute_service.instances().list(project=projectId, zone=zone).execute()
if 'items' in result.keys():
display(DataFrame.from_dict({instance['name']:(instance['status'],'✅'if instance['status']=='RUNNING' else '✖'if instance['status']=='TERMINATED' else '❓')for instance in result['items']},orient='index'))... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Start/Stop/Delete instances | # getting the current instances list
instances=compute_service.instances().list(project=projectId,zone=zone).execute()
instancesList=[item['name'] for item in instances['items']]
# none is added for the dropdownlist
instancesList.append('none')
#building and displaying the widgets
instancesWidget=widgets.Dropdown(opti... | google cloud/google cloud with python/cloud.google.compute.instances.ipynb | daverick/alella | gpl-3.0 |
Global Variables | # Global Variables
# Region-of-interest ofsets
top_x_offset = 0.45
top_y_offset = 0.60
bottom_x_offset = 0.07
# Stores the left and right lines from an image.
# Notice, need to clear before using it on new set of images (video).
right_lines = []
left_lines = []
| 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
Helper Functions | import math
# Global Variables
# Region-of-interest ofsets
top_x_offset = 0.45
top_y_offset = 0.60
bottom_x_offset = 0.07
# Stores the left and right lines from an image.
# Notice, need to clear before using it on new set of images (video).
right_lines = []
left_lines = []
def grayscale(img):
"""Applies the Gray... | 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
Test Images
Build your pipeline to work on the images in the directory "test_images"
You should make sure your pipeline works well on these images before you try the videos.
Build the pipeline and run your solution on all test_images. Make copies into the test_images_output directory, and you can use the images in your... | import os
os.listdir("test_images/")
def process_image(image, display_images=False, export_images=False):
# Step 1. Convert the image to grayscale.
gray_image = grayscale(image)
# Step 2. Blur using Gaussian smoothing / blurring
# kernel_size = 5
blurred_image = gaussian_blur(gray_ima... | 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
Test on Videos
We can test our solution on two provided videos:
solidWhiteRight.mp4
solidYellowLeft.mp4 | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
import imageio
imageio.plugins.ffmpeg.download()
right_lines.clear()
left_lines.clear()
white_output = 'test_videos_output/solidWhiteRight.mp4'
clip1 = VideoFileClip("test_videos/solidWhi... | 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
Improve the draw_lines() function
At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defi... | right_lines.clear()
left_lines.clear()
yellow_output = 'test_videos_output/solidYellowLeft.mp4'
clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source... | 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
Optional Challenge
I modified my pipeline so it works with this video and submited it along with the rest of my project! | right_lines.clear()
left_lines.clear()
challenge_output = 'test_videos_output/challenge.mp4'
clip3 = VideoFileClip('test_videos/challenge.mp4')
challenge_clip = clip3.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source... | 1. Computer Vision and Deep Learning/P1 Finding Lane Lines on the Road/P1.ipynb | egillanton/Udacity-SDCND | mit |
So there are 8 folders present inside the train folder, one for each species.
Now let us check the number of files present in each of these sub folders. | sub_folders = check_output(["ls", "../input/train/"]).decode("utf8").strip().split('\n')
count_dict = {}
for sub_folder in sub_folders:
num_of_files = len(check_output(["ls", "../input/train/"+sub_folder]).decode("utf8").strip().split('\n'))
print("Number of files for the species",sub_folder,":",num_of_files)
... | fish/fish_explore.ipynb | sysid/kg | mit |
So the number of files for species ALB (Albacore tuna) is much higher than other species.
Let us look at the number of files present in the test folder. | num_test_files = len(check_output(["ls", "../input/test_stg1/"]).decode("utf8").strip().split('\n'))
print("Number of test files present :", num_test_files) | fish/fish_explore.ipynb | sysid/kg | mit |
Image Size:
Now let us look at the image size of each of the files and see what different sizes are available. | train_path = "../input/train/"
sub_folders = check_output(["ls", train_path]).decode("utf8").strip().split('\n')
different_file_sizes = {}
for sub_folder in sub_folders:
file_names = check_output(["ls", train_path+sub_folder]).decode("utf8").strip().split('\n')
for file_name in file_names:
im_array = im... | fish/fish_explore.ipynb | sysid/kg | mit |
So 720_1280_3 is the most common image size available in the train data and 10 different sizes are available.
720_1244_3 is the smallest size of the available images in train set and 974_1732_3 is the largest one.
Now let us look at the distribution in test dataset as well. | test_path = "../input/test_stg1/"
file_names = check_output(["ls", test_path]).decode("utf8").strip().split('\n')
different_file_sizes = {}
for file_name in file_names:
size = "_".join(map(str,list(imread(test_path+file_name).shape)))
different_file_sizes[size] = different_file_sizes.get(size,0) + 1
pl... | fish/fish_explore.ipynb | sysid/kg | mit |
Test set also has a very similar distribution.
Animation:
Let us try to have some animation on the available images. Not able to embed the video in the notebook.
Please uncomment the following part of the code and run it in local for animation | """
import random
import matplotlib.animation as animation
from matplotlib import animation, rc
from IPython.display import HTML
random.seed(12345)
train_path = "../input/train/"
sub_folders = check_output(["ls", train_path]).decode("utf8").strip().split('\n')
different_file_sizes = {}
all_files = []
for sub_folder in... | fish/fish_explore.ipynb | sysid/kg | mit |
Basic CNN Model using Keras:
Now let us try to build a CNN model on the dataset. Due to the memory constraints of the kernels, let us take only (500,500,3) array from top left corner of each image and then try to classify based on that portion.
Kindly note that running it offline with the full image will give much bett... | import random
from subprocess import check_output
from scipy.misc import imread
import numpy as np
np.random.seed(2016)
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils ... | fish/fish_explore.ipynb | sysid/kg | mit |
NumPy & SciPy
Very good tutorials and docs:
Tentative NumPy Tutorial
Scientific Python stack official docs
There are a few compilations for helping MATLAB, IDL, R users transitioning to Python/NumPy. HTML and phf versions are both available. (Big thanks to Alex Mulia for bringing this to our attention!)
Thesaurus of... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import curve_fit
np.polyfit? | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
NumPy Arrays | a0 = np.arange(6)
a = a0.reshape((2,3))
print(a.dtype, a.itemsize, a.size, a.shape, '\n')
print(a, '\n')
print(repr(a), '\n')
print(a.tolist())
b = a.astype(float)
print(b, '\n')
print(repr(b))
# re-define a0 and a
a0 = np.arange(6)
a = a0.reshape((2,3))
# get a slice of a to make c
c = a[:2, 1:3]
# a and c are bo... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
Now, we'll primarily demonstrate SciPy's capability of fitting.
Fitting a single variable simple function
$f(x) = a e^{b x}$ | def f(x, a, b):
return a * np.exp(b * x)
x = np.linspace(0, 1, 1000)
y_ideal = f(x, 1, 2)
y = f(x, 1, 2) + np.random.randn(1000)
plt.plot(x, y)
plt.plot(x, y_ideal, lw=2)
popt, pcov = curve_fit(f, x, y)
# popt is the optimized parameters, and pcov is the covariance matrix.
# diagnal members np.diag(pcov) is ... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
Fitting a single variable function containing an integral
$f(x) = c \int_o^x (a x' + b) dx' + d$ | from scipy.integrate import quad
def f(x, a, b, c, d):
# the integrand function should be within function f, because parameters a and b
# are available within.
def integrand(xx):
return a * xx + b
# if the upper/lower limit of the integral is our unknown variable x, x has to be
# iter... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
Fitting a 2 variable function
$f(x) = a e^{b x_1} + e^{c x_2}$ | def f(x, a, b, c):
return a * np.exp(b * x[0]) + np.exp(c * x[1])
x1 = np.linspace(0, 1, 1000)
x2 = np.linspace(0, 1, 1000)
x = [x1, x2]
y_ideal = f(x, 1, 2, 3)
y = f(x, 1, 2, 3) + np.random.randn(1000)
from mpl_toolkits.mplot3d.axes3d import Axes3D
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, proje... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
matplotlib
Some core concepts in http://matplotlib.org/faq/usage_faq.html regarding backends, (non-)interactive modes. | # pyplot (plt) interface vs object oriented interface
fig, axes = plt.subplots(1, 2)
plt.plot([2,3,4])
# Looks like it automatically chose the right axes to plot on.
# how can I plot on the first graph?
# Either keep (well... kind of) using the convenient pyplot interface
fig, axes = plt.subplots(1, 2)
plt.plot([2,... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
pandas
A very good glimpse: Ten minutes of pandas.
Read data from online files. | pd.read_csv('https://raw.githubusercontent.com/pydata/pandas/master/doc/data/baseball.csv', index_col='id')
df = pd.read_excel('https://github.com/pydata/pandas/raw/master/doc/data/test.xls')
print(df) | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
Ways of Indexing
Very confusing? See http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing | # simple column selection by label
df['A']
# simple row slice by position, end not included
df[0:2]
# explicit row selection
df.loc['2000-01-03']
# explicit row slicing, end included
df.loc['2000-01-03':'2000-01-05']
# explicit column selection by label
df.loc[:, 'A']
# explicit element selection by label
df.loc['... | scientific-python-walkabout.ipynb | terencezl/scientific-python-walkabout | mit |
if you want to see logging events.
Transformation interface
In the previous tutorial on Corpora and Vector Spaces, we created a corpus of documents represented as a stream of vectors. To continue, let’s fire up gensim and use that corpus: | from gensim import corpora, models, similarities
if (os.path.exists("/tmp/deerwester.dict")):
dictionary = corpora.Dictionary.load('/tmp/deerwester.dict')
corpus = corpora.MmCorpus('/tmp/deerwester.mm')
print("Used files generated from first tutorial")
else:
print("Please run first tutorial to generate ... | docs/notebooks/Topics_and_Transformations.ipynb | Kreiswolke/gensim | lgpl-2.1 |
In this tutorial, I will show how to transform documents from one vector representation into another. This process serves two goals:
To bring out hidden structure in the corpus, discover relationships between words and use them to describe the documents in a new and (hopefully) more semantic way.
To make the document ... | tfidf = models.TfidfModel(corpus) # step 1 -- initialize a model | docs/notebooks/Topics_and_Transformations.ipynb | Kreiswolke/gensim | lgpl-2.1 |
We used our old corpus from tutorial 1 to initialize (train) the transformation model. Different transformations may require different initialization parameters; in case of TfIdf, the “training” consists simply of going through the supplied corpus once and computing document frequencies of all its features. Training ot... | doc_bow = [(0, 1), (1, 1)]
print(tfidf[doc_bow]) # step 2 -- use the model to transform vectors | docs/notebooks/Topics_and_Transformations.ipynb | Kreiswolke/gensim | lgpl-2.1 |
Or to apply a transformation to a whole corpus: | corpus_tfidf = tfidf[corpus]
for doc in corpus_tfidf:
print(doc) | docs/notebooks/Topics_and_Transformations.ipynb | Kreiswolke/gensim | lgpl-2.1 |
In this particular case, we are transforming the same corpus that we used for training, but this is only incidental. Once the transformation model has been initialized, it can be used on any vectors (provided they come from the same vector space, of course), even if they were not used in the training corpus at all. Thi... | lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) # initialize an LSI transformation
corpus_lsi = lsi[corpus_tfidf] # create a double wrapper over the original corpus: bow->tfidf->fold-in-lsi | docs/notebooks/Topics_and_Transformations.ipynb | Kreiswolke/gensim | lgpl-2.1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.