markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
次に、出力テンソルを調べます。 | print(tfq.from_tensor(output_circuit_tensor)) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
以下の例は tfq.layers.AddCircuit を使用せずに実行できますが、TensorFlow 計算グラフに複雑な機能を埋め込む方法を理解する上で役立ちます。
1.2 問題の概要
クラスター状態を準備し、「励起」があるかどうかを検出する量子分類器をトレーニングします。クラスター状態は極めてこじれていますが、古典的コンピュータにおいては必ずしも困難ではありません。わかりやすく言えば、これは論文で使用されているデータセットよりも単純です。
この分類タスクでは、次の理由により、ディープ <a href="https://arxiv.org/pdf/quant-ph/0610099.pdf" class="external">ME... | def generate_data(qubits):
"""Generate training and testing data."""
n_rounds = 20 # Produces n_rounds * n_qubits datapoints.
excitations = []
labels = []
for n in range(n_rounds):
for bit in qubits:
rng = np.random.uniform(-np.pi, np.pi)
excitations.append(cirq.Circ... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
通常の機械学習と同じように、モデルのベンチマークに使用するトレーニングとテストのセットを作成していることがわかります。次のようにすると、データポイントを素早く確認できます。 | sample_points, sample_labels, _, __ = generate_data(cirq.GridQubit.rect(1, 4))
print('Input:', tfq.from_tensor(sample_points)[0], 'Output:', sample_labels[0])
print('Input:', tfq.from_tensor(sample_points)[1], 'Output:', sample_labels[1]) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.5 レイヤーを定義する
上記の図で示すレイヤーを TensorFlow で定義しましょう。
1.5.1 クラスター状態
まず始めに、<a href="https://arxiv.org/pdf/quant-ph/0504097.pdf" class="external">クラスター状態</a>を定義しますが、これには Google が量子回路のプログラミング用に提供している <a href="https://github.com/quantumlib/Cirq" class="external">Cirq</a> フレームワークを使用します。モデルの静的な部分であるため、tfq.layers.AddCircuit 機能を使用して... | def cluster_state_circuit(bits):
"""Return a cluster state on the qubits in `bits`."""
circuit = cirq.Circuit()
circuit.append(cirq.H.on_each(bits))
for this_bit, next_bit in zip(bits, bits[1:] + [bits[0]]):
circuit.append(cirq.CZ(this_bit, next_bit))
return circuit | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
矩形の <a href="https://cirq.readthedocs.io/en/stable/generated/cirq.GridQubit.html" class="external"><code>cirq.GridQubit</code></a> のクラスター状態回路を表示します。 | SVGCircuit(cluster_state_circuit(cirq.GridQubit.rect(1, 4))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.5.2 QCNN レイヤー
<a href="https://arxiv.org/abs/1810.03787" class="external">Cong and Lukin の QCNN に関する論文</a>を使用して、モデルを構成するレイヤーを定義します。これには次の前提条件があります。
<a href="https://arxiv.org/abs/quant-ph/0507171" class="external">Tucci の論文</a>にある 1 キュービットと 2 キュービットのパラメータ化されたユニタリ―行列
一般的なパラメータ化された 2 キュービットプーリング演算 | def one_qubit_unitary(bit, symbols):
"""Make a Cirq circuit enacting a rotation of the bloch sphere about the X,
Y and Z axis, that depends on the values in `symbols`.
"""
return cirq.Circuit(
cirq.X(bit)**symbols[0],
cirq.Y(bit)**symbols[1],
cirq.Z(bit)**symbols[2])
def two_qu... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
作成したものを確認するために、1 キュービットのユニタリー回路を出力しましょう。 | SVGCircuit(one_qubit_unitary(cirq.GridQubit(0, 0), sympy.symbols('x0:3'))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
次に、2 キュービットのユニタリー回路を出力します。 | SVGCircuit(two_qubit_unitary(cirq.GridQubit.rect(1, 2), sympy.symbols('x0:15'))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
そして 2 キュービットのプーリング回路を出力します。 | SVGCircuit(two_qubit_pool(*cirq.GridQubit.rect(1, 2), sympy.symbols('x0:6'))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.5.2.1 量子畳み込み
<a href="https://arxiv.org/abs/1810.03787" class="external">Cong と Lukin</a> の論文にあるとおり、1 次元量子畳み込みを、ストライド 1 の隣接するすべてのキュービットペアに 2 キュービットのパラメーター化されたユニタリの適用として定義します。 | def quantum_conv_circuit(bits, symbols):
"""Quantum Convolution Layer following the above diagram.
Return a Cirq circuit with the cascade of `two_qubit_unitary` applied
to all pairs of qubits in `bits` as in the diagram above.
"""
circuit = cirq.Circuit()
for first, second in zip(bits[0::2], bit... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
(非常に水平な)回路を表示します。 | SVGCircuit(
quantum_conv_circuit(cirq.GridQubit.rect(1, 8), sympy.symbols('x0:15'))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.5.2.2 量子プーリング
量子プーリングレイヤーは、上記で定義された 2 キュービットプールを使用して、$N$ キュービットから $\frac{N}{2}$ キュービットまでをプーリングします。 | def quantum_pool_circuit(source_bits, sink_bits, symbols):
"""A layer that specifies a quantum pooling operation.
A Quantum pool tries to learn to pool the relevant information from two
qubits onto 1.
"""
circuit = cirq.Circuit()
for source, sink in zip(source_bits, sink_bits):
circuit +... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
プーリングコンポーネント回路を調べます。 | test_bits = cirq.GridQubit.rect(1, 8)
SVGCircuit(
quantum_pool_circuit(test_bits[:4], test_bits[4:], sympy.symbols('x0:6'))) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.6 モデルの定義
定義したレイヤーを使用して純粋な量子 CNN を構築します。8 キュービットで開始し、1 キュービットまでプールダウンしてから、$\langle \hat{Z} \rangle$ を測定します。 | def create_model_circuit(qubits):
"""Create sequence of alternating convolution and pooling operators
which gradually shrink over time."""
model_circuit = cirq.Circuit()
symbols = sympy.symbols('qconv0:63')
# Cirq uses sympy.Symbols to map learnable variables. TensorFlow Quantum
# scans incomin... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1.7 モデルをトレーニングする
この例を単純化するために、完全なバッチでモデルをトレーニングします。 | # Generate some training data.
train_excitations, train_labels, test_excitations, test_labels = generate_data(
cluster_state_bits)
# Custom accuracy metric.
@tf.function
def custom_accuracy(y_true, y_pred):
y_true = tf.squeeze(y_true)
y_pred = tf.map_fn(lambda x: 1.0 if x >= 0 else -1.0, y_pred)
retur... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
2. ハイブリッドモデル
量子畳み込みを使用して 8 キュービットから 1 キュービットにする必要はありません。量子畳み込みの 1~2 ラウンドを実行し、結果を従来のニューラルネットワークにフィードすることも可能です。このセクションでは、量子と従来のハイブリッドモデルを説明します。
2.1 単一量子フィルタを備えたハイブリッドモデル
量子畳み込みのレイヤーを 1 つ適用し、すべてのビットの $\langle \hat{Z}_n \rangle$ を読み取り、続いて密に接続されたニューラルネットワークを読み取ります。
<img src="./images/qcnn_5.png" width="1000">
2.1.1 モデルの定義 | # 1-local operators to read out
readouts = [cirq.Z(bit) for bit in cluster_state_bits[4:]]
def multi_readout_model_circuit(qubits):
"""Make a model circuit with less quantum pool and conv operations."""
model_circuit = cirq.Circuit()
symbols = sympy.symbols('qconv0:21')
model_circuit += quantum_conv_c... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
2.1.2 モデルをトレーニングする | hybrid_model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.02),
loss=tf.losses.mse,
metrics=[custom_accuracy])
hybrid_history = hybrid_model.fit(x=train_excitations,
y=train_labels,
batch_size=16,... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
ご覧のとおり、非常に控えめな古典的支援により、ハイブリッドモデルは通常、純粋な量子バージョンよりも速く収束します。
2.2 多重量子フィルタを備えたハイブリッド畳み込み
多重量子畳み込みと従来のニューラルネットワークを使用してそれらを組み合わせるアーキテクチャを試してみましょう。
<img src="./images/qcnn_6.png" width="1000">
2.2.1 モデルの定義 | excitation_input_multi = tf.keras.Input(shape=(), dtype=tf.dtypes.string)
cluster_state_multi = tfq.layers.AddCircuit()(
excitation_input_multi, prepend=cluster_state_circuit(cluster_state_bits))
# apply 3 different filters and measure expectation values
quantum_model_multi1 = tfq.layers.PQC(
multi_readout_m... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
2.2.2 モデルをトレーニングする | multi_qconv_model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.02),
loss=tf.losses.mse,
metrics=[custom_accuracy])
multi_qconv_history = multi_qconv_model.fit(x=train_excitations,
y=train_labels,
batch_si... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
Design a technique to construct smooth scalar signals $x \in \mathbb{R}^N$ over the graph $\mathcal{G}$.
Hint:
* This part is related to our last exercise.
* There is multiple ways to do this, another is to filter random signals. | # Fourier basis.
D = W.sum(axis=0)
D = scipy.sparse.diags(D.A.squeeze(), 0)
L = D - W
lamb, U = np.linalg.eigh(L.toarray())
# Low-pass filters.
def f1(u, a=4):
y = np.zeros(u.shape)
y[:a] = 1
return y
def f2(u, m=4):
return np.maximum(1 - m * u / u[-1], 0)
def f3(u, a=0.8):
return np.exp(-u / a)
... | algorithms/08_sol_graph_inpainting.ipynb | mdeff/ntds_2016 | mit |
2 Graph Signal Inpainting
Let $y$ be a signal obtained by observing $n$ out the $N$ entries of a smooth signal $x$. Design and implement a procedure to infer the missing values and test its average accuracy $\| x^\ast - x \|_2^2$ as a function of $n/N$ on a test set of signals created using the technique developed abov... | tau = 1e5 # Balance between fidelity and smoothness prior.
num = 100 # Number of signals and masks to generate.
# Percentage of values to keep.
probs = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0, 0.1, 0.2, 0.3]
errors = []
for p in probs:
mse = 0
for _ in range(num):
# Smooth signal.
x = np.random.uni... | algorithms/08_sol_graph_inpainting.ipynb | mdeff/ntds_2016 | mit |
Basic problems
Prediction of the next value of sequence
sequence of (110)+
Just a repeated pattern:
110110110110110...
Classification of sequences
The inputs/outputs must be tensors of shape (samples, time_steps, features).
In this case (1, len(X), 1).
For simplicity we have a single training example and no test test.
... | X = np.array([[[1],[1],[0]], [[1],[0],[1]], [[0],[1],[1]]])
y = np.array([[1], [1], [0]])
# X = np.array([[[1],[0],[0]], [[0],[1],[0]], [[0],[0],[1]]])
# y = np.array([[1], [0], [0]])
# input: 3 samples of 3-step sequences with 1 feature
# input: 3 samples with 1 feature
X.shape, y.shape | snippets/keras/lstm_hello_world.ipynb | bzamecnik/ml | mit |
Basic usage of LTSM layers in Keras
Notes:
the first layer must specify the input shape
TensorFlow needs explicit length of series, so input_shape or batch_input_shape must be used, not just input_dim
when specifying batch_input_shape in LSTM, we need to explicitly add batch_size to model.fit() | from keras.models import Sequential
from keras.layers.core import Dense, Activation, TimeDistributedDense
from keras.layers.recurrent import LSTM
# model = Sequential()
# # return_sequences=False
# model.add(LSTM(output_dim=1, input_shape=(3, 1)))
# # since the LSTM layer has only one output after activation we can di... | snippets/keras/lstm_hello_world.ipynb | bzamecnik/ml | mit |
LSTM weight meanings:
http://colah.github.io/posts/2015-08-Understanding-LSTMs/
source code LSTM in recurrent.py
[W_i, U_i, b_i,
W_c, U_c, b_c,
W_f, U_f, b_f,
W_o, U_o, b_o]
Type of weights:
- W - weight matrix - from input to output
- b - bias vector - from input to output
- U - weight matrix - from hidden to ou... | weight_names = ['W_i', 'U_i', 'b_i',
'W_c', 'U_c', 'b_c',
'W_f', 'U_f', 'b_f',
'W_o', 'U_o', 'b_o']
weight_shapes = [w.shape for w in model.get_weights()]
# for n, w in zip(weight_names, weight_shapes):
# print(n, ':', w)
print(weight_shapes)
def pad_vector_shape(s):
return (s[0], 1) if len(s) == 1 else s
... | snippets/keras/lstm_hello_world.ipynb | bzamecnik/ml | mit |
Read in data | rm = ReleaseManager('v1.0b4')
db = io.DBManager()
db.n_image_names
db.dbname
blotches = rm.read_blotch_file()
fans = rm.read_fan_file() | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Get original input stats | import dask.dataframe as dd
data = dd.read_hdf(db.dbname, 'df')
fan_input = data[data.marking=='fan']
blotch_input = data[data.marking=='blotch']
fan_input.compute().shape
blotch_input.compute().shape | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Convert distance to meters | fans['distance_m'] = fans.distance*fans.map_scale
blotches['radius_1_m'] = blotches.radius_1*blotches.map_scale
blotches['radius_2_m'] = blotches.radius_2*blotches.map_scale | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Reduction of number of fan markings to finals | n_fan_in = 2792963
fans.shape[0]
fans.shape[0] / n_fan_in
blotches.shape[0] | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Length stats
Percentage of fan markings below 100 m: | import scipy
scipy.stats.percentileofscore(fans.distance_m, 100) | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Cumulative histogram of fan lengths | def add_percentage_line(ax, meters, column):
y = scipy.stats.percentileofscore(column, meters)
ax.axhline(y/100)
ax.axvline(meters)
ax.text(meters, y/100, f"{y/100:0.2f}")
plt.close('all')
fig, ax = plt.subplots(figsize=(8,4))
sns.distplot(fans.distance_m, bins=500, kde=False, hist_kws={'cumulative':T... | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
General fan stats, in numbers | fans.distance_m.describe() | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
In words, the mean length of fans is {{f"{fans.distance_m.describe()['mean']:.1f}"}} m, while the median is
{{f"{fans.distance_m.describe()['50%']:.1f}"}} m.
Blotch sizes | plt.figure()
cols = ['radius_1','radius_2']
sns.distplot(blotches[cols], kde=False, bins=np.arange(2.0,50.),
color=['r','g'], label=cols)
plt.legend()
plt.figure()
cols = ['radius_1_m','radius_2_m']
sns.distplot(blotches[cols], kde=False, bins=np.arange(2.0,50.),
color=['r','g'], label=cols... | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Longest fans | fans.query('distance_m > 350')[
'distance_m distance obsid image_x image_y image_id x_tile y_tile'.split()].sort_values(
by='distance_m')
users1 = markings.ImageID("APF0000dtk").data.user_name.unique()
users2 = markings.ImageID("de3").data.user_name.unique()
same = []
for user in users1:
if user in u... | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Regional | from planet4 import stats
from planet4 import region_data
stats.define_season_column(fans)
stats.define_season_column(blotches)
regions = ['Manhattan2', 'Giza', 'Inca', 'Ithaca']
for reg in regions:
obj = getattr(region_data, reg)
roi = obj()
for marking in [fans, blotches]:
if reg == 'Manhattan2... | notebooks/LPSC 2018 stats.ipynb | michaelaye/planet4 | isc |
Let's see what's in this document | len(document.split('\n'))
document.split('\n')[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
It looks like we've gotten ourselves a bit of the script from Monty Python and the Holy Grail. Note that when we are looking at the text, part of the structure of the document is written in tokens. For example, stage directions have been placed in brackets, and the names of the person speaking are in all caps.
Regular ... | import re
snippet = "I fart in your general direction! Your mother was a hamster, and your father smelt of elderberries!"
re.search(r'mother', snippet) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Just like with str.find, we can search for plain text. But re also gives us the option for searching for patterns of bytes - like only alphabetic characters. | re.search(r'[a-z]', snippet) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
In this case, we've told re to search for the first sequence of bytes that is only composed of lowercase letters between a and z. We could get the letters at the end of each sentence by including a bang at the end of the pattern. | re.search(r'[a-z]!', snippet) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
If we wanted to pull out just the stage directions from the screenplay, we might try a pattern like this: | re.findall(r'[a-zA-Z]', document)[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
So that's obviously no good. There are two things happening here:
[ and ] do not mean 'bracket'; they are special characters which mean 'any thing of this class'
we've only matched one letter each
A better regular expression, then, would wrap this in escaped brackets, and include a command saying more than one letter... | re.findall(r'\[[a-zA-Z]+\]', document)[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
This is better, but it's missing that [clop clop clop] we saw above. This is because we told the regex engine to match any alphabetic character, but we did not specify whitespaces, commas, etc. to match these, we'll use the dot operator, which will match anything expect a newline.
Part of the power of regular expressio... | snippet = 'This is [cough cough] and example of a [really] greedy operator'
re.findall(r'\[.+\]', snippet) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Since the operator is greedy, it is matching everything inbetween the first open and the last close bracket. To make + consume the least possible amount of string, we'll add a ?. | p = re.compile(r'\[.+?\]')
re.findall(p, document)[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
What if we wanted to grab all of Arthur's speech? This one is a little trickier, since:
It is not conveniently bracketed; and,
We want to match on ARTHUR, but not to capture it
If we wanted to do this using base string manipulation, we would need to do something like:
split the document into lines
create a new list o... | p = re.compile(r'(?:ARTHUR: )(.+)')
re.findall(p, document)[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Because we are using findall, the regex engine is capturing and returning the normal groups, but not the non-capturing group. For complicated, multi-piece regular expressions, you may need to pull groups out separately. You can do this with names. | p = re.compile(r'(?P<name>[A-Z ]+)(?::)(?P<line>.+)')
match = re.search(p, document)
match
match.group('name'), match.group('line') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Now let's try a small challenge!
To check that you've understood something about regular expressions, we're going to have you do a small test challenge. Partner up with the person next to you - we're going to do this as a pair coding exercise - and choose which computer you are going to use.
Then, navigate to challenge... | p = re.compile(r'(?:ARTHUR: )(.+)')
arthur = ' '.join(re.findall(p, document))
arthur[0:100] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
In our model for natural language, we're interested in words. The document is currently a continuous string of bytes, which isn't ideal. You might be tempted to separate this into words using your newfound regex knowledge: | p = re.compile(r'\w+', flags=re.I)
re.findall(p, arthur)[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
But this is problematic for languages that make extensive use of punctuation. For example, see what happens with: | re.findall(p, "It isn't Dav's cheesecake that I'm worried about") | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
The practice of pulling apart a continuous string into units is called "tokenizing", and it creates "tokens". NLTK, the canonical library for NLP in Python, has a couple of implementations for tokenizing a string into words. | from nltk import word_tokenize
word_tokenize("It isn't Dav's cheesecake that I'm worried about") | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
The distinction here is subtle, but look at what happened to "isn't". It's been separated into "IS" and "N'T", which is more in keeping with the way contractions work in English. | tokens = word_tokenize(arthur)
tokens[0:10] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
At this point, we can start asking questions like what are the most common words, and what words tend to occur together. | len(tokens), len(set(tokens)) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
So we can see right away that Arthur is using the same words a whole bunch - on average, each unique word is used four times. This is typical of natural language.
Not necessarily the value, but that the number of unique words in any corpus increases much more slowly than the total number of words.
A corpus with 100M ... | from nltk import collocations
fd = collocations.FreqDist(tokens)
fd.most_common()[:10]
measures = collocations.BigramAssocMeasures()
c = collocations.BigramCollocationFinder.from_words(tokens)
c.nbest(measures.pmi, 10)
c.nbest(measures.likelihood_ratio, 10) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
We see here that the collocation finder is pulling out some things that have face validity. When Arthur is talking about peasants, he calls them "bloody" more often than not. However, collocations like "Brother Maynard" and "BLACK KNIGHT" are less informative to us, because we know that they are proper names.
If you we... | snowball = nltk.SnowballStemmer('english') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Now, we can try stemming some words | snowball.stem('running')
snowball.stem('eats')
snowball.stem('embarassed') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Snowball is a very fast algorithm, but it has a lot of edge cases. In some cases, words with the same stem are reduced to two different stems. | snowball.stem('cylinder'), snowball.stem('cylindrical') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
In other cases, two different words are reduced to the same stem.
This is sometimes referred to as a 'collision' | snowball.stem('vacation'), snowball.stem('vacate')
snowball.stem('organization'), snowball.stem('organ')
snowball.stem('iron'), snowball.stem('ironic')
snowball.stem('vertical'), snowball.stem('vertices') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
A more accurate approach is to use an English word bank like WordNet to call dictionary lookups on word forms, in a process called lemmatization. | # nltk.download('wordnet')
wordnet = nltk.WordNetLemmatizer()
wordnet.lemmatize('iron'), wordnet.lemmatize('ironic')
wordnet.lemmatize('vacation'), wordnet.lemmatize('vacate') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Nothing comes for free, and you've probably noticed already that the lemmatizer is slower. We can see how much slower with one of IPYthon's magic functions. | %timeit wordnet.lemmatize('table')
4.45 * 5.12
%timeit snowball.stem('table') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Time for another small challenge!
Switch computers for this one, so that you are using your partner's computer, and try your hand at challenge B!
Sentiment
Frequently, we are interested in text to learn something about the person who is speaking. One of these things we've talked about already - linguistic diversity. A ... | from textblob import TextBlob
blob = TextBlob(arthur)
for sentence in blob.sentences[10:25]:
print(sentence.sentiment.polarity, sentence) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Semantic distance
Another common NLP task is to look for semantic distance between documents. This is used by search engines like Google (along with other things like PageRank) to decide which websites to show you when you search for things like 'bike' versus 'motorcycle'.
It is also used to cluster documents into topi... | from gensim import corpora, models, similarities | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
We already have a document for Arthur, but let's grab the text from someone else to compare it with. | p = re.compile(r'(?:GALAHAD: )(.+)')
galahad = ' '.join(re.findall(p, document))
arthur_tokens = tokens
galahad_tokens = word_tokenize(galahad) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Now, we use gensim to create vectors from these tokenized documents: | dictionary = corpora.Dictionary([arthur_tokens, galahad_tokens])
corpus = [dictionary.doc2bow(doc) for doc in [arthur_tokens, galahad_tokens]]
tfidf = models.TfidfModel(corpus, id2word=dictionary) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Then, we create matrix models of our corpus and query | query = tfidf[dictionary.doc2bow(['peasant'])]
index = similarities.MatrixSimilarity(tfidf[corpus]) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
And finally, we can test our query, "peasant" on the two documents in our corpus | list(enumerate(index[query])) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
So we see here that "peasant" does not match Galahad very well (a really bad match would have a negative value), and is more similar to the kind of speach output that we see from King Arthur.
Tabular data
In data storage, data visualization, inferential statistics, and machine learning, the most common way to pass data... | import pandas as pd | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
You might not have seen this as convention yet. It is just telling python that when we import pandas, we don't want to access it in the namespace as pandas but as pd instead.
Pandas basics
We'll start by making a small table to practice on. Tables in pandas are called data frames, so we'll start by making an instance o... | table = pd.DataFrame({'id': [1,2,3], 'name':['dillon','juan','andrew'], 'age':[47,27,23]})
print(table) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Variables in pandas are represented by a pandas-specific data structure, called a Series. You can grab a Series out of a DataFrame by using the slicing operator with the name of the variable that you want to pull. | table['name'], type(table['name']) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
We could have made each variable a Series, and then put it into the DataFrame object, but it's easier in this instance to pass in a dictionary where the keys are variable names and the values are lists. You can also modify a data frame in place using similar syntax: | table['fingers'] = [9, 10, None] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
If you try to run that code without the None there, pandas will return an error. In a table (in any language) each column must have the same number of rows.
We've entered None, base python's missingness indicator, but pandas is going to swap this out with something else: | table['fingers'] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
You might be tempted to write your own control structures around these missing values (which are variably called NaN, nan, and NA), but this is always a bad idea: | table['fingers'][2] == None
table['fingers'][2] == 'NaN'
type(table['fingers'][2]) == str | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
None of this works because the pandas NaN is a subclass of numpy's double precision floating point number. However, for ambiguous reasons, even numpy.nan does not evaluate as being equal to itself.
To handle missing data, you'll need to use the pandas method isnull. | pd.isnull(table['fingers']) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
In the same way that we've been pulling out columns by name, you can pull out rows by index. If I want to grab the first row, I can use: | table[:1] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Recall that indices in python start at zero, and that selecting by a range does not include the final value (i.e. [ , )).
Unlike other software languages (R, I'm looking at you here), row indices in pandas are immutable. So, if I rearrange my data, the index also get shuffled. | table.sort_values('age') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Because of this, it's common to set the index to be something like a timestamp or UUID.
We can select parts of a DataFrame with conditional statements: | table[table['age'] < 40] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Merging tables
As you might expect, tables in pandas can also be merged by keys. So, if we make a new dataset that shares an attribute in common: | other_table = pd.DataFrame({
'name':['dav', 'juan', 'dillon'],
'languages':['python','python','python']})
table.merge(other_table, on='name') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Note that we have done an "inner join" here, which means we are only getting the intersection of the two tables. If we want the union, we can specify that we want an outer join: | table.merge(other_table, on='name', how='outer') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Or maybe we want all of the data from table, but not other_table | table.merge(other_table, on='name', how='left') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Reshaping
To make analysis easier, you may have to reshape your data. It's easiest to deal with data when each table meets the follwing criteria:
Each row is exactly one observation
Each column is exactly one kind of data
The table expresses one and only one relationship between observations and variables
This kind o... | wide_table = pd.DataFrame({'name' : ['dillon', 'juan', 'dav'],
'city1' : ['williamsburg', 'berkeley', 'cambridge'],
'city2' : ['berkeley', 'berkeley', 'berkeley'],
'population' : [110, 110, 110]
})
wide_table | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
We can make this longer in pandas using the melt function | long_table = pd.melt(wide_table, id_vars = ['name'])
long_table | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
We can make the table wider using the pivot method
side note - this kind of inconsistency between melt and pivot is un-pythonic and should not be emulated | long_table.pivot(columns='variable') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
WHOA
One of the really cool things about pandas is that it allows you to have multiple indexes for rows and columns. Since pandas couldn't figure out what do with two kinds of value variables, it doubled up our column index. We can fix this by specifying that we only want the 'values' values | long_table.pivot(columns='variable', values='value') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Challenge time!
Switch computers again so that you are working on the first computer of the day, and have a look at challenge C. This will have you practice reading and merging tables. Again, when you are finished, check your work by running py.test test_C in a shell.
Descriptive statistics
Single descriptives have the... | table['fingers'].mean()
table['fingers'].std()
table['fingers'].quantile(.25)
table['fingers'].kurtosis() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
You can call several of these at once with the describe method | table.describe() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Inferential statistics
pandas does not have statistical functions baked in, so we are going to call them from the scipy.stats library and the statmodels scikit.
We are also going to load in an actual dataset, as stats examples aren't very interesting with tiny bits of fake data. | from scipy import stats
data = pd.read_csv('../data/03_feedback.csv') | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Using what you've learned so far about manipulating pandas objects, how would you find out the names of the variables in this dataset? Their datatypes? The distribution of their values?
Comparisons of group means
A common statistical procedure is to look for differences between groups of values. Typically, the values a... | i = data['inside.barriers'].dropna()
o = data['outside.barriers'].dropna()
stats.ttest_ind(i, o) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Notice that here, we are passing in two whole columns, but we could also be subsetting by some other factor.
If you have more than two groups (or levels) that you would like to compare, you'll have to use something like an ANOVA: | m = data[data.gender == "Male/Man"]['outside.barriers'].dropna()
f = data[data.gender == "Female/Woman"]['outside.barriers'].dropna()
q = data[data.gender == "Genderqueer/Gender non-conforming"]['outside.barriers'].dropna()
stats.f_oneway(m, f, q) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Linear relationships
Another common task is to establish if/how two variables are related across linear space. This could be something, for example, like relating shoe size to height. Here, we are going to ask whether barriers to access to technology inside and outside of the D-Lab are related.
One implementation of li... | intermediate = data.dropna(subset=['inside.barriers', 'outside.barriers'])
stats.pearsonr(intermediate['outside.barriers'], intermediate['inside.barriers']) | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
At this point, we're going to pivot to using statsmodels | import statsmodels.formula.api as smf | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
The formulas module in statsmodels lets us work with pandas dataframes, and linear model specifications that are similar to R and other variants of statistical software, e.g.:
outcome ~ var1 + var2 | model_1 = smf.ols("inside_barriers ~ outside_barriers", data=data).fit()
model_1 | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
To get a summary of the test results, call the model's summary method | model_1.summary() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Since Python does not have private data or hidden attributes, you can pull out just about any intermediate information you want, including coefficients, residuals, and eigenvalues
Raymond Hettinger would say that Python is a "consenting adult language" | model_1.params['outside_barriers'] | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
statsmodels also exposes methods for validity checking your regressions, like looking for outliers by influence statistics | model_1.get_influence().summary_frame() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
If, at this stage, you suspect that one or more outliers is unduly influencing your model fit, you can transform your results into robust OLS with a method call: | model_1.get_robustcov_results().summary() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
This isn't very different, so we're probably okay.
If you want to add more predictors to your model, you can do so inside the function string: | smf.ols("inside_barriers ~ outside_barriers + gender", data=data).fit().summary() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Note that our categorical/factor variable has been automatically one-hot encoded as treatment conditions. There's not way to change this within statsmodels, but you can specify your contrasts indirectly using a library called (Patsy)[http://statsmodels.sourceforge.net/stable/contrasts.html].
To add interactions to your... | smf.ols("inside_barriers ~ outside_barriers * gender", data=data).fit().summary() | instructor/day_three.ipynb | deniederhut/workshop_pyintensive | bsd-2-clause |
Getting started with BigQuery ML
BigQuery ML enables users to create and execute machine learning models in BigQuery using SQL queries. The goal is to democratize machine learning by enabling SQL practitioners to build models using their existing tools and to increase development speed by eliminating the need for data ... | from google.cloud import bigquery
client = bigquery.Client(location="US") | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Next, you create a BigQuery dataset to store your ML model. Run the following to create your dataset: | dataset = client.create_dataset("bqml_tutorial") | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Create your model
Next, you create a logistic regression model using the Google Analytics sample
dataset for BigQuery. The model is used to predict whether a
website visitor will make a transaction. The standard SQL query uses a
CREATE MODEL statement to create and train the model. Standard SQL is the
default query syn... | %%bigquery
CREATE OR REPLACE MODEL `bqml_tutorial.sample_model`
OPTIONS(model_type='logistic_reg') AS
SELECT
IF(totals.transactions IS NULL, 0, 1) AS label,
IFNULL(device.operatingSystem, "") AS os,
device.isMobile AS is_mobile,
IFNULL(geoNetwork.country, "") AS country,
IFNULL(totals.pageviews, 0) AS pagevie... | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
The query takes several minutes to complete. After the first iteration is
complete, your model (sample_model) appears in the navigation panel of the
BigQuery web UI. Because the query uses a CREATE MODEL statement to create a
table, you do not see query results. The output is an empty DataFrame.
Get training statistics... | %%bigquery
SELECT
*
FROM
ML.TRAINING_INFO(MODEL `bqml_tutorial.sample_model`) | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Note: Typically, it is not a best practice to use a SELECT * query. Because the model output is a small table, this query does not process a large amount of data. As a result, the cost is minimal.
When the query is complete, the results appear below the query. The results should look like the following:
The loss colum... | %%bigquery
SELECT
*
FROM ML.EVALUATE(MODEL `bqml_tutorial.sample_model`, (
SELECT
IF(totals.transactions IS NULL, 0, 1) AS label,
IFNULL(device.operatingSystem, "") AS os,
device.isMobile AS is_mobile,
IFNULL(geoNetwork.country, "") AS country,
IFNULL(totals.pageviews, 0) AS pageviews
FROM
... | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
When the query is complete, the results appear below the query. The
results should look like the following:
Because you performed a logistic regression, the results include the following
columns:
precision
recall
accuracy
f1_score
log_loss
roc_auc
Use your model to predict outcomes
Now that you have evaluated your m... | %%bigquery
SELECT
country,
SUM(predicted_label) as total_predicted_purchases
FROM ML.PREDICT(MODEL `bqml_tutorial.sample_model`, (
SELECT
IFNULL(device.operatingSystem, "") AS os,
device.isMobile AS is_mobile,
IFNULL(totals.pageviews, 0) AS pageviews,
IFNULL(geoNetwork.country, "") AS country
FR... | notebooks/official/template_notebooks/getting_started_bigquery_ML.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.