markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Instantiate and evaluate this model: | baseline = Baseline(label_index=column_indices['T (degC)'])
baseline.compile(loss=tf.losses.MeanSquaredError(),
metrics=[tf.metrics.MeanAbsoluteError()])
val_performance = {}
performance = {}
val_performance['Baseline'] = baseline.evaluate(single_step_window.val)
performance['Baseline'] = baseline.ev... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
That printed some performance metrics, but those don't give you a feeling for how well the model is doing.The `WindowGenerator` has a plot method, but the plots won't be very interesting with only a single sample. So, create a wider `WindowGenerator` that generates windows 24h of consecutive inputs and labels at a time... | wide_window = WindowGenerator(
input_width=24, label_width=24, shift=1,
label_columns=['T (degC)'])
wide_window | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
This expanded window can be passed directly to the same `baseline` model without any code changes. This is possible because the inputs and labels have the same number of timesteps, and the baseline just forwards the input to the output:  | print('Input shape:', wide_window.example[0].shape)
print('Output shape:', baseline(wide_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Plotting the baseline model's predictions you can see that it is simply the labels, shifted right by 1h. | wide_window.plot(baseline) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
In the above plots of three examples the single step model is run over the course of 24h. This deserves some explaination:* The blue "Inputs" line shows the input temperature at each time step. The model recieves all features, this plot only shows the temperature.* The green "Labels" dots show the target prediction val... | linear = tf.keras.Sequential([
tf.keras.layers.Dense(units=1)
])
print('Input shape:', single_step_window.example[0].shape)
print('Output shape:', linear(single_step_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
This tutorial trains many models, so package the training procedure into a function: | MAX_EPOCHS = 20
def compile_and_fit(model, window, patience=2):
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',
patience=patience,
mode='min')
model.compile(loss=tf.losses.MeanSquaredError... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Train the model and evaluate its performance: | history = compile_and_fit(linear, single_step_window)
val_performance['Linear'] = linear.evaluate(single_step_window.val)
performance['Linear'] = linear.evaluate(single_step_window.test, verbose=0) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Like the `baseline` model, the linear model can be called on batches of wide windows. Used this way the model makes a set of independent predictions on consecuitive time steps. The `time` axis acts like another `batch` axis. There are no interactions between the predictions at each time step.![A single step prediction]... | print('Input shape:', wide_window.example[0].shape)
print('Output shape:', baseline(wide_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Here is the plot of its example predictions on the `wide_window`, note how in many cases the prediction is clearly better than just returning the input temperature, but in a few cases it's worse: | wide_window.plot(linear) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
One advantage to linear models is that they're relatively simple to interpret.You can pull out the layer's weights, and see the weight assigned to each input: | plt.bar(x = range(len(train_df.columns)),
height=linear.layers[0].kernel[:,0].numpy())
axis = plt.gca()
axis.set_xticks(range(len(train_df.columns)))
_ = axis.set_xticklabels(train_df.columns, rotation=90) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Sometimes the model doesn't even place the most weight on the input `T (degC)`. This is one of the risks of random initialization. DenseBefore applying models that actually operate on multiple time-steps, it's worth checking the performance of deeper, more powerful, single input step models.Here's a model similar to ... | dense = tf.keras.Sequential([
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=1)
])
history = compile_and_fit(dense, single_step_window)
val_performance['Dense'] = dense.evaluate(single_step_window.val)
performance['Dense'... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Multi-step denseA single-time-step model has no context for the current values of its inputs. It can't see how the input features are changing over time. To address this issue the model needs access to multiple time steps when making predictions:... | CONV_WIDTH = 3
conv_window = WindowGenerator(
input_width=CONV_WIDTH,
label_width=1,
shift=1,
label_columns=['T (degC)'])
conv_window
conv_window.plot()
plt.title("Given 3h as input, predict 1h into the future.") | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
You could train a `dense` model on a multiple-input-step window by adding a `layers.Flatten` as the first layer of the model: | multi_step_dense = tf.keras.Sequential([
# Shape: (time, features) => (time*features)
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units=32, activation='relu'),
tf.keras.layers.Dense(units=32, activation='relu'),
tf.keras.layers.Dense(units=1),
# Add back the time dimension.
# Shape: (ou... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The main down-side of this approach is that the resulting model can only be executed on input windows of exactly this shape. | print('Input shape:', wide_window.example[0].shape)
try:
print('Output shape:', multi_step_dense(wide_window.example[0]).shape)
except Exception as e:
print(f'\n{type(e).__name__}:{e}') | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The convolutional models in the next section fix this problem. Convolution neural network A convolution layer (`layers.Conv1D`) also takes multiple time steps as input to each prediction. Below is the **same** model as `multi_step_dense`, re-written with a convolution. Note the changes:* The `layers.Flatten` and the f... | conv_model = tf.keras.Sequential([
tf.keras.layers.Conv1D(filters=32,
kernel_size=(CONV_WIDTH,),
activation='relu'),
tf.keras.layers.Dense(units=32, activation='relu'),
tf.keras.layers.Dense(units=1),
]) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Run it on an example batch to see that the model produces outputs with the expected shape: | print("Conv model on `conv_window`")
print('Input shape:', conv_window.example[0].shape)
print('Output shape:', conv_model(conv_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Train and evaluate it on the ` conv_window` and it should give performance similar to the `multi_step_dense` model. | history = compile_and_fit(conv_model, conv_window)
IPython.display.clear_output()
val_performance['Conv'] = conv_model.evaluate(conv_window.val)
performance['Conv'] = conv_model.evaluate(conv_window.test, verbose=0) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The difference between this `conv_model` and the `multi_step_dense` model is that the `conv_model` can be run on inputs of any length. The convolutional layer is applied to a sliding window of inputs:If you run it on wider input, it produces w... | print("Wide window")
print('Input shape:', wide_window.example[0].shape)
print('Labels shape:', wide_window.example[1].shape)
print('Output shape:', conv_model(wide_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Note that the output is shorter than the input. To make training or plotting work, you need the labels, and prediction to have the same length. So build a `WindowGenerator` to produce wide windows with a few extra input time steps so the label and prediction lengths match: | LABEL_WIDTH = 24
INPUT_WIDTH = LABEL_WIDTH + (CONV_WIDTH - 1)
wide_conv_window = WindowGenerator(
input_width=INPUT_WIDTH,
label_width=LABEL_WIDTH,
shift=1,
label_columns=['T (degC)'])
wide_conv_window
print("Wide conv window")
print('Input shape:', wide_conv_window.example[0].shape)
print('Labels shap... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Now you can plot the model's predictions on a wider window. Note the 3 input time steps before the first prediction. Every prediction here is based on the 3 preceding timesteps: | wide_conv_window.plot(conv_model) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Recurrent neural networkA Recurrent Neural Network (RNN) is a type of neural network well-suited to time series data. RNNs process a time series step-by-step, maintaining an internal state from time-step to time-step.For more details, read the [text generation tutorial](https://www.tensorflow.org/tutorials/text/text_g... | lstm_model = tf.keras.models.Sequential([
# Shape [batch, time, features] => [batch, time, lstm_units]
tf.keras.layers.LSTM(32, return_sequences=True),
# Shape => [batch, time, features]
tf.keras.layers.Dense(units=1)
]) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
With `return_sequences=True` the model can be trained on 24h of data at a time.Note: This will give a pessimistic view of the model's performance. On the first timestep the model has no access to previous steps, and so can't do any better than the simple `linear` and `dense` models shown earlier. | print('Input shape:', wide_window.example[0].shape)
print('Output shape:', lstm_model(wide_window.example[0]).shape)
history = compile_and_fit(lstm_model, wide_window)
IPython.display.clear_output()
val_performance['LSTM'] = lstm_model.evaluate(wide_window.val)
performance['LSTM'] = lstm_model.evaluate(wide_window.tes... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Performance With this dataset typically each of the models does slightly better than the one before it. | x = np.arange(len(performance))
width = 0.3
metric_name = 'mean_absolute_error'
metric_index = lstm_model.metrics_names.index('mean_absolute_error')
val_mae = [v[metric_index] for v in val_performance.values()]
test_mae = [v[metric_index] for v in performance.values()]
plt.ylabel('mean_absolute_error [T (degC), normal... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Multi-output modelsThe models so far all predicted a single output feature, `T (degC)`, for a single time step.All of these models can be converted to predict multiple features just by changing the number of units in the output layer and adjusting the training windows to include all features in the `labels`. | single_step_window = WindowGenerator(
# `WindowGenerator` returns all features as labels if you
# don't set the `label_columns` argument.
input_width=1, label_width=1, shift=1)
wide_window = WindowGenerator(
input_width=24, label_width=24, shift=1)
for example_inputs, example_labels in wide_window.tr... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Note above that the `features` axis of the labels now has the same depth as the inputs, instead of 1. BaselineThe same baseline model can be used here, but this time repeating all features instead of selecting a specific `label_index`. | baseline = Baseline()
baseline.compile(loss=tf.losses.MeanSquaredError(),
metrics=[tf.metrics.MeanAbsoluteError()])
val_performance = {}
performance = {}
val_performance['Baseline'] = baseline.evaluate(wide_window.val)
performance['Baseline'] = baseline.evaluate(wide_window.test, verbose=0) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Dense | dense = tf.keras.Sequential([
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=64, activation='relu'),
tf.keras.layers.Dense(units=num_features)
])
history = compile_and_fit(dense, single_step_window)
IPython.display.clear_output()
val_performance['Dense'] = dense.evaluate(si... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
RNN | %%time
wide_window = WindowGenerator(
input_width=24, label_width=24, shift=1)
lstm_model = tf.keras.models.Sequential([
# Shape [batch, time, features] => [batch, time, lstm_units]
tf.keras.layers.LSTM(32, return_sequences=True),
# Shape => [batch, time, features]
tf.keras.layers.Dense(units=num_f... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Advanced: Residual connectionsThe `Baseline` model from earlier took advantage of the fact that the sequence doesn't change drastically from time step to time step. Every model trained in this tutorial so far was randomly initialized, and then had to learn that the output is a a small change from the previous time ste... | class ResidualWrapper(tf.keras.Model):
def __init__(self, model):
super().__init__()
self.model = model
def call(self, inputs, *args, **kwargs):
delta = self.model(inputs, *args, **kwargs)
# The prediction for each timestep is the input
# from the previous time step plus the delta
# calcul... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Performance Here is the overall performance for these multi-output models. | x = np.arange(len(performance))
width = 0.3
metric_name = 'mean_absolute_error'
metric_index = lstm_model.metrics_names.index('mean_absolute_error')
val_mae = [v[metric_index] for v in val_performance.values()]
test_mae = [v[metric_index] for v in performance.values()]
plt.bar(x - 0.17, val_mae, width, label='Validat... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The above performances are averaged across all model outputs. Multi-step modelsBoth the single-output and multiple-output models in the previous sections made **single time step predictions**, 1h into the future.This section looks at how to expand these models to make **multiple time step predictions**.In a multi-step... | OUT_STEPS = 24
multi_window = WindowGenerator(input_width=24,
label_width=OUT_STEPS,
shift=OUT_STEPS)
multi_window.plot()
multi_window | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Baselines A simple baseline for this task is to repeat the last input time step for the required number of output timesteps: | class MultiStepLastBaseline(tf.keras.Model):
def call(self, inputs):
return tf.tile(inputs[:, -1:, :], [1, OUT_STEPS, 1])
last_baseline = MultiStepLastBaseline()
last_baseline.compile(loss=tf.losses.MeanSquaredError(),
metrics=[tf.metrics.MeanAbsoluteError()])
multi_val_performance = {}
mu... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Since this task is to predict 24h given 24h another simple approach is to repeat the previous day, assuming tomorrow will be similar: | class RepeatBaseline(tf.keras.Model):
def call(self, inputs):
return inputs
repeat_baseline = RepeatBaseline()
repeat_baseline.compile(loss=tf.losses.MeanSquaredError(),
metrics=[tf.metrics.MeanAbsoluteError()])
multi_val_performance['Repeat'] = repeat_baseline.evaluate(multi_window.val)... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Single-shot modelsOne high level approach to this problem is use a "single-shot" model, where the model makes the entire sequence prediction in a single step.This can be implemented efficiently as a `layers.Dense` with `OUT_STEPS*features` output units. The model just needs to reshape that output to the required `(OUT... | multi_linear_model = tf.keras.Sequential([
# Take the last time-step.
# Shape [batch, time, features] => [batch, 1, features]
tf.keras.layers.Lambda(lambda x: x[:, -1:, :]),
# Shape => [batch, 1, out_steps*features]
tf.keras.layers.Dense(OUT_STEPS*num_features,
kernel_initi... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
DenseAdding a `layers.Dense` between the input and output gives the linear model more power, but is still only based on a single input timestep. | multi_dense_model = tf.keras.Sequential([
# Take the last time step.
# Shape [batch, time, features] => [batch, 1, features]
tf.keras.layers.Lambda(lambda x: x[:, -1:, :]),
# Shape => [batch, 1, dense_units]
tf.keras.layers.Dense(512, activation='relu'),
# Shape => [batch, out_steps*features]
... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
CNN A convolutional model makes predictions based on a fixed-width history, which may lead to better performance than the dense model since it can see how things are changing over time: | CONV_WIDTH = 3
multi_conv_model = tf.keras.Sequential([
# Shape [batch, time, features] => [batch, CONV_WIDTH, features]
tf.keras.layers.Lambda(lambda x: x[:, -CONV_WIDTH:, :]),
# Shape => [batch, 1, conv_units]
tf.keras.layers.Conv1D(256, activation='relu', kernel_size=(CONV_WIDTH)),
# Shape => [ba... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
RNN A recurrent model can learn to use a long history of inputs, if it's relevant to the predictions the model is making. Here the model will accumulate internal state for 24h, before making a single prediction for the next 24h.In this single-shot format, the LSTM only needs to produce an output at the last time step,... | multi_lstm_model = tf.keras.Sequential([
# Shape [batch, time, features] => [batch, lstm_units]
# Adding more `lstm_units` just overfits more quickly.
tf.keras.layers.LSTM(32, return_sequences=False),
# Shape => [batch, out_steps*features]
tf.keras.layers.Dense(OUT_STEPS*num_features,
... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Advanced: Autoregressive modelThe above models all predict the entire output sequence as a in a single step.In some cases it may be helpful for the model to decompose this prediction into individual time steps. Then each model's output can be fed back into itself at each step and predictions can be made conditioned on... | class FeedBack(tf.keras.Model):
def __init__(self, units, out_steps):
super().__init__()
self.out_steps = out_steps
self.units = units
self.lstm_cell = tf.keras.layers.LSTMCell(units)
# Also wrap the LSTMCell in an RNN to simplify the `warmup` method.
self.lstm_rnn = tf.keras.layers.RNN(self.l... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The first method this model needs is a `warmup` method to initialize its internal state based on the inputs. Once trained this state will capture the relevant parts of the input history. This is equivalent to the single-step `LSTM` model from earlier: | def warmup(self, inputs):
# inputs.shape => (batch, time, features)
# x.shape => (batch, lstm_units)
x, *state = self.lstm_rnn(inputs)
# predictions.shape => (batch, features)
prediction = self.dense(x)
return prediction, state
FeedBack.warmup = warmup | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
This method returns a single time-step prediction, and the internal state of the LSTM: | prediction, state = feedback_model.warmup(multi_window.example[0])
prediction.shape | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
With the `RNN`'s state, and an initial prediction you can now continue iterating the model feeding the predictions at each step back as the input.The simplest approach to collecting the output predictions is to use a python list, and `tf.stack` after the loop. Note: Stacking a python list like this only works with eage... | def call(self, inputs, training=None):
# Use a TensorArray to capture dynamically unrolled outputs.
predictions = []
# Initialize the lstm state
prediction, state = self.warmup(inputs)
# Insert the first prediction
predictions.append(prediction)
# Run the rest of the prediction steps
for n in range(1,... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Test run this model on the example inputs: | print('Output shape (batch, time, features): ', feedback_model(multi_window.example[0]).shape) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Now train the model: | history = compile_and_fit(feedback_model, multi_window)
IPython.display.clear_output()
multi_val_performance['AR LSTM'] = feedback_model.evaluate(multi_window.val)
multi_performance['AR LSTM'] = feedback_model.evaluate(multi_window.test, verbose=0)
multi_window.plot(feedback_model) | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Performance There are clearly diminishing returns as a function of model complexity on this problem. | x = np.arange(len(multi_performance))
width = 0.3
metric_name = 'mean_absolute_error'
metric_index = lstm_model.metrics_names.index('mean_absolute_error')
val_mae = [v[metric_index] for v in multi_val_performance.values()]
test_mae = [v[metric_index] for v in multi_performance.values()]
plt.bar(x - 0.17, val_mae, wi... | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
The metrics for the multi-output models in the first half of this tutorial show the performance averaged across all output features. These performances similar but also averaged across output timesteps. | for name, value in multi_performance.items():
print(f'{name:8s}: {value[1]:0.4f}') | _____no_output_____ | Apache-2.0 | site/en/tutorials/structured_data/time_series.ipynb | jcjveraa/docs-2 |
Word Embeddings in MySQLThis example uses the official MySQL Connector within Python3 to store and retrieve various amounts of Word Embeddings.We will use a local MySQL database running as a Docker Container for testing purposes. To start the database run:```docker run -ti --rm --name ohmysql -e MYSQL_ROOT_PASSWORD=mi... | import mysql.connector
import io
import time
import numpy
import plotly
from tqdm import tqdm_notebook as tqdm | _____no_output_____ | MIT | Word_Embeddings_MySQL.ipynb | krokodilj/word_embedding_storage |
Dummy EmbeddingsFor testing purposes we will use randomly generated numpy arrays as dummy embbeddings. | def embeddings(n=1000, dim=300):
"""
Yield n tuples of random numpy arrays of *dim* length indexed by *n*
"""
idx = 0
while idx < n:
yield (str(idx), numpy.random.rand(dim))
idx += 1 | _____no_output_____ | MIT | Word_Embeddings_MySQL.ipynb | krokodilj/word_embedding_storage |
Conversion FunctionsSince we can't just save a NumPy array into the database, we will convert it into a BLOB. | def adapt_array(array):
"""
Using the numpy.save function to save a binary version of the array,
and BytesIO to catch the stream of data and convert it into a BLOB.
"""
out = io.BytesIO()
numpy.save(out, array)
out.seek(0)
return out.read()
def convert_array(blob):
"""
Using By... | CPU times: user 393 ms, sys: 42.7 ms, total: 435 ms
Wall time: 1.26 s
| MIT | Word_Embeddings_MySQL.ipynb | krokodilj/word_embedding_storage |
Sample some dataTo test the I/O we will write and read some data from the database. This may take a while. | write_times = []
read_times = []
counts = [500, 1000, 2000, 3000, 4000, 5000]
for c in counts:
print(c)
cursor.execute('DROP TABLE IF EXISTS `embeddings`;')
cursor.execute('CREATE TABLE IF NOT EXISTS `embeddings` (`key` TEXT, `embedding` BLOB);')
connection.commit()
start_time_write = time.time()
... | 500
| MIT | Word_Embeddings_MySQL.ipynb | krokodilj/word_embedding_storage |
Results | plotly.offline.init_notebook_mode(connected=True)
trace = plotly.graph_objs.Scatter(
y = write_times,
x = counts,
mode = 'lines+markers'
)
layout = plotly.graph_objs.Layout(title="MySQL Write Times",
yaxis=dict(title='Time in Seconds'),
xaxis=dict(title='Embedding Count'))
da... | _____no_output_____ | MIT | Word_Embeddings_MySQL.ipynb | krokodilj/word_embedding_storage |
Prepare df and dict corpus | fields_of_interest = [
'Id',
'name',
'producer',
'description',
'price',
'category',
'source'
]
amazon_walmart_all_df = pd.read_csv(amazon_walmart_all_path, sep=',', quotechar='"')[fields_of_interest]
amazon_walmart_all_df.dtypes
x = amazon_walmart_all_df[amazon_walmart_all_df['category'].is... | _____no_output_____ | MIT | dedupe/Product Data/product_amazon_walmart.ipynb | MauriceStr/StandardizedDI_Clients_SDASP |
In the following, we want to partition responses according to how many times a player has miscoordinated before. For a start, we concatenate all three experiments into one dataframe: | #df = pd.concat([
# df_MTurk.join(pd.Series(['MTurk']*len(df_MTurk), name='experiment')),
# df_DTU1.join(pd.Series(['DTU1']*len(df_DTU1), name='experiment')),
# df_DTU2.join(pd.Series(['DTU2']*len(df_DTU2), name='experiment'))],
# ignore_index=True)
#df.head(... | _____no_output_____ | MIT | python/figS6_logit_twobins_MTurk.ipynb | thomasnicolet/Paper_canteen_dilemma |
Now we group the data into response pairs | df = df_MTurk.groupby(['session', 'group', 'round'], as_index=False)[['code', 'id_in_group', 'arrival', 'choice', 'certainty']].agg(lambda x: tuple(x))
df.head()
#df0 = pd.DataFrame(columns=df.columns)
#df1_ = pd.DataFrame(columns=df.columns)
#sessions = df.session.unique()
#for session in sessions:
# df_session = d... | _____no_output_____ | MIT | python/figS6_logit_twobins_MTurk.ipynb | thomasnicolet/Paper_canteen_dilemma |
Now a bit of magic: we need to separate the tuples again and create rows for each person: (see ref at https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe | def unnesting(df, explode):
idx = df.index.repeat(df[explode[0]].str.len())
df1 = pd.concat([
pd.DataFrame({x: np.concatenate(df[x].values)}) for x in explode], axis=1)
df1.index = idx
return df1.join(df.drop(explode, 1), how='left')
dfnew0 = unnesting(df0,['code', 'id_in_group', 'arrival', '... | _____no_output_____ | MIT | python/figS6_logit_twobins_MTurk.ipynb | thomasnicolet/Paper_canteen_dilemma |
COVID-MultiVentThe COVID MultiVent System was developed through a collaboration between Dr. Arun Agarwal, pulmonary critical care fellow at the University of Missouri, and a group of medical students at the University of Pennsylvania with backgrounds in various types of engineering. The system allows for monitoring of... | %%html
<iframe src="https://docs.google.com/presentation/d/e/2PACX-1vT2kAsF54vHJoIti5iQkk8zUTkcQuRBFnbtgAhCoHwxrThIzZ14mCpdgNkWrqS8bRf5xFB2ZoeXlfUk/embed?start=false&loop=false&delayms=3000" frameborder="0" width="480" height="299" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe> | _____no_output_____ | MIT-0 | Notebooks/Index.ipynb | covid-multivent/covid-multivent.github.io |
Original Video and Facebook Group Please see below Dr. Agrawal's original video showing the proposed setup. A link to the MultiVent facebook group can be found [here](https://facebook.com/COVIDMULTIVENT/). | %%html
<iframe width="560" height="315" src="https://www.youtube.com/embed/odnhnnlBlpM" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> | _____no_output_____ | MIT-0 | Notebooks/Index.ipynb | covid-multivent/covid-multivent.github.io |
Assembly Guide and Component ListFor detailed instructions on how to build the MultiVent setup please click [here](https://docs.google.com/document/d/11Z7MpeGSC6m3ipsMVLe-Ofkw4HeqCN6x1Zhqy8FMRpc/edit?usp=sharing)Below see the proposed parts list with the number of each part required for a single or a 2-patient setup. ... | import pandas as pd
df = pd.read_excel('Website Ventilator splitting components.xlsx')
df | _____no_output_____ | MIT-0 | Notebooks/Index.ipynb | covid-multivent/covid-multivent.github.io |
Homework 10: `SQL` Due Date: Thursday, November 16th at 11:59 PMYou will create a database of the NASA polynomial coefficients for each specie.**Please turn in your database with your `Jupyter` notebook!** Question 1: Convert XML to a SQL database Create two tables named `LOW` and `HIGH`, each corresponding to data ... | import xml.etree.ElementTree as ET
import sqlite3
import pandas as pd
from IPython.core.display import display
pd.set_option('display.width', 500)
pd.set_option('display.max_columns', 100)
pd.set_option('display.notebook_repr_html', True)
# Create and connect to database
db = sqlite3.connect('NASA_coef.sqlite')
curso... | _____no_output_____ | MIT | Homework/HW10/HW10-final.ipynb | JasmineeeeeTONG/CS207_coursework |
Question 2: `WHERE` Statements 1. Write a `Python` function `get_coeffs` that returns an array of 7 coefficients. The function should take in two parameters: 1.) `species_name` and 2.) `temp_range`, an indicator variable ('low' or 'high') to indicate whether the coefficients should come from the low or high tem... | def get_coeffs(species_name, temp_range):
query = '''SELECT COEFF_1, COEFF_2, COEFF_3, COEFF_4, COEFF_5, COEFF_6, COEFF_7
FROM {}
WHERE SPECIES_NAME = "{}"'''.format(temp_range.upper(), species_name)
coeffs = list(cursor.execute(query).fetchall()[0])
return coeffs
get_coeffs... | _____no_output_____ | MIT | Homework/HW10/HW10-final.ipynb | JasmineeeeeTONG/CS207_coursework |
Question 3: `JOIN` STATEMENTS Create a table named `ALL_TEMPS` that has the following columns:- `SPECIES_NAME`- `TEMP_LOW`- `TEMP_HIGH`This table should be created by joining the tables `LOW` and `HIGH` on the value `SPECIES_NAME`. | # Create the table for ALL_TEMPS
cursor.execute("DROP TABLE IF EXISTS ALL_TEMPS")
cursor.execute('''CREATE TABLE ALL_TEMPS (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
SPECIES_NAME TEXT,
TEMP_LOW REAL,
TEMP_HIGH REAL)''')
db.commit()
# Insert TEMP_LOW ... | _____no_output_____ | MIT | Homework/HW10/HW10-final.ipynb | JasmineeeeeTONG/CS207_coursework |
1. Write a `Python` function `get_range` that returns the range of temperatures for a given species_name.The range should be computed within the `SQL` query (i.e. you should subtract within the `SELECT` statement in the `SQL` query).```pythondef get_range(species_name): '''Fill in here''' return range```Note that... | def get_range(species_name):
query = '''SELECT (TEMP_HIGH - TEMP_LOW) AS T_range FROM ALL_TEMPS WHERE SPECIES_NAME = "{}"'''.format(species_name)
T_range = cursor.execute(query).fetchall()[0][0]
return T_range
get_range('O')
# Close the Database
db.commit()
db.close() | _____no_output_____ | MIT | Homework/HW10/HW10-final.ipynb | JasmineeeeeTONG/CS207_coursework |
Results for BERT when applying syn tranformation to both premise and hypothesis to the MNLI dataset | import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tqdm import tqdm
from IPython.display import display, HTML
from lr.analysis.util import get_ts_from_results_folder
from lr.analysis.util import get_rho_stats_from_result_list
from lr.stats.h_testing import get_... | _____no_output_____ | MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
Get Results | all_accs = []
all_transformed_accs = []
all_paired_t_p_values = []
all_dev_plus_diff = []
all_time = []
m_name = "bert_base"
folder = "mnli"
test_repetitions = 5
batchs = range(1, test_repetitions + 1)
for i in tqdm(batchs):
test_accuracy = get_ts_from_results_folder(path="results/{}/{}/syn_p_h/batch{}/".format(... | Time for all experiments = 204.6 hours
Number of paramaters for BERT = 109484547
| MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
Accuracy | rhos, mean_acc, error_acc, _ = get_rho_stats_from_result_list(all_accs)
_, mean_acc_t, error_acc_t, _ = get_rho_stats_from_result_list(all_transformed_accs)
fig, ax = plt.subplots(figsize=(12,6))
ax.errorbar(rhos, mean_acc, yerr=error_acc, fmt='-o', label="original test data");
ax.errorbar(rhos, mean_acc_t, yerr=erro... | _____no_output_____ | MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
P-values | rhos, mean_p_values, error_p_values, min_p_values = get_rho_stats_from_result_list(all_paired_t_p_values)
alpha = 0.05
alpha_adj = alpha / test_repetitions
rejected_ids = []
remain_ids = []
for i,p in enumerate(min_p_values):
if p < alpha_adj:
rejected_ids.append(i)
else:
remain_ids.append(i)... | _____no_output_____ | MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
Accuracy difference | rhos, diff, _,_ = get_rho_stats_from_result_list(all_dev_plus_diff)
_, test_acc, _,_ = get_rho_stats_from_result_list(all_accs)
_, test_acc_t, _,_ = get_rho_stats_from_result_list(all_transformed_accs)
test_diff = np.abs(test_acc - test_acc_t)
fig, ax = plt.subplots(figsize=(12,6))
ax.errorbar(rhos, diff, fmt='-o', la... | _____no_output_____ | MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
Selecting the best $\rho$ | id_min = np.argmin(diff)
min_rho = rhos[id_min]
min_rho_test_acc = test_acc[id_min]
min_rho_transformed_test_acc = test_acc_t[id_min]
test_accuracy_loss_pct = np.round(((min_rho_test_acc - test_acc[0]) / test_acc[0]) * 100, 1)
analysis = {"dataset":"mnli",
"model": "BERT",
"rho":min_rho,
... | _____no_output_____ | MIT | src/drafts/check_results_bert_base_MNLI.ipynb | lukewanless/looking-for-equivalences |
[View in Colaboratory](https://colab.research.google.com/github/tompollard/buenosaires2018/blob/master/1_intro_to_python.ipynb) Programming in Python In this part of the workshop, we will introduce some basic programming concepts in Python. We will then explore how these concepts allow us to carry out an anlysis that ... | 3+5 | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
However, to do anything useful, we will need to assign values to `variables`. Assign a height in cm to a variable in the cell below. | height_cm = 180 | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Now the value has been assigned to our variable, we can print it in the console with `print`. | print('Height in cm is:', height_cm) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can also do arithmetic with the variable. Convert the height in cm to metres, then print the new value as before (Warning! In Python 2, dividing an integer by an integer will return an integer.) | height_m = height_cm / 100
print('height in metres:',height_m) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can check which variables are available in memory with the special command: `%whos` | %whos | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can see that each of our variables has a type (in this case `int` and `float`), describing the type of data held by the variable. We can use `type` to check the data type of a variable. | type(height_cm) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Another data type is a `list`, which can hold a series of items. For example, we might measure a patient's heart rate several times over a period. | heartrate = [66,64,63,62,66,69,70,75,76]
print(heartrate)
type(heartrate) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Repeating actions in loops We can access individual items in a list using an index (note, in Python, indexing begins with 0!). For example, let's view the first `[0]` and second `[1]` heart rate measurements. | print(heartrate[0])
print(heartrate[1]) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can iterate through a list with the help of a `for` loop. Let's try looping over our list of heart rates, printing each item as we go. | for i in heartrate:
print('the heart rate is:', i) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Making choices Sometimes we want to take different actions depending on a set of conditions. We can do this using an `if/else` statement. Let's write a statement to test if a mean arterial pressure (`meanpressure`) is high or low. | meanpressure = 70
if meanpressure < 60:
print('Low pressure')
elif meanpressure > 100:
print('High pressure')
else:
print('Normal pressure') | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Writing our own functions To help organise our code and to avoid replicating the same code again and again, we can create functions. Let's create a function to convert temperature in fahrenheit to celsius, using the following formula:`celsius = (fahrenheit - 32) * 5/9` | def fahr_to_celsius(temp):
celsius = (temp - 32) * 5/9
return celsius
| _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Now we can call the function `fahr_to_celsius` to convert a temperature from celsius to fahrenheit. | body_temp_f = 98.6
body_temp_c = fahr_to_celsius(body_temp_f)
print('Patient body temperature is:', body_temp_c, 'celsius') | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Reusing code with libraries Python is a popular language for data analysis, so thankfully we can benefit from the hard work of others with the use of libraries. Pandas, a popular library for data analysis, introduces the `DataFrame`, a convenient data structure similar to a spreadsheet. Before using a library, we will... | # let's assign pandas an alias, pd, for brevity
import pandas as pd | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We have shared a demo dataset online containing physiological data relating to 1000 patients admitted to an intensive care unit in Boston, Massachussetts, USA. Let's load this data into our new data structure. | url="https://raw.githubusercontent.com/tompollard/tableone/master/data/pn2012_demo.csv"
data=pd.read_csv(url) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
The variable `data` should now contain our new dataset. Let's view the first few rows using `head()`. Note: parentheses `"()"` are generally required when we are performing an action/operation. In this case, the action is to select a limited number of rows. | data.head() | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can perform other operations on the dataframe. For example, using `mean()` to get an average of the columns. | data.mean() | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
If we are unsure of the meaning of a method, we can check by adding `?` after the method. For example, what is `max`? | data.max?
data.max() | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
We can access a single column in the data by specifying the column name after the variable. For example, we can select a list of ages with `data.Age`, and then find the mean for this column in a similar way to before. | print('The mean age of patients is:', data.Age.mean()) | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
Pandas also provides a convenient method `plot` for plotting data. Let's plot a distribution of the patient ages in our dataset. | data.Age.plot(kind='kde', title='Age of patients in years') | _____no_output_____ | MIT | 1_intro_to_python.ipynb | stickbass/buenosaires2018 |
import pandas as pd
!pip install rasterio
import rasterio
!pip install geopandas
import geopandas as gpd
import numpy as np
from google.colab import drive
drive.mount('/content/gdrive')
import numpy as np
from sklearn.model_selection import train_test_split
!pip install xgboost
from xgboost import XGBClassifier
from sk... | _____no_output_____ | MIT | 01_ICST2020/03_BUildup_transformation.ipynb | achmfirmansyah/sweet_project | |
Sign in to Apple Music and navigate to required song class-name | songs_wrap = driver.find_elements_by_class_name("song-name")
songs = [x.text for x in song_wrap]
song_subdiv = driver.find_elements_by_class_name("song-name-wrapper")
artists_wrap = [x.find_element_by_class_name("dt-link-to") for x in song_subdiv]
artists = [x.text for x in artists_wrap]
len(songs)
len(artists)
'''
T... | _____no_output_____ | MIT | music-app/Data_Scraping/applescraper.ipynb | DL-ify/Music-app |
Copyright 2021 Google LLCLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed und... | # install published dev version
# !pip install cirq~=0.4.0.dev
# install directly from HEAD:
!pip install git+https://github.com/quantumlib/Cirq.git@8c59dd97f8880ac5a70c39affa64d5024a2364d0 | Collecting git+https://github.com/quantumlib/Cirq.git@8c59dd97f8880ac5a70c39affa64d5024a2364d0
Cloning https://github.com/quantumlib/Cirq.git (to revision 8c59dd97f8880ac5a70c39affa64d5024a2364d0) to /tmp/pip-req-build-p85k13_x
Requirement already satisfied: google-api-python-client~=1.6 in /usr/local/lib/python3.6/d... | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
To verify that Cirq is installed in your environment, try to `import cirq` and print out a diagram of the Foxtail device. It should produce a 2x11 grid of qubits. | import cirq
import numpy as np
import matplotlib.pyplot as plt
print(cirq.google.Foxtail) | (0, 0)βββ(0, 1)βββ(0, 2)βββ(0, 3)βββ(0, 4)βββ(0, 5)βββ(0, 6)βββ(0, 7)βββ(0, 8)βββ(0, 9)βββ(0, 10)
β β β β β β β β β β β
β β β β β β β β β β β
(1, 0)βββ(1, 1)βββ(1, 2)βββ(1, 3)βββ(1... | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
The QNN IdeaWe'll begin by describing here the QNN model we are pursuing. We'll discuss the quantum circuit describing a very simple neuron, and how it can be trained. As in an ordinary neural network, a QNN takes in data, processes that data, and then returns an answer. In the quantum case, the data will be encoded i... | a = cirq.NamedQubit("a")
b = cirq.NamedQubit("b")
w = .25 # Put your own weight here.
angle = 2*np.pi*w
circuit = cirq.Circuit.from_ops(cirq.ControlledGate(cirq.Rx(angle)).on(a,b))
print(circuit)
circuit.to_unitary_matrix().round(2) | a: βββ@ββββββββββ
β
b: βββRx(0.5Ο)βββ
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
__Question__: The rotation in the upper-left block is by the opposite angle. But how do we get the rotation to happen in the upper-left block of the $4\times 4$ matrix in the first place? What is the circuit? Solution Switching the upper-left and lower-right blocks of a controlled gate corresponds to activating when t... | a = cirq.NamedQubit("a")
b = cirq.NamedQubit("b")
w = 0.25 # Put your own weight here.
angle = 2*np.pi*w
circuit = cirq.Circuit.from_ops([cirq.X(a),
cirq.ControlledGate(cirq.Rx(-angle)).on(a,b),
cirq.X(a)])
print(circuit)
circuit.to_unitary_matrix().roun... | a: βββXβββ@βββββββββββXβββ
β
b: βββββββRx(-0.5Ο)βββββββ
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
The Full $ZX$ Gate We can put together the two controlled rotations to make the full $ZX$ gate. Having discussed the decomposition already, we can make our own class and specify its action using the `_decpompose_` method. Fill in the following code block to implement this gate. | class ZXGate(cirq.ops.gate_features.TwoQubitGate):
"""ZXGate with variable weight."""
def __init__(self, weight=1):
"""Initializes the ZX Gate up to phase.
Args:
weight: rotation angle, period 2
"""
self.weight = weight
def _decompose_(self, qubits):
a, b = qubits
## YOUR... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Solution | class ZXGate(cirq.ops.gate_features.TwoQubitGate):
"""ZXGate with variable weight."""
def __init__(self, weight=1):
"""Initializes the ZX Gate up to phase.
Args:
weight: rotation angle, period 2
"""
self.weight = weight
def _decompose_(self, qubits):
a, b = qubits
yield c... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
EigenGate ImplementationAnother way to specify how a gate works is by an explicit eigen-action. In our case that is also easy, since we know that the gate acts as a phase (the eigenvalue) when the first qubit is in a $Z$ eigenstate (i.e., a computational basis state) and the second qubit is in an $X$ eigenstate.The wa... | class ZXGate(cirq.ops.eigen_gate.EigenGate,
cirq.ops.gate_features.TwoQubitGate):
"""ZXGate with variable weight."""
def __init__(self, weight=1):
"""Initializes the ZX Gate up to phase.
Args:
weight: rotation angle, period 2
"""
self.weight = weight
super().__init__(... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Solution | class ZXGate(cirq.ops.eigen_gate.EigenGate,
cirq.ops.gate_features.TwoQubitGate):
"""ZXGate with variable weight."""
def __init__(self, weight=1):
"""Initializes the ZX Gate up to phase.
Args:
weight: rotation angle, period 2
"""
self.weight = weight
super().__init__(... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Testing the Gate __BEFORE MOVING ON__ make sure you've executed the `EigenGate` solution of the $ZX$ gate implementation. That's the one assumed for the code below, though other implementations may work just as well. In general, the cells in this Colab may depend on previous cells.Let's test out our gate. First we'll ... | a = cirq.NamedQubit("a")
b = cirq.NamedQubit("b")
w = .15 # Put your own weight here. Try using a cirq.Symbol.
circuit = cirq.Circuit.from_ops(ZXGate(w).on(a,b))
print(circuit) | a: βββZββββββββ
β
b: βββX^0.15βββ
| Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
We should also check that the matrix is what we expect: | test_matrix = np.array([[np.cos(np.pi*w), 1j*np.sin(np.pi*w), 0, 0],
[1j*np.sin(np.pi*w), np.cos(np.pi*w), 0, 0],
[0, 0, np.cos(np.pi*w), -1j*np.sin(np.pi*w)],
[0, 0, -1j*np.sin(np.pi*w),np.cos(np.pi*w)]])
# Test for five digits of accuracy. Won't ... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Create CircuitNow we have to create the QNN circuit. We are simply going to let a $ZX$ gate act between each data qubit and the readout qubit. For simplicity, let's share a single weight between all of the gates. You are invited to experiment with making the weights different, but in our example problem below we can s... | # Total number of data qubits
INPUT_SIZE = 9
data_qubits = cirq.LineQubit.range(INPUT_SIZE)
readout = cirq.NamedQubit('r')
# Initialize parameters of the circuit
params = {'w': 0}
def ZX_layer():
"""Adds a ZX gate between each data qubit and the readout.
All gates are given the same cirq.Symbol for a weight."""
... | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Use this generator to create the QNN circuit. Don't forget to add the basis change for the readout qubit at the end! | qnn = cirq.Circuit()
qnn.append(???) # YOUR CODE HERE | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Solution | qnn = cirq.Circuit()
qnn.append(ZX_layer())
qnn.append([cirq.S(readout)**-1, cirq.H(readout)]) # Basis transformation | _____no_output_____ | Apache-2.0 | colabs/QNN_hands_on.ipynb | derekchen-2/physics-math-tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.