markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Complexity ?
$\implies$ The function lempel_ziv_complexity_cython seems to be indeed (almost) linear in $n$, the length of the binary sequence $S$.
But let check more precisely, as it could also have a complexity of $\mathcal{O}(n \log n)$. | import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set(context="notebook", style="darkgrid", palette="hls", font="sans-serif", font_scale=1.4)
import numpy as np
import timeit
sizes = np.array(np.trunc(np.logspace(1, 6, 30)), dtype=int)
times = np.array([
timeit.timeit(
stmt="le... | Short_study_of_the_Lempel-Ziv_complexity.ipynb | Naereen/Lempel-Ziv_Complexity | mit |
It is linear in $\log\log$ scale, so indeed the algorithm seems to have a linear complexity.
To sum-up, for a sequence $S$ of length $n$, it takes $\mathcal{O}(n)$ basic operations to compute its Lempel-Ziv complexity $\mathrm{Lempel}-\mathrm{Ziv}(S)$.
Conclusion
The Lempel-Ziv complexity is not too hard to implemen... | %%time
%%script julia
"""Lempel-Ziv complexity for a sequence, in simple Julia code."""
function lempel_ziv_complexity(sequence)
sub_strings = Set()
n = length(sequence)
ind = 1
inc = 1
while true
if ind + inc > n
break
end
sub_str = sequence[ind : ind + inc]
... | Short_study_of_the_Lempel-Ziv_complexity.ipynb | Naereen/Lempel-Ziv_Complexity | mit |
And to compare it fairly, let us use Pypy for comparison. | %%time
%%pypy
def lempel_ziv_complexity(sequence):
"""Lempel-Ziv complexity for a binary sequence, in simple Python code."""
sub_strings = set()
n = len(sequence)
ind = 0
inc = 1
while True:
if ind + inc > len(sequence):
break
sub_str = sequence[ind : ind + inc]
... | Short_study_of_the_Lempel-Ziv_complexity.ipynb | Naereen/Lempel-Ziv_Complexity | mit |
Load learner object
Note: you don't have to do this over and over again, you just have to call learn.export() to save the learner after you have loaded everything. | data_lm = load_data(data_path, bs=96)
learn = language_model_learner(data=data_lm,
arch=AWD_LSTM,
model_dir=model_path,
pretrained=False) | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
Load weights of trained model | learn.load('best_22zkdqlr') | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
Export Minimal Model State For Inference | learn.export('trained_model_22zkdqlr.hdf')
learn.save_encoder('trained_model_encoder_22zkdqlr') | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
The data is very large so if you are running this notebook best to release memory by deleting these objects and loading the more lightweight inference artifacts that we just saved. | del learn
del data_lm | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
Part II: Load Minimal Model For Inference | from inference import InferenceWrapper, pass_through | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
Create an InferenceWrapper object | wrapper = InferenceWrapper(model_path='/ds/lang_model/models_22zkdqlr/',
)
issue_string = '# hello abacadabra world \nA second line **something bold**.'
pooledfeat = wrapper.get_pooled_features(issue_string)
print(pooledfeat)
print(pooledfeat.shape)
rawfeat = wrapper.get_raw_features(issue... | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
Predict the next 5 words
We don't actually use this functionality, but it is interesting to see for those who are curious what the output of a langauge model is. Recall that we are using the encoder of the language model to extract features from GitHub issues. | wrapper.learn.predict('I am having trouble opening a', 5) | Issue_Embeddings/notebooks/04_Inference.ipynb | kubeflow/code-intelligence | mit |
<a id='twotime'></a>
Two-Time Correlation Functions
With the QuTiP time-evolution functions (for example mesolve and mcsolve), a state vector or density matrix can be evolved from an initial state at :math:t_0 to an arbitrary time $t$, $\rho(t)=V(t, t_0)\left{\rho(t_0)\right}$, where $V(t, t_0)$ is the propagator defin... | times = np.linspace(0,10.0,200)
a = destroy(10)
x = a.dag() + a
H = a.dag() * a
corr1 = correlation_2op_1t(H, None, times, [np.sqrt(0.5) * a], x, x)
corr2 = correlation_2op_1t(H, None, times, [np.sqrt(1.0) * a], x, x)
corr3 = correlation_2op_1t(H, None, times, [np.sqrt(2.0) * a], x, x)
plot(times, np.real(corr1), time... | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
<a id='emission'></a>
Emission Spectrum
Given a correlation function $\left<A(\tau)B(0)\right>$ we can define the corresponding power spectrum as
$$
S(\omega) = \int_{-\infty}^{\infty} \left<A(\tau)B(0)\right> e^{-i\omega\tau} d\tau.
$$
In QuTiP, we can calculate $S(\omega)$ using either spectrum, which first calculate... | N = 4 # number of cavity fock states
wc = wa = 1.0 * 2 * np.pi # cavity and atom frequency
g = 0.1 * 2 * np.pi # coupling strength
kappa = 0.75 # cavity dissipation rate
gamma = 0.25 # atom dissipation rate
# Jaynes-Cummings Hamiltonian
a = tensor(destroy(N), q... | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
<a id='nonsteady'></a>
Non-Steady State Correlation Function
More generally, we can also calculate correlation functions of the kind $\left<A(t_1+t_2)B(t_1)\right>$, i.e., the correlation function of a system that is not in its steadystate. In QuTiP, we can evoluate such correlation functions using the function correla... | times = np.linspace(0, 10.0, 200)
a = destroy(10)
x = a.dag() + a
H = a.dag() * a
alpha = 2.5
rho0 = coherent_dm(10, alpha)
corr = correlation_2op_2t(H, rho0, times, times, [np.sqrt(0.25) * a], x, x)
pcolor(np.real(corr))
colorbar()
xlabel(r'Time $t_2$')
ylabel(r'Time $t_1$')
title(r'Correlation $\left<x(t)x(0)\right>... | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
However, in some cases we might be interested in the correlation functions on the form $\left<A(t_1+t_2)B(t_1)\right>$, but only as a function of time coordinate $t_2$. In this case we can also use the correlation_2op_2t function, if we pass the density matrix at time $t_1$ as second argument, and None as third argumen... | N = 15
taus = np.linspace(0,10.0,200)
a = destroy(N)
H = 2 * np.pi * a.dag() * a
# collapse operator
G1 = 0.75
n_th = 2.00 # bath temperature in terms of excitation number
c_ops = [np.sqrt(G1 * (1 + n_th)) * a, np.sqrt(G1 * n_th) * a.dag()]
# start with a coherent state
rho0 = coherent_dm(N, 2.0)
# first calculate ... | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
For convenience, the steps for calculating the first-order coherence function have been collected in the function coherence_function_g1.
Example: Second-Order Optical Coherence Function
The second-order optical coherence function, with time-delay $\tau$, is defined as
$$
\displaystyle g^{(2)}(\tau) = \frac{\langle a^\d... | N = 25
taus = np.linspace(0, 25.0, 200)
a = destroy(N)
H = 2 * np.pi * a.dag() * a
kappa = 0.25
n_th = 2.0 # bath temperature in terms of excitation number
c_ops = [np.sqrt(kappa * (1 + n_th)) * a, np.sqrt(kappa * n_th) * a.dag()]
states = [{'state': coherent_dm(N, np.sqrt(2)), 'label': "coherent state"},
... | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
For convenience, the steps for calculating the second-order coherence function have been collected in the function coherence_function_g2. | from IPython.core.display import HTML
def css_styling():
styles = open("../styles/guide.css", "r").read()
return HTML(styles)
css_styling() | docs/guide/CorrelationFunctions.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
As always, let's do imports and initialize a logger and a new bundle. | import phoebe
from phoebe import u
import numpy as np
import matplotlib.pyplot as plt
phoebe.devel_on() # needed to use WD-style meshing, which isn't fully supported yet
logger = phoebe.logger()
b = phoebe.default_binary()
b['q'] = 0.7
b['requiv@secondary'] = 0.7 | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Adding Datasets and Compute Options | b.add_dataset('lc', times=np.linspace(0,1,101), dataset='lc01')
b.add_dataset('rv', times=np.linspace(0,1,101), dataset='rvdyn')
b.add_dataset('rv', times=np.linspace(0,1,101), dataset='rvnum') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's add compute options for phoebe using both the new (marching) method for creating meshes as well as the WD method which imitates the format of the mesh used within legacy. | b.add_compute(compute='phoebe2marching', irrad_method='none', mesh_method='marching')
b.add_compute(compute='phoebe2wd', irrad_method='none', mesh_method='wd', eclipse_method='graham') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Now we add compute options for the 'legacy' backend. | b.add_compute('legacy', compute='phoebe1', irrad_method='none') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
And set the two RV datasets to use the correct methods (for both compute options) | b.set_value_all('rv_method', dataset='rvdyn', value='dynamical')
b.set_value_all('rv_method', dataset='rvnum', value='flux-weighted') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's use the external atmospheres available for both phoebe1 and phoebe2 | b.set_value_all('atm', 'extern_planckint') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's make sure both 'phoebe1' and 'phoebe2wd' use the same value for gridsize | b.set_value_all('gridsize', 30) | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's also disable other special effect such as heating, gravity, and light-time effects. | b.set_value_all('ld_mode', 'manual')
b.set_value_all('ld_func', 'logarithmic')
b.set_value_all('ld_coeffs', [0.,0.])
b.set_value_all('rv_grav', False)
b.set_value_all('ltte', False) | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Finally, let's compute all of our models | b.run_compute(compute='phoebe2marching', model='phoebe2marchingmodel')
b.run_compute(compute='phoebe2wd', model='phoebe2wdmodel')
b.run_compute(compute='phoebe1', model='phoebe1model') | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Plotting
Light Curve | colors = {'phoebe2marchingmodel': 'g', 'phoebe2wdmodel': 'b', 'phoebe1model': 'r'}
afig, mplfig = b['lc01'].plot(c=colors, legend=True, show=True) | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Now let's plot the residuals between these two models | artist, = plt.plot(b.get_value('fluxes@lc01@phoebe2marchingmodel') - b.get_value('fluxes@lc01@phoebe1model'), 'g-')
artist, = plt.plot(b.get_value('fluxes@lc01@phoebe2wdmodel') - b.get_value('fluxes@lc01@phoebe1model'), 'b-')
artist = plt.axhline(0.0, linestyle='dashed', color='k')
ylim = plt.ylim(-0.003, 0.003) | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Dynamical RVs
Since the dynamical RVs don't depend on the mesh, there should be no difference between the 'phoebe2marching' and 'phoebe2wd' synthetic models. Here we'll just choose one to plot. | afig, mplfig = b.filter(dataset='rvdyn', model=['phoebe2wdmodel', 'phoebe1model']).plot(c=colors, legend=True, show=True) | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
And also plot the residuals of both the primary and secondary RVs (notice the scale on the y-axis) | artist, = plt.plot(b.get_value('rvs@rvdyn@primary@phoebe2wdmodel') - b.get_value('rvs@rvdyn@primary@phoebe1model'), color='b', ls=':')
artist, = plt.plot(b.get_value('rvs@rvdyn@secondary@phoebe2wdmodel') - b.get_value('rvs@rvdyn@secondary@phoebe1model'), color='b', ls='-.')
artist = plt.axhline(0.0, linestyle='dashed',... | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Numerical (flux-weighted) RVs | afig, mplfig = b.filter(dataset='rvnum').plot(c=colors, show=True)
artist, = plt.plot(b.get_value('rvs@rvnum@primary@phoebe2marchingmodel', ) - b.get_value('rvs@rvnum@primary@phoebe1model'), color='g', ls=':')
artist, = plt.plot(b.get_value('rvs@rvnum@secondary@phoebe2marchingmodel') - b.get_value('rvs@rvnum@secondary... | 2.3/examples/legacy.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
The above parameters are explained in the manuscript. | hinge_points = [(0.4, 0), (1, 0.7), (0.5, 0.4)]
metric = LpNormCurve(hinge_points[0][0], hinge_points[1][1], hinge_points[2][0], hinge_points[2][1])
et = EffTox(real_doses, efftox_priors, tox_cutoff, eff_cutoff, tox_certainty, eff_certainty, metric, trial_size,
first_dose) | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
The EffTox class is an object-oriented implementation of the trial design by Thall & Cook (Thall, P. F., & Cook, J. D. (2004). Dose-Finding Based on Efficacy-Toxicity Trade-Offs. Biometrics, 60(3), 684โ693.)
After observing outcomes 3NTE
Outcomes for a patient are represented by a three item tuple, where:
first item i... | outcomes1 = [(3, 0, 0), (3, 1, 0), (3, 0, 1)]
np.random.seed(123)
et.update(outcomes1, n=10**6) | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
In this instance, escalation to dose-level 4 is recommended. | et.tabulate() | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
We see that all doses are admissible in this instance, and that the utilities of dose-levels 3 and 4 are very similar. Dose Ambivalence is the likely result, i.e. after observing 3NTE in the Matchpoint trial, the design would have recommended dose 3 or dose 4. The reason is made plain by the plot below. | et.plot_posterior_utility_density(include_doses=[3,4], boot_samps=1000) | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
The posterior distributions of the utility of doses 3 and 4 largely occupy the same space so picking between them is difficult. In the Ambivalence.ipynb tutorial, we demonstrate a method for dealing with dose ambivalence.
The plot above is similar (but not identical) to Figure 2 in the publication. I used the R package... | outcomes2 = [
(2, 0, 0), (2, 0, 0), (2, 0, 0),
(3, 0, 1), (3, 0, 0), (3, 0, 0),
(4, 0, 1), (4, 1, 1), (4, 0, 1),
(3, 1, 0), (3, 0, 1), (3, 0, 1),
(4, 0, 0), (4, 0, 1), (4, 0, 1),
]
et.reset()
et.update(outcomes2, n=10**6)
et.tabulate() | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
Dose 4 is now clearly the preferable dose. | et.plot_posterior_utility_density(include_doses=[3,4], boot_samps=1000) | tutorials/matchpoint/Utility.ipynb | brockk/clintrials | gpl-3.0 |
Model.fit์ ๋์ ์ฌ์ฉ์ ์ ์ํ๊ธฐ
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org์์ ๋ณด๊ธฐ</a></td>
<td><a target="_blank" href="https://colab.research... | import tensorflow as tf
from tensorflow import keras | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
์ฒซ ๋ฒ์งธ ๊ฐ๋จํ ์์
๊ฐ๋จํ ์์ ๋ถํฐ ์์ํ๊ฒ ์ต๋๋ค.
keras.Model์ ํ์ ํด๋์คํํ๋ ์ ํด๋์ค๋ฅผ ๋ง๋ญ๋๋ค.
train_step(self, data) ๋ฉ์๋๋ฅผ ์ฌ์ ์ํฉ๋๋ค.
์์ค์ ํฌํจํ์ฌ ์ฌ์ ๋งคํ ๋ฉํธ๋ฆญ ์ด๋ฆ์ ํ์ฌ ๊ฐ์ผ๋ก ๋ฐํํฉ๋๋ค.
์
๋ ฅ ์ธ์ data๋ ํ๋ จ ๋ฐ์ดํฐ์ ๋ง๊ฒ ์ ๋ฌ๋ฉ๋๋ค.
fit(x, y, ...)๋ฅผ ํธ์ถํ์ฌ Numpy ๋ฐฐ์ด์ ์ ๋ฌํ๋ฉด data๋ ํํ (x, y)๊ฐ ๋ฉ๋๋ค.
tf.data.Dataset๋ฅผ ์ ๋ฌํ๋ ๊ฒฝ์ฐ, fit(dataset, ...)๋ฅผ ํธ์ถํ์ฌ data๊ฐ ๊ฐ ๋ฐฐ์น์์ dataset์ ์ํด ์ฐ์ถ๋ฉ๋๋ค.
train_s... | class CustomModel(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute the los... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ค์์ ์๋ํด๋ด
์๋ค. | import numpy as np
# Construct and compile an instance of CustomModel
inputs = keras.Input(shape=(32,))
outputs = keras.layers.Dense(1)(inputs)
model = CustomModel(inputs, outputs)
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
# Just use `fit` as usual
x = np.random.random((1000, 32))
y = np.random.ran... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ ๋ฎ์ ์์ค์ผ๋ก ๊ตฌ์ฑํ๊ธฐ
๋น์ฐํ compile()์์ ์์ค ํจ์์ ์ ๋ฌ์ ๊ฑด๋๋ฐ๊ณ , ๋์ <code>train_step</code>์์ <em>์๋์ผ๋ก</em> ๋ชจ๋ ์ํํ ์ ์์ต๋๋ค. ๋ฉํธ๋ฆญ๋ ๋ง์ฐฌ๊ฐ์ง์
๋๋ค.
๋ค์์ ์ตํฐ๋ง์ด์ ๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํด compile()๋ง ์ฌ์ฉํ๋ ํ์ ์์ค์ ์์
๋๋ค.
๋จผ์ ์์ค๊ณผ MAE ์ ์๋ฅผ ์ถ์ ํ๊ธฐ ์ํด Metric ์ธ์คํด์ค๋ฅผ ์์ฑํฉ๋๋ค.
(๋ฉํธ๋ฆญ์ ๋ํ update_state()๋ฅผ ํธ์ถํ์ฌ) ๋ฉํธ๋ฆญ์ ์ํ๋ฅผ ์
๋ฐ์ดํธํ๋ ์ฌ์ฉ์ ์ ์train_step()์ ๊ตฌํํ ๋ค์, ์ฟผ๋ฆฌํ์ฌ(result()๋ฅผ ํตํด) ํ์ฌ ํ๊ท ๊ฐ์ ๋ฐํํ์ฌ ... | loss_tracker = keras.metrics.Mean(name="loss")
mae_metric = keras.metrics.MeanAbsoluteError(name="mae")
class CustomModel(keras.Model):
def train_step(self, data):
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute our own... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
sample_weight ๋ฐ class_weight ์ง์ํ๊ธฐ
์ฒซ ๋ฒ์งธ ๊ธฐ๋ณธ ์์ ์์๋ ์ํ ๊ฐ์ค์น์ ๋ํด ์ธ๊ธํ์ง ์์์ต๋๋ค. fit() ์ธ์ sample_weight ๋ฐ class_weight๋ฅผ ์ง์ํ๋ ค๋ฉด ๋ค์์ ์ํํ๋ฉด ๋ฉ๋๋ค.
data ์ธ์์์ sample_weight ํจํค์ง๋ฅผ ํ๋๋ค.
compiled_loss ๋ฐ compiled_metrics์ ์ ๋ฌํฉ๋๋ค(์์ค ๋ฐ ๋ฉํธ๋ฆญ์ ์ํด compile()์ ์์กดํ์ง ์๋๋ค๋ฉด ์๋์ผ๋ก ์ ์ฉํ ์๋ ์์ต๋๋ค).
๋ค์์ ๊ทธ ๋ชฉ๋ก์
๋๋ค. | class CustomModel(keras.Model):
def train_step(self, data):
# Unpack the data. Its structure depends on your model and
# on what you pass to `fit()`.
if len(data) == 3:
x, y, sample_weight = data
else:
sample_weight = None
x, y = data
with... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
์์ ๋ง์ ํ๊ฐ ๋จ๊ณ ์ ๊ณตํ๊ธฐ
model.evaluate() ํธ์ถ์ ๋ํด ๊ฐ์ ์์
์ ์ํํ๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผ ํ ๊น์? ์ ํํ ๊ฐ์ ๋ฐฉ์์ผ๋ก test_step์ ์ฌ์ ์ํฉ๋๋ค. ๋ค์๊ณผ ๊ฐ์ต๋๋ค. | class CustomModel(keras.Model):
def test_step(self, data):
# Unpack the data
x, y = data
# Compute predictions
y_pred = self(x, training=False)
# Updates the metrics tracking the loss
self.compiled_loss(y, y_pred, regularization_losses=self.losses)
# Update th... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ง๋ฌด๋ฆฌ: ์๋-ํฌ-์๋ GAN ์์
๋ฐฉ๊ธ ๋ฐฐ์ด ๋ชจ๋ ๋ด์ฉ์ ํ์ฉํ๋ ์๋ ํฌ ์๋ ์์ ๋ฅผ ์ดํด๋ณด๊ฒ ์ต๋๋ค.
๋ค์์ ๊ณ ๋ คํฉ๋๋ค.
์์ฑ๊ธฐ ๋คํธ์ํฌ๋ 28x28x1 ์ด๋ฏธ์ง๋ฅผ ์์ฑํฉ๋๋ค.
discriminator ๋คํธ์ํฌ๋ 28x28x1 ์ด๋ฏธ์ง๋ฅผ ๋ ๊ฐ์ ํด๋์ค("false" ๋ฐ "real")๋ก ๋ถ๋ฅํ๊ธฐ ์ํ ๊ฒ์
๋๋ค.
๊ฐ๊ฐ ํ๋์ ์ตํฐ๋ง์ด์ ๋ฅผ ๊ฐ์ง๋๋ค.
discriminator๋ฅผ ํ๋ จํ๋ ์์ค ํจ์์
๋๋ค. | from tensorflow.keras import layers
# Create the discriminator
discriminator = keras.Sequential(
[
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(64, (3, 3), strides=(2, 2), padding="same"),
layers.LeakyReLU(alpha=0.2),
layers.Conv2D(128, (3, 3), strides=(2, 2), padding="same"),
... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
๋ค์์ ์์ ๋ง์ ์๋ช
์ ์ฌ์ฉํ๊ธฐ ์ํด compile()์ ์ฌ์ ์ํ๊ณ train_step 17์ค๋ก ์ ์ฒด GAN ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํํ๋ ํน์ฑ ์๋ฃํ GAN ํด๋์ค์
๋๋ค. | class GAN(keras.Model):
def __init__(self, discriminator, generator, latent_dim):
super(GAN, self).__init__()
self.discriminator = discriminator
self.generator = generator
self.latent_dim = latent_dim
def compile(self, d_optimizer, g_optimizer, loss_fn):
super(GAN, self)... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
ํ
์คํธํด ๋ด
์๋ค. | # Prepare the dataset. We use both the training & test MNIST digits.
batch_size = 64
(x_train, _), (x_test, _) = keras.datasets.mnist.load_data()
all_digits = np.concatenate([x_train, x_test])
all_digits = all_digits.astype("float32") / 255.0
all_digits = np.reshape(all_digits, (-1, 28, 28, 1))
dataset = tf.data.Datase... | site/ko/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
Calculate gradients
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/quantum/tutorials/gradients"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.... | !pip install tensorflow==2.7.0 | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Install TensorFlow Quantum: | !pip install tensorflow-quantum
# Update package resources to account for version changes.
import importlib, pkg_resources
importlib.reload(pkg_resources) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Now import TensorFlow and the module dependencies: | import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
1. Preliminary
Let's make the notion of gradient calculation for quantum circuits a little more concrete. Suppose you have a parameterized circuit like this one: | qubit = cirq.GridQubit(0, 0)
my_circuit = cirq.Circuit(cirq.Y(qubit)**sympy.Symbol('alpha'))
SVGCircuit(my_circuit) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Along with an observable: | pauli_x = cirq.X(qubit)
pauli_x | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Looking at this operator you know that $โจY(\alpha)| X | Y(\alpha)โฉ = \sin(\pi \alpha)$ | def my_expectation(op, alpha):
"""Compute โจY(alpha)| `op` | Y(alpha)โฉ"""
params = {'alpha': alpha}
sim = cirq.Simulator()
final_state_vector = sim.simulate(my_circuit, params).final_state_vector
return op.expectation_from_state_vector(final_state_vector, {qubit: 0}).real
my_alpha = 0.3
print("Expe... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
and if you define $f_{1}(\alpha) = โจY(\alpha)| X | Y(\alpha)โฉ$ then $f_{1}^{'}(\alpha) = \pi \cos(\pi \alpha)$. Let's check this: | def my_grad(obs, alpha, eps=0.01):
grad = 0
f_x = my_expectation(obs, alpha)
f_x_prime = my_expectation(obs, alpha + eps)
return ((f_x_prime - f_x) / eps).real
print('Finite difference:', my_grad(pauli_x, my_alpha))
print('Cosine formula: ', np.pi * np.cos(np.pi * my_alpha)) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
2. The need for a differentiator
With larger circuits, you won't always be so lucky to have a formula that precisely calculates the gradients of a given quantum circuit. In the event that a simple formula isn't enough to calculate the gradient, the tfq.differentiators.Differentiator class allows you to define algorithm... | expectation_calculation = tfq.layers.Expectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
expectation_calculation(my_circuit,
operators=pauli_x,
symbol_names=['alpha'],
symbol_values=[[my_alpha]]) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
However, if you switch to estimating expectation based on sampling (what would happen on a true device) the values can change a little bit. This means you now have an imperfect estimate: | sampled_expectation_calculation = tfq.layers.SampledExpectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
sampled_expectation_calculation(my_circuit,
operators=pauli_x,
repetitions=500,
s... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
This can quickly compound into a serious accuracy problem when it comes to gradients: | # Make input_points = [batch_size, 1] array.
input_points = np.linspace(0, 5, 200)[:, np.newaxis].astype(np.float32)
exact_outputs = expectation_calculation(my_circuit,
operators=pauli_x,
symbol_names=['alpha'],
... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Here you can see that although the finite difference formula is fast to compute the gradients themselves in the analytical case, when it came to the sampling based methods it was far too noisy. More careful techniques must be used to ensure a good gradient can be calculated. Next you will look at a much slower techniqu... | # A smarter differentiation scheme.
gradient_safe_sampled_expectation = tfq.layers.SampledExpectation(
differentiator=tfq.differentiators.ParameterShift())
with tf.GradientTape() as g:
g.watch(values_tensor)
imperfect_outputs = gradient_safe_sampled_expectation(
my_circuit,
operators=pauli_... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
From the above you can see that certain differentiators are best used for particular research scenarios. In general, the slower sample-based methods that are robust to device noise, etc., are great differentiators when testing or implementing algorithms in a more "real world" setting. Faster methods like finite differe... | pauli_z = cirq.Z(qubit)
pauli_z | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
If this observable is used with the same circuit as before, then you have $f_{2}(\alpha) = โจY(\alpha)| Z | Y(\alpha)โฉ = \cos(\pi \alpha)$ and $f_{2}^{'}(\alpha) = -\pi \sin(\pi \alpha)$. Perform a quick check: | test_value = 0.
print('Finite difference:', my_grad(pauli_z, test_value))
print('Sin formula: ', -np.pi * np.sin(np.pi * test_value)) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
It's a match (close enough).
Now if you define $g(\alpha) = f_{1}(\alpha) + f_{2}(\alpha)$ then $g'(\alpha) = f_{1}^{'}(\alpha) + f^{'}_{2}(\alpha)$. Defining more than one observable in TensorFlow Quantum to use along with a circuit is equivalent to adding on more terms to $g$.
This means that the gradient of a partic... | sum_of_outputs = tfq.layers.Expectation(
differentiator=tfq.differentiators.ForwardDifference(grid_spacing=0.01))
sum_of_outputs(my_circuit,
operators=[pauli_x, pauli_z],
symbol_names=['alpha'],
symbol_values=[[test_value]]) | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Here you see the first entry is the expectation w.r.t Pauli X, and the second is the expectation w.r.t Pauli Z. Now when you take the gradient: | test_value_tensor = tf.convert_to_tensor([[test_value]])
with tf.GradientTape() as g:
g.watch(test_value_tensor)
outputs = sum_of_outputs(my_circuit,
operators=[pauli_x, pauli_z],
symbol_names=['alpha'],
symbol_values=test_v... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
Here you have verified that the sum of the gradients for each observable is indeed the gradient of $\alpha$. This behavior is supported by all TensorFlow Quantum differentiators and plays a crucial role in the compatibility with the rest of TensorFlow.
4. Advanced usage
All differentiators that exist inside of TensorFl... | class MyDifferentiator(tfq.differentiators.Differentiator):
"""A Toy differentiator for <Y^alpha | X |Y^alpha>."""
def __init__(self):
pass
def get_gradient_circuits(self, programs, symbol_names, symbol_values):
"""Return circuits to compute gradients for given forward pass circuits.
... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
The Differentiator base class uses the components returned from get_gradient_circuits to calculate the derivative, as in the parameter shift formula you saw above. This new differentiator can now be used with existing tfq.layer objects: | custom_dif = MyDifferentiator()
custom_grad_expectation = tfq.layers.Expectation(differentiator=custom_dif)
# Now let's get the gradients with finite diff.
with tf.GradientTape() as g:
g.watch(values_tensor)
exact_outputs = expectation_calculation(my_circuit,
operato... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
This new differentiator can now be used to generate differentiable ops.
Key Point: A differentiator that has been previously attached to an op must be refreshed before attaching to a new op, because a differentiator may only be attached to one op at a time. | # Create a noisy sample based expectation op.
expectation_sampled = tfq.get_sampled_expectation_op(
cirq.DensityMatrixSimulator(noise=cirq.depolarize(0.01)))
# Make it differentiable with your differentiator:
# Remember to refresh the differentiator before attaching the new op
custom_dif.refresh()
differentiable_o... | site/en-snapshot/quantum/tutorials/gradients.ipynb | tensorflow/docs-l10n | apache-2.0 |
2. Check for errors
Don't assume that the data is always good. Create tests to make sure. | # We start with the assumption that the data is news worthy.
IsNewsWorthy = True
# Are there errors in the data?
if data["Richter"] > 100:
# A earthquake with magnitue of 100 seems unlikely, so we ignore it.
IsNewsWorthy = False
# We are only interested in earthquakes in Sweden.
if data["Country"] != "Sweden... | 3 News robot/Earthquake news robot.ipynb | peterdalle/mij | gpl-3.0 |
3. Create text
Basically, it's just a lot of if-statements.
How to make the code easier to read:
Don't nest if-statements inside each other too much. Use elif instead.
Use multiline strings, with """ around them.
Use .format on strings.
text = "My name is {0} and I am {1} years old"
text = text.format(Name, Age)
Whic... | # If the earthquake is deemed news worthy, then create a journalistic text.
text = ""
if IsNewsWorthy:
if (data["Richter"] > 6):
# Text for large quake (6+).
text = """BREAKING: Major earthquake in {0}
Today at {1} there was a severe earthquake in {2}, {3}, with a magnitude of {4} on th... | 3 News robot/Earthquake news robot.ipynb | peterdalle/mij | gpl-3.0 |
4. Save the results to a text file
Lets create a function that saves the text to a file. | # Function to save the text to a file.
def savefile(filename, text):
f = open(filename, mode="w") # Open file for writing (w = writing, a = append, r = reading)
f.write(text)
f.close()
# Only save as text file if there is some text.
if text != "":
savefile("newsrobot-earthquake.txt", text)
print(... | 3 News robot/Earthquake news robot.ipynb | peterdalle/mij | gpl-3.0 |
5. Present the results (read from text file)
Lets create a function that reads the text from the text file. | # Function that reads text from a file.
def readfile(filename):
f = open(filename, mode="r") # Open file for reading (w = writing, a = append, r = reading)
lines = f.read()
f.close()
return(lines)
# Read the file created earlier by the news robot.
text = readfile("newsrobot-earthquake.txt")
# Look a... | 3 News robot/Earthquake news robot.ipynb | peterdalle/mij | gpl-3.0 |
Preparation of data and model
To create a multi-label model in shogun, we'll first create an instance of MultilabelModel and initialize it by the features and labels. The labels should be MultilabelSOLables. It should be initialized by providing with the n_labels (number of examples) and n_classes (total number of clas... | def create_features(X, constant):
feats = sg.create_features(
np.c_[X, constant * np.ones(X.shape[0])].T)
return feats
def create_labels(Y, n_classes):
try:
n_samples = Y.shape[0]
except AttributeError:
n_samples = len(Y)
labels = sg.MultilabelSOLabels(... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Training and Evaluation of Structured Machines with/without Threshold
In Shogun, several solvers and online solvers have been implemented for SO-Learning. Let's try to train the model using an online solver StochasticSOSVM. | import time
sgd = sg.create_machine("StochasticSOSVM", model=model, labels=labels)
sgd_with_bias = sg.create_machine("StochasticSOSVM", model=model_with_bias, labels=labels)
start = time.process_time()
sgd.train()
print(">>> Time taken for SGD *without* threshold tuning = %f" % (time.process_time() - start))
start = ... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Accuracy
For measuring accuracy in multi-label classification, Jaccard Similarity Coefficients $\big(J(A, B) = \frac{|A \cap B|}{|A \cup B|}\big)$ is used :
$Accuracy = \frac{1}{p}\sum_{i=1}^{p}\frac{ |Y_i \cap h(x_i)|}{|Y_i \cup h(x_i)|}$
This is available in MultilabelAccuracy for MultilabelLabels and StructuredAccur... | def evaluate_machine(machine,
X_test,
Y_test,
n_classes,
bias):
if bias:
feats_test = create_features(X_test, 1)
else:
feats_test = create_features(X_test, 0)
test_labels = create_labels(Y_test, n_classe... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Plotting the Data along with the Boundary | import matplotlib.pyplot as plt
%matplotlib inline
def get_parameters(weights):
return -weights[0]/weights[1], -weights[2]/weights[1]
def scatter_plot(X, y):
zeros_class = np.where(y == 0)
ones_class = np.where(y == 1)
plt.scatter(X[zeros_class, 0], X[zeros_class, 1], c='b', label="Negative Class")
... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
As we can see from the above plot that sgd_with_bias can produce better classification boundary. The model without threshold tuning is crossing origin of space, while the one with threshold tuning is crossing $(1,1)$ (the constant we have added earlier). | from shogun import SparseMultilabel_obtain_from_generic
def plot_decision_plane(machine,
title,
X, y, bias):
plt.figure(figsize=(24, 8))
plt.suptitle(title)
plt.subplot(1, 2, 1)
x_min, x_max = np.min(X[:, 0]) - 0.5, np.max(X[:, 0]) + 0.5
y_min, y_max ... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
As we can see from the above plots of decision surface, the black region corresponds to the region of negative (label = $0$) class, where as the red region corresponds to the positive (label = $1$). But along with that there are some regions (although very small) of white surface and orange surface. The white surface c... | def load_data(file_name):
input_file = open(file_name)
lines = input_file.readlines()
n_samples = len(lines)
n_features = len(lines[0].split()) - 1
Y = []
X = []
for line in lines:
data = line.split()
Y.append(map(int, data[0].split(",")))
feats = []
for feat ... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Training and Evaluation of Structured Machines with/without Threshold | def test_multilabel_data(train_file,
test_file):
X_train, Y_train, n_samples, n_features, n_classes = load_data(train_file)
X_test, Y_test, n_samples, n_features, n_classes = load_data(test_file)
# create features and labels
multilabel_feats_0 = create_features(X_train, 0)
... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Comparision with scikit-learn's implementation | from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.metrics import jaccard_similarity_score
from sklearn.preprocessing import LabelBinarizer
def sklearn_implementation(train_file,
test_file):
label_binarizer = LabelBinarizer()
X_train, Y_train... | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Yeast Multi-Label Data [2] | print_table(os.path.join(SHOGUN_DATA_DIR, "multilabel/yeast_train.svm"),
os.path.join(SHOGUN_DATA_DIR, "multilabel/yeast_test.svm"),
"Yeast dataset") | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Scene Multi-Label Data [2] | print_table(os.path.join(SHOGUN_DATA_DIR, "multilabel/scene_train"),
os.path.join(SHOGUN_DATA_DIR, "multilabel/scene_test"),
"Scene dataset") | doc/ipython-notebooks/structure/multilabel_structured_prediction.ipynb | geektoni/shogun | bsd-3-clause |
Implement Preprocessing Function
Text to Word Ids
As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence fr... | def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):
"""
Convert source and target text to proper word ids
:param source_text: String that contains all the source text.
:param target_text: String that contains all the target text.
:param source_vocab_to_int: Dictionar... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Process Decoding Input
Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the beginning of each batch. | def process_decoding_input(target_data, target_vocab_to_int, batch_size):
"""
Preprocess target data for dencoding
:param target_data: Target Placehoder
:param target_vocab_to_int: Dictionary to go from the target words to an id
:param batch_size: Batch Size
:return: Preprocessed target data
... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Encoding
Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn(). | def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob):
"""
Create encoding layer
:param rnn_inputs: Inputs for the RNN
:param rnn_size: RNN Size
:param num_layers: Number of layers
:param keep_prob: Dropout keep probability
:return: RNN state
"""
# TODO: Implement Function
... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Decoding - Training
Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs. | def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope,
output_fn, keep_prob):
"""
Create a decoding layer for training
:param encoder_state: Encoder State
:param dec_cell: Decoder RNN Cell
:param dec_embed_input: Decoder embedded ... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Decoding - Inference
Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder(). | def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id,
maximum_length, vocab_size, decoding_scope, output_fn, keep_prob):
"""
Create a decoding layer for inference
:param encoder_state: Encoder state
:param dec_cell: Decoder R... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Build the Decoding Layer
Implement decoding_layer() to create a Decoder RNN layer.
Create RNN cell for decoding using rnn_size and num_layers.
Create the output fuction using lambda to transform it's input, logits, to class logits.
Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_le... | def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size,
num_layers, target_vocab_to_int, keep_prob):
"""
Create decoding layer
:param dec_embed_input: Decoder embedded input
:param dec_embeddings: Decoder embeddings
:param encoder_... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Build the Neural Network
Apply the functions you implemented above to:
Apply embedding to the input data for the encoder.
Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob).
Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function... | def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size,
enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int):
"""
Build the Sequence-to-Sequence part of the neural network
:param input_data: Inpu... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set num_layers to the number of layers.
Set encoding_embedding_size to the size of the embedding for the encoder.
Set decoding_embedding_siz... | # Number of Epochs
epochs = 5
# Batch Size
batch_size = 256
# RNN Size
rnn_size = 512
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 196
decoding_embedding_size = 196
# Learning Rate
learning_rate = 0.005
# Dropout Keep Probability
keep_probability = 0.9 | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Sentence to Sequence
To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.
Convert the sentence to lowercase
Convert words into ids using vocab_to_int
Convert words not in the vocabulary, to the <UNK> word id. | def sentence_to_seq(sentence, vocab_to_int):
"""
Convert a sentence to a sequence of ids
:param sentence: String
:param vocab_to_int: Dictionary to go from the words to an id
:return: List of word ids
"""
# TODO: Implement Function
int_sentence = [vocab_to_int.get(w.lower(), vocab_t... | language-translation/dlnd_language_translation.ipynb | rajuniit/udacity | mit |
Reading the data
We download the data from "stooq" and only store the High value.
Please note: this notebook is for showcasing tsfreshs feature extraction - not to predict stock market prices :-) | df = web.DataReader("AAPL", 'stooq')["High"]
df.head()
plt.figure(figsize=(15, 6))
df.plot(ax=plt.gca())
plt.show() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
We want to make the time dependency a bit clearer and add an identifier to each of the stock values (in this notebook we only have Google though). | df_melted = pd.DataFrame({"high": df.copy()})
df_melted["date"] = df_melted.index
df_melted["Symbols"] = "AAPL"
df_melted.head() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Create training data sample
Forecasting typically involves the following steps:
* take all data up to today
* do feature extraction (e.g. by running extract_features)
* run a prediction model (e.g. a regressor, see below)
* use the result as the forecast for tomorrow
In training however, we need multiple examples to tr... | df_rolled = roll_time_series(df_melted, column_id="Symbols", column_sort="date",
max_timeshift=20, min_timeshift=5)
df_rolled.head() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
The resulting dataframe now consists of these "windows" stamped out of the original dataframe.
For example all data with the id = (AAPL, 2020-07-14 00:00:00) comes from the original data of stock AAPL including the last 20 days until 2020-07-14: | df_rolled[df_rolled["id"] == ("AAPL", pd.to_datetime("2020-07-14"))]
df_melted[(df_melted["date"] <= pd.to_datetime("2020-07-14")) &
(df_melted["date"] >= pd.to_datetime("2020-06-15")) &
(df_melted["Symbols"] == "AAPL")] | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
If you now group by the new id column, each of the groups will be a certain stock symbol until and including the data until a certain day (and including the last 20 days in the past).
Whereas we started with 1259 data samples: | len(df_melted) | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
we now have 1254 unique windows (identified by stock symbol and ending date): | df_rolled["id"].nunique() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
We "lost" 5 windows, as we required to have a minimum history of more than 5 days. | df_rolled.groupby("id").size().agg([np.min, np.max]) | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
The process is also shown in this image (please note that the window size is smaller for better visibility):
<img src="./stocks.png"/>
Extract Features
The rolled (windowed) data sample is now in the correct format to use it for tsfreshs feature extraction.
As normal, features will be extracted using all data for a giv... | X = extract_features(df_rolled.drop("Symbols", axis=1),
column_id="id", column_sort="date", column_value="high",
impute_function=impute, show_warnings=False)
X.head() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
We make the data a bit easier to work with by removing the tuple-index | X = X.set_index(X.index.map(lambda x: x[1]), drop=True)
X.index.name = "last_date"
X.head() | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Our (AAPL, 2020-07-14 00:00:00) is also in the data again: | X.loc['2020-07-14'] | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Just to repeat: the features in this row were only calculated using the time series values of AAPL up to and including 2015-07-14 and the last 20 days.
Prediction
We can now use the extracted features to train a regressor.
But what will be our targets?
The target for the row 2020-07-13 is the value on the next timestep... | y = df_melted.set_index("date").sort_index().high.shift(-1) | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Quick consistency test: | y["2020-07-13"], df["2020-07-14"].iloc[0] | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
However, we need to be a bit careful here: X is missing the first 5 dates (as our minimum window size was 5) and y is missing the last date (as there is nothing to predict on today).
So lets make sure we have a consistent view on the data. | y = y[y.index.isin(X.index)]
X = X[X.index.isin(y.index)] | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
We can now train normal AdaBoostRegressors to predict the next time step .
Let's split the data into a training and testing sample (but make sure to keep temporal consistency).
We take everything until 2019 as train data an the rest as test: | X[:"2018"]
X_train = X[:"2018"]
X_test = X["2019":]
y_train = y[:"2018"]
y_test = y["2019":] | notebooks/examples/05 Timeseries Forecasting.ipynb | blue-yonder/tsfresh | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.