Muennighoff/xP3x-sample huggingface dataset:
inputs: "<font color=blue>
Cost
</font>
<font color=blue>
The cost of migration between an origin and destination is the weighted average of the distance, migration history, shared language and political barriers between the two countries. 
\begin{equation}
C = { \alpha_1 \frac{D_{O\leftrightarrow D}} {D_{Max}} + \alpha_2 MH_{O\rightarrow D}  + \alpha_3 L_{O\leftrightarrow D} + \alpha_4 PB}
\end{equation}
</font>"
Please write code following the instructions in jupyter notebook style.

targets: 
# Cost
alpha1=.35
alpha2=.35
alpha3=.15
alpha4=.15
c = (alpha1*world.matrices["distance"] +
     alpha2*world.matrices["Migration History"] +
     alpha3*world.matrices["language"] +
     alpha4*world.matrices["Political Barriers"])
world.add_matrix("cost", c * world.data['beta'])

map_plot(world.matrices["cost"]["SYR"], title="Costs (SYR)")

map_plot(world.matrices["cost"]["FRA"], title="Costs (FRA)")

world.update_neighborhoods((1 - world.data["Unemployment"]) * world.data["rts"], "wages")

map_plot(world.data["wages"], title="Wages")

#beta = world.data.rts.mean()
#beta = RTS_list.median()

world.add_matrix("migration", (pd.DataFrame(
    np.array(
        [[x] * len(world.data) for x in world.data["wages"].values]
    ) - np.array(
        [list(world.data["wages"].values)] * len(world.data)
    ),
    world.data.index,
    world.data.index
    )  - world.matrices["cost"]).clip(lower=0))
world.matrices["migration"] = world.matrices["migration"] / (world.matrices["migration"].sum() + 1)
world.matrices["migration"] = world.matrices["migration"] / world.matrices["migration"].sum(axis=1).max()

# TODO: Why does this require being transposed?
world.matrices["migration"] = (0.15 * world.matrices["migration"].transpose() * world.data["Population"]).transpose()

world.matrices["migration"]

map_plot(
   world.matrices["migration"].sum(axis=1)+1,
   title="Immigration Estimations (x={})".format(skill.value),
   normc=matplotlib.colors.LogNorm
)

map_plot(
   world.matrices["migration"].sum(),
   title="Estimated Number of Emigrants (x={})".format(skill.value),
   normc=matplotlib.colors.Normalize
)

map_plot(
   world.matrices["migration"].sum(axis=1) - world.matrices["migration"].sum(),
   title="Net Migration (x={})".format(skill.value),
   normc=gos.visualization.MidPointNorm
)
inputs: # iterate through all train and validation batches

Given the above code, generate some markdown instructions for it.

targets: 
Exercise: Use the for loop to iterate through all train and validation batches.
inputs: 2.2 Leave-one-out Cross-Validation Example

targets: from sympy import Matrix, Rational, Eq, sqrt
var('x1 x2 x3 rho')
inputs: 2. Grid Search for Optimal Parameter Values

targets: df = pd.DataFrame(columns=['beta', 'sigma_z', 'score'])
outDfRow = -1
saveResults = False
noiseLevels = np.linspace(0, 100, 21)
noiseLevels = [5]
sampleRates = [1, 5, 10, 20, 30]
sampleRates = [5]
betas = np.linspace(1,10,19)
sigmaZs = np.linspace(1,10,19)

for i, rteCoords in enumerate(routeList):
    print("Processig route {0} of {1}".format(i, len(routeList)))
    shape, routeUrl = val.get_route_shape(rteCoords)
    
    for beta in betas:
        
        for sigmaZ in sigmaZs:
            print("Computing score for sigma_z: {0}, beta: {1}".format(
                        sigmaZ, beta))
            edges, shapeCoords, traceAttrUrl = val.get_trace_attrs(
                shape, beta=beta, sigmaZ=sigmaZ)
            edges = val.get_coords_per_second(shapeCoords, edges, '2768')

            for noise in noiseLevels:
                noise = round(noise,3)

                for sampleRate in sampleRates:
                    outDfRow += 1
                    df.loc[outDfRow, ['beta','sigma_z']] = [beta, sigmaZ]
                    dfEdges = val.format_edge_df(edges)
                    dfEdges, jsonDict, geojson = val.synthesize_gps(
                        dfEdges, shapeCoords, '2768', noise=noise, sampleRate=sampleRate, 
                        beta=beta, sigmaZ=sigmaZ)
                    segments, reportUrl = val.get_reporter_segments(jsonDict)
                    matches, score = val.get_matches(segments, dfEdges)
                    df.loc[outDfRow, 'score'] = score

                    if saveResults:
                        matches.to_csv(
                            '../data/matches_{0}_to_{1}_w_{2}_m_noise_at_{3}_Hz.csv'.format(
                                stName, endName, str(noise), str(Hz)), index=False)
                        with open('../data/trace_{0}_to_{1}_w_{2}_m_noise_at_{3}_Hz.geojson'.format(
                            stName, endName, str(noise), str(Hz)), 'w+') as fp:
                            json.dump(geojson, fp)
inputs: And now applying this on some real data
These exercises are based on the PyCon tutorial of Brandon Rhodes (so all credit to him!) and the datasets he prepared for that. You can download these data from here: titles.csv and cast.csv and put them in the /data folder.

targets: cast = pd.read_csv('data/cast.csv')
cast.head()

titles = pd.read_csv('data/titles.csv')
titles.head()
inputs: # convert to magnitudes
import numpy as np

# We'll use Vega spectrum as example
vega = Vega()
f = lib['HST_WFC3_F110W']
# compute the integrated flux through the filter f
# note that it work on many spectra at once
fluxes = f.get_flux(vega.wavelength, vega.flux, axis=-1)
# convert to vega magnitudes
mags = -2.5 * np.log10(fluxes.magnitude) - f.Vega_zero_mag
print("Vega magnitude of Vega in {0:s} is : {1:f} mag".format(f.name, mags))
mags = -2.5 * np.log10(fluxes.magnitude) - f.AB_zero_mag
print("AB magnitude of Vega in {0:s} is : {1:f} mag".format(f.name, mags))
mags = -2.5 * np.log10(fluxes.magnitude) - f.ST_zero_mag
print("ST magnitude of Vega in {0:s} is : {1:f} mag".format(f.name, mags))

f.AB_zero_Jy, f.Vega_zero_Jy, f.ST_zero_Jy
Given the above code, generate some markdown instructions for it.

targets: 
Vega
Suppose one has a calibrated spectrum and wants to compute the vega magnitude throug the HST WFC3 F110W passband,
inputs: I am working on the file ".ipynb_checkpoints/barriere-capillaire-checkpoint.ipynb".
The first task is:
Capacité et longueur de transfert
Can you write Python code for it?

targets: 
pente = 0.25

Qmax = pente * quad(k_vanGenuchten, profileCBL.psiMax, profileMRL.psiMax, args=(mrlaVG, mrlnVG, mrlmVG, mrlksat, mrllVG))[0]
L = Qmax / unit_flow

print ('Le débit de transfert maximal dans la barrière capillaire est de', Qmax, 'm²/s.')
print ('La longueur de transfert maximale dans la barrière capillaire est de', L, 'm.')
inputs: Although statmorph is designed to process all the sources labeled by the segmentation map, in this example we only focus on the main (largest) source found in the image.

targets: # Keep only the largest segment
label = np.argmax(segm.areas) + 1
segmap = segm.data == label
plt.imshow(segmap, origin='lower', cmap='gray')
inputs: # Same analysis with scipy.stats fxns
observed_nomargin = pd.crosstab(bumpus.survived, bumpus.sex, margins=False)
Chi2, Pval, Dof, Expected = stats.chi2_contingency(observed_nomargin.values, 
                                                   correction=False)

Chi2, Pval, Dof
Given the above code, generate some markdown instructions for it.

targets: 
$X^2$-square test of independence using scipy.stats
inputs: As above, these two variables are defined positional to correspond to both
the distribution and polynomial.
From the simplified equation above, it can be observed that the fraction of
expected values doesn't depend on neither $c$ nor $t$, and can therefore be
pre-computed.
For the denominator $\mathbb E[\beta\Phi_n\Phi_k]$, since there are both $\Phi_k$
and $\Phi_n$ terms, the full expression can be defined as a two-dimensional
tensor:

targets: phi_phi = chaospy.outer(
    polynomial_expansion, polynomial_expansion)
[polynomial_expansion.shape, phi_phi.shape]
inputs: "Basic slicing"
Please write code following the instructions in jupyter notebook style.

targets: 
one_dim_array[0]

two_dim_array[-1, -1]
inputs: # Create AgeGroups for further Analysis
'''bins = [0, 25, 50, 75, 100, 120]
group_names = ['0-25', '25-50', '50-75', '75-100', '100-120']
clean_appointment_data['age-group'] = pd.cut(clean_appointment_data['Fixed_Age'], bins, labels=group_names)
clean_appointment_data.head()'''
clean_appointment_data['Age_rounded'] = np.round(clean_appointment_data['Fixed_Age'], -1)


categories_dict = {0: '0-5',
                   10: '5-15',
                   20: '15-25',
                    30 : '25-35',
                    40 : '35-45',
                    50 : '45-55',
                   60: '55-65',
                    70 : '65-75',
                    80 : '75-85',
                  90: '85-95',
                  100: '95-105',
                  120: '105-115'}

clean_appointment_data['age_group'] = clean_appointment_data['Age_rounded'].map(categories_dict)

clean_appointment_data['age_group']
Given the above code, generate some markdown instructions for it.

targets: 
The Fixed_Age column is created in order to replace the negative value available in the Age column. The newly created Fixed_Age column will help in the proper calculation in the further questions and the results will be perfect and clear too. The negative value (-1) is changed in to a positive value (1) by using the .abd() function.
inputs: "Basic List Methods
If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
Let's go ahead and explore some more special methods for lists:"
Please write code following the instructions in jupyter notebook style.

targets: 
# Create a new list
l = [1,2,3]
inputs: "Classes
The simplest class"
Please write code following the instructions in jupyter notebook style.

targets: 
# define the class
class myclass():
    pass

# create an instance
foo_instance = myclass()
print(type(foo_instance))
inputs: "Common formatting tricks
There are hundreds of formatting options available in Matplotlib, many of which you will end up using occasionally. There are a few options, however, that you will use very frequently. Here's a short list...

Changing axis limits
Changing line colors
Changing lines to dashed (for black and white figures)
Adding markers to lines
Make tick labels point outward instead of inward
Get rid of the box surrounding the plot
Adding subplot letters, like (a) and (b)

...and some examples for how to accomplish all of these things."
Please write code following the instructions in jupyter notebook style.

targets: 
# Make some data to plot
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)

# First, create an empty figure with 1 subplot
fig, ax1 = plt.subplots(1, 1)

# Add title and labels
ax1.set_title('My Plot',fontsize=20)
ax1.set_xlabel('x',fontsize=20)
ax1.set_ylabel('y',fontsize=20)

# Change axis limits
ax1.set_xlim([0,2])
ax1.set_ylim([-1, 2])

# Add the lines, changing their color, style, and marker
ax1.plot(x, y1, 'k--o', label='sin') # Black line, dashed, with 'o' markers
ax1.plot(x, y2, 'r-^', label='cos') # Red line, solid, with triangle-up markers

# Adjust tick marks and get rid of 'box'
ax1.tick_params(direction='out', top=False, right=False) # Turn ticks out
ax1.spines['top'].set_visible(False) # Get rid of top axis line
ax1.spines['right'].set_visible(False) #  Get rid of bottom axis line

# Add subplot letter
ax1.annotate('(a)', (0.01, 0.96), size=12, xycoords='figure fraction')

# Add legend
ax1.legend()

# Finally, save the figure as a png file
fig.savefig('myfig-formatted.png')
inputs: 4. Looking at the data
Summaries

targets: prms.Batch.summary_plot_height = 800
prms.Batch.summary_plot_width = 900

# Plot the charge capacity and the C.E. (and resistance) vs. cycle number (standard plot)
b.plot_summaries()

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, ColumnarDataSource

data = ColumnDataSource(
    pd.DataFrame(
        {
            "header_en": [1, 2, 3, 4],
            "annen": [22.1, 22.2, 22.3, 22.4],
            "siste": [1000, 2000, 3000, 4000],
        }
    )
)


p = figure(
    title="Top Title with Toolbar",
    toolbar_location="above",
    plot_width=600,
    plot_height=300,
)
p.circle(x="header_en", y="annen", source=data)

show(p)

b.summary_headers

# Show the journal pages
# b.experiment.journal.pages.head()

# Show the most important part of the journal pages
b.view

# b.experiment.status()

b.summaries.head()

summaries = b.summaries.copy()

from cellpy.parameters.internal_settings import (
    get_headers_summary,
    get_headers_normal,
    get_headers_step_table,
)
inputs: I am working on the file "03-Pandas_and_DTM/00-PandasAndTextAnalysis.ipynb".
The first task is:
<a id='apply'></a>
3. The apply function
We can also apply a function to each row. To get a word count of a text file we would take the length of the split string like this:
len(text_split)
If we want to do this on every row in our dataframe, we can use the apply() function.
Can you write Python code for it?

targets: 
df['word_count'] = df['text_split'].apply(len)
df
inputs: I am working on the file "BAMM.101x/Networks_new.ipynb".
The first task is:
<h4>Largest connected component subgraph</h4>
Can you write Python code for it?

targets: 
largest_size=0
largest_graph = None
for g in nx.connected_component_subgraphs(friend_graph):
    if len(g) > largest_size:
        largest_size = len(g)
        largest_graph = g
nx.draw(largest_graph)
inputs: # Why are flights late? Lets look at some delayed flights and the delay causes
late_flights = spark.sql("""
SELECT
  ArrDelayMinutes,
  WeatherDelay,
  CarrierDelay,
  NASDelay,
  SecurityDelay,
  LateAircraftDelay
FROM
  on_time_performance
WHERE
  WeatherDelay IS NOT NULL
  OR
  CarrierDelay IS NOT NULL
  OR
  NASDelay IS NOT NULL
  OR
  SecurityDelay IS NOT NULL
  OR
  LateAircraftDelay IS NOT NULL
ORDER BY
  FlightDate
""")
late_flights.sample(False, 0.01).show()
Given the above code, generate some markdown instructions for it.

targets: 
Inspecting Late Flights
inputs: By default, Pool creates a fixed number of worker processes and passes jobs to them until there are no more jobs. Setting the maxtasksperchild parameter tells the pool to restart a worker process after it has finished a few tasks, preventing long-running workers from consuming ever more system resources.

targets: import multiprocessing


def do_calculation(data):
    return data * 2


def start_process():
    print('Starting', multiprocessing.current_process().name)


if __name__ == '__main__':
    inputs = list(range(10))
    print('Input   :', inputs)

    builtin_outputs = map(do_calculation, inputs)
    print('Built-in:', builtin_outputs)

    pool_size = multiprocessing.cpu_count() * 2
    pool = multiprocessing.Pool(
        processes=pool_size,
        initializer=start_process,
        maxtasksperchild=2,
    )
    pool_outputs = pool.map(do_calculation, inputs)
    pool.close()  # no more tasks
    pool.join()  # wrap up current tasks

    print('Pool    :', pool_outputs)
inputs: I am working on the file "CrashCourse_Lecture1.ipynb".
The first task is:
Great! 95% accuracy!
Let's try it with random labels:
Can you write Python code for it?

targets: 
wilt_svm = sklearn.svm.SVC(C=1)
wilt_svm.fit(wilt_train_features, np.random.permutation(wilt_train_labels))
print "Score: %f" % wilt_svm.score(wilt_test_features, np.random.permutation(wilt_test_labels))
inputs: # Calculate the mean wind speed (column 'wspd'):


# Calculate the median of the wind direction (column 'wdir'):


# Obtain the maximum difference between two time steps
# (column 'wspd_std')

Given the above code, generate some markdown instructions for it.

targets: 
Now, we are skimming this. Later we will see it in a more detailed way:
Let's do some simple examples:
inputs: "Apply Pre-trained Inception V1 model to Images.
We have to convert each image to the size expected by the model checkpoint.
There is no easy way to determine this size from the checkpoint itself.
So we use a preprocessor to enforce this."
Please write code following the instructions in jupyter notebook style.

targets: 
import numpy as np
import os
import tensorflow as tf

try:
    import urllib2 as urllib
except ImportError:
    import urllib.request as urllib

from datasets import imagenet
from nets import inception
from preprocessing import inception_preprocessing

from tensorflow.contrib import slim

image_size = inception.inception_v1.default_image_size

with tf.Graph().as_default():
    url = 'https://upload.wikimedia.org/wikipedia/commons/7/70/EnglishCockerSpaniel_simon.jpg'
    image_string = urllib.urlopen(url).read()
    image = tf.image.decode_jpeg(image_string, channels=3)
    processed_image = inception_preprocessing.preprocess_image(image, image_size, image_size, is_training=False)
    processed_images  = tf.expand_dims(processed_image, 0)
    
    # Create the model, use the default arg scope to configure the batch norm parameters.
    with slim.arg_scope(inception.inception_v1_arg_scope()):
        logits, _ = inception.inception_v1(processed_images, num_classes=1001, is_training=False)
    probabilities = tf.nn.softmax(logits)
    
    init_fn = slim.assign_from_checkpoint_fn(
        os.path.join(checkpoints_dir, 'inception_v1.ckpt'),
        slim.get_model_variables('InceptionV1'))
    
    with tf.Session() as sess:
        init_fn(sess)
        np_image, probabilities = sess.run([image, probabilities])
        probabilities = probabilities[0, 0:]
        sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x:x[1])]
        
    plt.figure()
    plt.imshow(np_image.astype(np.uint8))
    plt.axis('off')
    plt.show()

    names = imagenet.create_readable_names_for_imagenet_labels()
    for i in range(5):
        index = sorted_inds[i]
        print('Probability %0.2f%% => [%s]' % (probabilities[index] * 100, names[index]))
inputs: "Amennyiben az oszlop neve nem tartalmaz szóközöket, attribútumként is elérjük."
Please write code following the instructions in jupyter notebook style.

targets: 
grades.teacher
inputs: # compute dists for each combination (1->5)
...

# plot results
# remember to label your axes!
...
Given the above code, generate some markdown instructions for it.

targets: 
Now, compute, plot, and label the luminosity distance $d_L(z; \Omega_{m,0}, \Omega_\Lambda)$ for different combinations of $(\Omega_{m,0}, \Omega_\Lambda)$:
1. $(0.3, 0.0)$, 
2. $(0.3, 0.4)$, 
3. $(0.3, 0.7)$, 
4. $(0.5, 0.7)$,
5. $(0.8, 0.8)$.
inputs: As with the BDF, we can use the long form and the short form.  However, the long form for the OP2 doesn't really add anything.  So, let's just use the short form.
Besides massive speed improvements in the OP2 relative to v0.7, this version adds pandas dataframe support.

targets: #op2_filename = r'D:\work\pynastran_0.8.0\models\iSat\ISat_Launch_Sm_Rgd.op2'
#op2_filename = r'D:\work\pynastran_0.8.0\models\iSat\ISat_Launch_Sm_4pt.op2'
op2_filename = os.path.abspath(os.path.join(pkg_path, '..', 'models', 'iSat', 'ISat_Launch_Sm_4pt.op2'))
assert os.path.exists(op2_filename), print_bad_path(op2_filename)

# define the input file with a file path
op2 = read_op2(op2_filename, build_dataframe=True, debug=False)
inputs: 1. Use the "trends.csv" file and csv2rec() to import the data and reproduce this plot:
<img align='left' src="trends.png">

targets: # we can import the CSV data as a numpy rec array
from matplotlib.pylab import csv2rec
trends = csv2rec('trends.csv')

plot(trends.week_start, trends.spring_break, label='spring break')
plot(trends.week_start, trends.textbooks, label='texbooks')
plot(trends.week_start, trends.norad, label='norad')
plot(trends.week_start, trends.skiing, label='skiing')
legend()
inputs: Build VectorAssembler stage

targets: feature_columns = ['onehot_' + c for c in categorical_columns]
vectorassembler_stage = VectorAssembler(inputCols=feature_columns, outputCol='features')
inputs: Create the CausalModels

targets: models = []
for data in datasets:
    model = CausalModel(
                data = data['df'],
                treatment = data['treatment_name'],
                outcome = data['outcome_name'],
                graph = data['gml_graph']
            )
    models.append(model)
inputs: I am working on the file "PageviewAnalysis.ipynb".
The first task is:
Create a column 'date' that combines year, month, and day. Use it as the x axis later when plotting
Can you write Python code for it?

targets: 
df['day'] = '01'
df['date']= df.apply(lambda x:datetime.strptime("{0} {1} {2}".format(x['year'],x['month'], x['day']), "%Y %m %d"),axis=1)
inputs: "Alternative: ResNet

basic ideas
depth does matter
8x deeper than VGG
possible by using shortcuts and skipping final fc layer
prevents vanishing gradient problem
https://keras.io/applications/#resnet50
https://medium.com/towards-data-science/neural-network-architectures-156e5bad51ba

http://arxiv.org/abs/1512.03385"
Please write code following the instructions in jupyter notebook style.

targets: 
from tensorflow.keras.applications.resnet50 import ResNet50

# https://keras.io/applications/#mobilenet
# https://arxiv.org/pdf/1704.04861.pdf
from tensorflow.keras.applications.mobilenet import MobileNet

# model = ResNet50(classes=10, weights=None, input_shape=(32, 32, 1))
model = MobileNet(classes=10, weights=None, input_shape=(32, 32, 1))

model.summary()

BATCH_SIZE=10
EPOCHS = 20

model.compile(loss='sparse_categorical_crossentropy',
             optimizer='adam',
             metrics=['accuracy'])

%time history = model.fit(x_train_224, y_train_samples, epochs=EPOCHS, batch_size=BATCH_SIZE, validation_split=0.2, verbose=1)

import pandas as pd
from matplotlib import pyplot as plt
%matplotlib inline

def plot_history(history, samples=10, init_phase_samples=None):
    epochs = history.params['epochs']
    
    acc = history.history['acc']
    val_acc = history.history['val_acc']

    every_sample =  int(epochs / samples)
    acc = pd.DataFrame(acc).iloc[::every_sample, :]
    val_acc = pd.DataFrame(val_acc).iloc[::every_sample, :]

    fig, ax = plt.subplots(figsize=(20,5))

    ax.plot(acc, 'bo', label='Training acc')
    ax.plot(val_acc, 'b', label='Validation acc')
    ax.set_title('Training and validation accuracy')
    ax.legend()

plot_history(history)
inputs: AoC2017.4 == [F +] step_zero

targets: define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')

J('''

[[5 1 9 5]
 [7 5 4 3]
 [2 4 6 8]] AoC2017.4

''')
inputs: !pip install pyrpl #if you look at this file in ipython notebook, just execute this cell to install pyrplockbox
Given the above code, generate some markdown instructions for it.

targets: 
Should the directory not be the one of your local github installation, you might have an older version of pyrpl installed. Just delete any such directories other than your principal github clone and everything should work. 
Option 2: from GitHub using setuptools (beta version)
Download the code manually from https://github.com/lneuhaus/pyrpl/archive/master.zip and unzip it or get it directly from git by typing 
$\texttt{git clone https://github.com/lneuhaus/pyrpl.git YOUR_DESTINATIONFOLDER}$
In a command line shell, navigate into your new local pyrplockbox directory and execute
$\texttt{python setup.py install}$
This copies the files into the side-package directory of python. The setup should make sure that you have the python libraries paramiko (http://www.paramiko.org/installing.html) and scp (https://pypi.python.org/pypi/scp) installed. If this is not the case you will get a corresponding error message in a later step of this tutorial. 
Option 1: with pip (coming soon)
If you have pip correctly installed, executing the following line in a command line should install pyrplockbox and all dependencies: 
$\texttt{pip install pyrpl}$
inputs: #wyrównanie do nawiasu otwierającego
foo = moja_dluga_funkcja(zmienna_jeden, zmienna_dwa
                         zmienna_trzy, zmienna_cztery)

# zwiększone wcięcia aby rozróżnić funkcję od ciała funkcji
def moja_dluga_funkcja(
        zmienna_jeden, zmienna_dwa, zmienna_trzy,
        zmienna_cztery):
    print(zmienna_jeden)

foo = moja_dluga_funkcja(
    zmienna_jeden, zmienna_dwa,
    zmienna_trzy, zmienna_cztery)

# Może być w tym przypadku inna ilość wcięć niż 4
foo = moja_dluga_funkcja(
  zmienna_jeden, zmienna_dwa,
  zmienna_trzy, zmienna_cztery)

moja_lista = [
    1, 2, 3,
    4, 5, 6,
    ]

wynik = funkcja_przyjmujaca_argumenty(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

# dozwolone też wyrównanie z początkiem lini otwierającej wielowierszową konstrukcję

moja_lista = [
    1, 2, 3,
    4, 5, 6,
]

wynik = funkcja_przyjmujaca_argumenty(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

przychod = (zarobki_brutto
            + zwrot_z_podatku
            + (dywidendy - podatek_od_dywidend)
            - ubezpieczenie_samochodu
            - kredyt_studencki)

#Dobrze:
import os
import sys

#Źle:  
import sys, os
    
#Dobrze:
from subprocess import Popen, PIPE 

"""Przykładowy moduł.

Coś tutaj się dzieje.
"""

from __future__ import jakiś_moduł

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Andrzej Krawczyk'

import os
import sys

#Dobrze:
def average(count, length=5):
    return foo(c=count, l=length)

#Źle:
def complex(count, length = 5):
    return foo(c = count, l = length)
Given the above code, generate some markdown instructions for it.

targets: 
Uruchomiene Aplikacji


Z poziomu konsoli
    > python program.py


Shebang (Unix)
    > #!/usr/bin/env python3


Prawa wykonywania
    > chmod u+x program.py
    >


Interaktywny Interpreter
    > ipython


Składnia

instrukcje nie są zakończone średnikiem
bloki kodu są definiowane przez wcięcia
wiele angielskich słów
komentarz #
zminimalizowany zbiór instrukcji

PEP8

wcięcia 4 spacje
Długość lini 79
Importowanie per linia, na poczatku modułu, kolejność priorytetowa
(2 + 3), 4
inputs: "1.4.2.3 Conclusion
Over the years the repartition has changed. As we are doing predictions with user data from July 2014, this changes may require us to focus on the most recent data during training. It is most likely to have similar pattern than test data.
1.4.3 Account Creation Analysis
We want to evaluate the quantity of data we would have left if we only consider the N-last months of the data.
We have seen that the "early users" are very different of the actual ones. Let's see how much of data we can delete of the dataset."
Please write code following the instructions in jupyter notebook style.

targets: 
tmp_df = df_output_by_year_and_month[['country_destination','year_month_account_created']].sort_values(
    by="year_month_account_created"
)

tmp_df = tmp_df.groupby(["year_month_account_created"]).agg("count")
tmp_df.head(n=4)

# Plot Data
x_data = [str(x) for x in tmp_df["country_destination"].index.values]
y_data = tmp_df["country_destination"].values

p = bk_plt.figure(plot_width=980, plot_height=400, y_range=[0, y_data.max()+1000], x_range=x_data)

p.line(x_data, y_data, line_width=2)
p.circle(x_data, y_data, fill_color="white", size=8)


# Draw a line when X% of the users of the dataset have sign-up
split_1 = 20 # 80% left
split_2 = 30 # 70% left
split_3 = 50 # 50% left
split_4 = 70 # 30% left

thrs_value_1 = 213450 * split_1 / 100
thrs_value_2 = 213450 * split_2 / 100
thrs_value_3 = 213450 * split_3 / 100
thrs_value_4 = 213450 * split_4 / 100

index_1 = 0
index_2 = 0
index_3 = 0
index_4 = 0

tmp_sum = 0
for val in y_data:
    tmp_sum += val
    
    if tmp_sum <= thrs_value_1:
        index_1 += 1     
        index_2 += 1
        index_3 += 1
        index_4 += 1
    elif tmp_sum <= thrs_value_2:    
        index_2 += 1
        index_3 += 1
        index_4 += 1
    elif tmp_sum <= thrs_value_3:
        index_3 += 1
        index_4 += 1
    elif tmp_sum <= thrs_value_4:
        index_4 += 1
    else:
        break
           
        
vline_1 = bk_md.Span(location=index_1, dimension='height', line_color='blue', line_width=3) # 80% Data Left
vline_2 = bk_md.Span(location=index_2, dimension='height', line_color='green', line_width=3) # 70% Data Left
vline_3 = bk_md.Span(location=index_3, dimension='height', line_color='orange', line_width=3) # 50% Data Left
vline_4 = bk_md.Span(location=index_4, dimension='height', line_color='red', line_width=3) # 30% Data Left

p.renderers.extend([vline_1, vline_2, vline_3, vline_4])

# We set label orientation
from math import pi
p.xaxis.major_label_orientation = pi/2

# We display the graph
bk_plt.show(p)
inputs: I am working on the file "11.Introduction_to_Numpy.ipynb".
The first task is:
Translating from Python to English, "call the randint module from the random module of numpy, then select 20 numbers between 0 and 999 at random, and assign that to an array named rand_arr i.e. 0 is included, 1000 is excluded.
<img src="images/simples.gif"> <br><br>
Can you write Python code for it?

targets: 
rand_arr.reshape(5,4)

rand_arr.reshape(4,5)

rand_arr.reshape(2,10)
inputs: "Adding wind vectors can be done with the incwind argument."
Please write code following the instructions in jupyter notebook style.

targets: 
test.map2d("t",incwind=True)
inputs: #Weight matrices generated by the neural network after training

#Maps the label vectors to the neuron activity of the ensemble
label_weights = cPickle.load(open("label_weights1000.p", "rb"))
#Maps the activity of the neurons to the visual representation of the image
activity_to_img_weights = cPickle.load(open("activity_to_img_weights_scale1000.p", "rb"))
#Maps the activity of the neurons of an image with the activity of the neurons of an image scaled
scale_up_weights = cPickle.load(open("scale_up_weights1000.p", "rb"))
scale_down_weights = cPickle.load(open("scale_down_weights1000.p", "rb"))

#Create the pointers for the numbers
temp = np.diag([1]*10)

ZERO = temp[0]
ONE =  temp[1]
TWO =  temp[2]
THREE= temp[3]
FOUR = temp[4]
FIVE = temp[5]
SIX =  temp[6]
SEVEN =temp[7]
EIGHT= temp[8]
NINE = temp[9]

labels =[ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE]

#Visualize the one hot representation
print(ZERO)
print(ONE)
Given the above code, generate some markdown instructions for it.

targets: 
Load the weight matrices from the training
inputs: I am working on the file "Notebooks/Using nbconvert as a Library.ipynb".
The first task is:
Notice that base64 images are not embeded, but instead there are file name like strings.  The strings actually are (configurable) keys that map to the binary data in the resources dict.
Note, if you write an RST Plugin, you are responsible for writing all the files to the disk (or uploading, etc...) in the right location.  Of course, the naming scheme is configurable.
As an exercise, this notebook will show you how to get one of those images.
Can you write Python code for it?

targets: 
list(resources['outputs'])
inputs: "Create an input pipeline
Typically, you will use a two step proces to build the pipeline. Step one is to define the columns of data; i.e., which column we're predicting for, and the default values.  Step 2 is to define two functions - a function to define the features and label you want to use and a function to load the training data.  Also, note that pickup_datetime is a string and we will need to handle this in our feature engineered model."
Please write code following the instructions in jupyter notebook style.

targets: 
CSV_COLUMNS = [
    "fare_amount",
    "pickup_datetime",
    "pickup_longitude",
    "pickup_latitude",
    "dropoff_longitude",
    "dropoff_latitude",
    "passenger_count",
    "key",
]
LABEL_COLUMN = "fare_amount"
STRING_COLS = ["pickup_datetime"]
NUMERIC_COLS = [
    "pickup_longitude",
    "pickup_latitude",
    "dropoff_longitude",
    "dropoff_latitude",
    "passenger_count",
]
DEFAULTS = [[0.0], ["na"], [0.0], [0.0], [0.0], [0.0], [0.0], ["na"]]
DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

# A function to define features and labesl
def features_and_labels(row_data):
    for unwanted_col in ["key"]:
        row_data.pop(unwanted_col)
    label = row_data.pop(LABEL_COLUMN)
    return row_data, label


# A utility method to create a tf.data dataset from a Pandas Dataframe
def load_dataset(pattern, batch_size=1, mode="eval"):
    dataset = tf.data.experimental.make_csv_dataset(
        pattern, batch_size, CSV_COLUMNS, DEFAULTS
    )
    dataset = dataset.map(features_and_labels)  # features, label
    if mode == "train":
        dataset = dataset.shuffle(1000).repeat()
        # take advantage of multi-threading; 1=AUTOTUNE
        dataset = dataset.prefetch(1)
    return dataset
inputs: Creating the next_fn
We now use our client and server update code to write the actual algorithm. We will first turn our client_update into a tff.tf_computation that accepts a client datasets and server weights, and outputs an updated client weights tensor.
We will need the corresponding types to properly decorate our function. Luckily, the type of the server weights can be extracted directly from our model.

targets: whimsy_model = model_fn()
tf_dataset_type = tff.SequenceType(whimsy_model.input_spec)
inputs: "13. Change the age in row 'f' to 1.5."
Please write code following the instructions in jupyter notebook style.

targets: 
df.loc['f', 'age'] = 1.5
inputs: 4. Making the plot easier to read and more informative
<p>While the plot above is informative enough, it can be improved. Bitcoin is too big, and the other coins are hard to distinguish because of this. Instead of the percentage, let's use a log<sup>10</sup> scale of the "raw" capitalization. Plus, let's use color to group similar coins and make the plot more informative<sup>1</sup>. </p>
<p>For the colors rationale: bitcoin-cash and bitcoin-gold are forks of the bitcoin <a href="https://en.wikipedia.org/wiki/Blockchain">blockchain</a><sup>2</sup>. Ethereum and Cardano both offer Turing Complete <a href="https://en.wikipedia.org/wiki/Smart_contract">smart contracts</a>. Iota and Ripple are not minable. Dash, Litecoin, and Monero get their own color.</p>
<p><sup>1</sup> <em>This coloring is a simplification. There are more differences and similarities that are not being represented here.</em></p>
<p><sup>2</sup> <em>The bitcoin forks are actually <strong>very</strong> different, but it is out of scope to talk about them here. Please see the warning above and do your own research.</em></p>

targets: # Colors for the bar plot
COLORS = ['orange', 'green', 'orange', 'cyan', 'cyan', 'blue', 'silver', 'orange', 'red', 'green']

# Plotting market_cap_usd as before but adding the colors and scaling the y-axis  
ax = cap10.plot.bar(x='id',y='market_cap_perc',title=TOP_CAP_TITLE, color=COLORS, log=True)

# Annotating the y axis with 'USD'
ax.set_ylabel("USD")

# Final touch! Removing the xlabel as it is not very informative
ax.set_xlabel('')
inputs: "Calculating event distribution for a sphere
We can also use the event_distribution for a sample with a sphere boundary. To do this, simply set boundary='sphere' when setting the sample parameters above. See montecarlo_tutorial.ipynb for additional optional parameters that can be set for the sphere case. 
Calculate event distribution
Input the output from calc_refl_trans() into a function that calculates the how the reflectance is distributed across all the events"
Please write code following the instructions in jupyter notebook style.

targets: 
refl_events, trans_events = ed.calc_refl_trans_event(refl_per_traj, 
                                                     inc_refl_per_traj, 
                                                     trans_per_traj, 
                                                     refl_indices, 
                                                     trans_indices, 
                                                     nevents)
inputs: I am working on the file "ANTLR4-Python/LR-Parser-Generator/LR-Table-Generator.ipynb".
The first task is:
The function to_rule(self) turns the extended marked rule self into  a GrammarRule, i.e. the extended marked rule
$$ c \rightarrow \alpha \bullet \beta: L $$
is turned into the grammar rule
$$ c \rightarrow \alpha\, \beta. $$
Can you write Python code for it?

targets: 
def to_rule(self):
    return GrammarRule(self.mVariable, self.mAlpha + self.mBeta)

ExtendedMarkedRule.to_rule = to_rule
del to_rule
inputs: "Analyze with OPS"
Please write code following the instructions in jupyter notebook style.

targets: 
analysis_file = paths.AnalysisStorage("one_way.nc")

scheme = analysis_file.schemes[0]
scheme.move_summary(analysis_file.steps)

import openpathsampling.visualize as ops_vis
from IPython.display import SVG
history = ops_vis.PathTree(
    analysis_file.steps,
    ops_vis.ReplicaEvolution(replica=0)
)
# switch to the "boxcar" look for the trajectories
history.options.movers['default']['new'] = 'single'
history.options.css['horizontal_gap'] = True
SVG(history.svg())

path_lengths = [len(step.active[0].trajectory) for step in analysis_file.steps]
plt.hist(path_lengths, alpha=0.5);

cv_x = analysis_file.cvs['x']
# load the active trajectory as storage.steps[step_num].active[replica_id]
plt.plot(cv_x(analysis_file.steps[2].active[0]), 'o-');
inputs: I am working on the file ".ipynb_checkpoints/AAG_16 copy-checkpoint.ipynb".
The first task is:
Future Work & Vision
$\Longrightarrow$ Provide more accessible alternatives to spatial optimization & GIS
$\Longrightarrow$ Develop a python library to bring together spatial analysis & spatial optimization in one package [spanoptpy], potentially incorporating:
|QGIS|  PySAL  |  NetworkX  |  Pandas & QGrid |  GeoPandas  |  NumPy / SciPy  |  Shapely  |  Bokeh | CyLP | PostgreSQL & PostGIS
|----|---------|-------------------------------------------------------------------------
|GIS|network analysis|network analysis|data frames|geo dataframes|scientific computing|geometric objects|visualizations|optimization | DBMS
$\Longrightarrow$ Need PySAL.Network to be able to handle larger networks
$\Longrightarrow$ Intergration with PostgreSQL & PostGIS for data storage
$\Longrightarrow$ Develop functionality within a Linux environment
$\Longrightarrow$  scipy.spatial.cKDTree(dist_matrix)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$\ast$  query_ball_point() for close neighbors of the selected sites
$\Longrightarrow$ Master CyLP from COIN-OR or develop an open-source optimization suite

interface with CLP, CBC, CGL
[ http://mpy.github.io/CyLPdoc/ ]
relatively steep learning curve 
Computational Optimization Infrastructure for Operations Research
[ http://www.coin-or.org ]

$\ast$ CyLP example
Minimize
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $ 3x + 2y $
Subject To
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $ x \geq 3$
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $ y \geq 5$
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $ x - y \leq 20$
Can you write Python code for it?

targets: 
# Gurobi
m = gbp.Model()
m.setParam('OutputFlag', False) 
x = m.addVar(vtype=gbp.GRB.CONTINUOUS, name='x')
y = m.addVar(vtype=gbp.GRB.CONTINUOUS, name='y')
m.update()
m.setObjective(3*x + 2*y, gbp.GRB.MINIMIZE)
m.addConstr(x >= 3)
m.addConstr(y >= 5)
m.addConstr(x - y <= 20)
m.optimize()
#m.write('path_m.lp')
print m.objVal
print m.getVars()

# CyLP
s = CyClpSimplex()
x = s.addVariable('x', 1)
y = s.addVariable('y', 1)
s.addConstraint(x >= 3)
s.addConstraint(y >= 5)
s.addConstraint(x - y <= 20)
s.objective = 3 * x + 2 * y
s.primal()
#s.writeLp('path_s')
print s.objectiveValue
print s.primalVariableSolution
print 'Gurobi & CLP Objective Values match? --> ', m.objVal == s.objectiveValue
inputs: # Train PCA on training data set
X_pca_train = pca.fit_transform(X_train)

# apply to test set
X_pca_test = pca.transform(X_test)

# we'll leave the test set for later.

# instantiate the random forest classifier:
RFmod = RandomForestClassifier()

# do a grid search over the free random forest parameters:
pars = {"n_estimators": [10, 100, 300],
        "max_features": [1, 2], 
        "min_samples_leaf": [1,10]}

grid_results = GridSearchCV(RandomForestClassifier(), 
                            pars,
                            cv = 5)

grid_results.fit(X_pca_train, y_train)



grid_results.best_score_
Given the above code, generate some markdown instructions for it.

targets: 
Exercise 5: Re-do the classification on the PCA components instead of the original features.
inputs: "As you might expect, the posterior distribution for A is shifted to the right and the posterior distribution for B is shifted to the left.
We can summarize the results by computing the posterior means:"
Please write code following the instructions in jupyter notebook style.

targets: 
prior.mean()

print(marginal_A.mean(), marginal_B.mean())
inputs: # TODO: Import 'train_test_split'
from sklearn.cross_validation import train_test_split

# TODO: Shuffle and split the data into training and testing subsets
X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.2, random_state=0)

# Success
print "Training and testing split was successful."
Given the above code, generate some markdown instructions for it.

targets: 
Answer: According to the R^2 result above, the model successfull captures the variations in the target variables. 
Implementation: Shuffle and Split Data
Your next implementation requires that you take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is also shuffled into a random order when creating the training and testing subsets to remove any bias in the ordering of the dataset.
For the code cell below, you will need to implement the following:
- Use train_test_split from sklearn.cross_validation to shuffle and split the features and prices data into training and testing sets.
  - Split the data into 80% training and 20% testing.
  - Set the random_state for train_test_split to a value of your choice. This ensures results are consistent.
- Assign the train and testing splits to X_train, X_test, y_train, and y_test.
inputs: #@test {"skip": true}
try:
  %%time
except:
  pass

# Reset the train step
tf_agent.train_step_counter.assign(0)

# Evaluate the agent's policy once before training.
avg_return = get_eval_metrics()["AverageReturn"]
returns = [avg_return]

for _ in range(num_iterations):
  # Training.
  collect_actor.run()
  loss_info = agent_learner.run(iterations=1)

  # Evaluating.
  step = agent_learner.train_step_numpy

  if eval_interval and step % eval_interval == 0:
    metrics = get_eval_metrics()
    log_eval_metrics(step, metrics)
    returns.append(metrics["AverageReturn"])

  if log_interval and step % log_interval == 0:
    print('step = {0}: loss = {1}'.format(step, loss_info.loss.numpy()))

rb_observer.close()
reverb_server.stop()
Given the above code, generate some markdown instructions for it.

targets: 
さまざまなメトリクスの他の標準実装については、metrics moduleをご覧ください。
エージェントのトレーニング
トレーニングループには、環境からのデータ収集とエージェントのネットワークの最適化の両方が含まれます。途中で、エージェントのポリシーを時々評価して、状況を確認します。
inputs: # Create a symmetric matrix
S = A + A.T

# Compute eigenvectors of S and print eigenvalues
lmbda, U = np.linalg.eig(S)
print(lmbda)

# R matrix
R = U.T

# Diagonalise S
Lambda = R.dot(S.dot(R.T))
print(Lambda)
Given the above code, generate some markdown instructions for it.

targets: 
Note that the matrix Lambda ($\boldsymbol{\Lambda}$) is diagonal, and the diagonal entries are the eigenvalues.
Diagonalisation of symmetric matrices
In the above, we have only required that the eigenvectors be linearly independent. In this case, the matrix $\boldsymbol{U}$ can be inverted. For a symmetric matrix, we have proved in the lecture notes that the eigenvectors are orthogonal. Therefore, for a real, symmetric matrix $\boldsymbol{S}$, if the eigenvectors have been normalised the matrix $\boldsymbol{U}$ is an orthogonal matrix. In this case 
$$
\boldsymbol{S} = \boldsymbol{U} \boldsymbol{\Lambda} \boldsymbol{U}^{T}
$$
In terms of the notation used for the rotation of matrices, $\boldsymbol{R} = \boldsymbol{U}^{T}$, where in this case $\boldsymbol{R}$ is used to change the basis to one aligned with the eigenvectors:
$$
\boldsymbol{S} = \boldsymbol{R}^{T} \boldsymbol{\Lambda} \boldsymbol{R}
$$
Since $\boldsymbol{R}$ is an orthogonal matrix,
$$
\boldsymbol{\Lambda} = \boldsymbol{R} \boldsymbol{S} \boldsymbol{R}^{T}
$$
We can test this for a given matrix:
inputs: As you see, the loss and error rate is decreasing as the finetuning progresses.
Let's see the classification result after finetuning.

targets: _, _ = run_validation(pred_valid, loss_valid, top_1_error_valid, input_image_valid, data_iterator_valid, with_visualized=True)
inputs: # Number of Epochs
num_epochs = 200

# Batch Size
batch_size = 128

# RNN Size
rnn_size = 256

# Embedding Dimension Size
embed_dim = 300

# Sequence Length
seq_length = 20

# Learning Rate
learning_rate = 0.01

# Show stats for every n number of batches
show_every_n_batches = 13

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = './save'
Given the above code, generate some markdown instructions for it.

targets: 
Neural Network Training
Hyperparameters
Tune the following parameters:

Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the neural network should print progress.
inputs: "3. Examples of training Logit-Linear / GBM / DNN predictors
Next we train 3 models on all 4 CNN collections with the best hyperparameter configurations we found during our studies (documented in Table 2 and Section 4 of the paper).
First, we load the best hyperparameter configurations we found.
The file best_configs.json contains a list. 
Each entry of that list corresponds to the single hyperparameter configuration. 
It consists of: 
(1) name of the CNN collection (mnist/fashion mnist/cifar10/svhn) 
(2) predictor type (linear/dnn/lgbm)
(3) type of inputs, (refer to Table 2)
(4) value of MSE you will get training with these settings, 
(5) dictionary of "parameter name"-> "parameter value" for the given type of predictor."
Please write code following the instructions in jupyter notebook style.

targets: 
with gfile.GFile(os.path.join(CONFIGS_PATH_BASE, 'best_configs.json'), 'r') as file:
  best_configs = json.load(file)
inputs: "Compute now the mean square error (MSE) and the negative log-predictive density (NLPD) with the following code:"
Please write code following the instructions in jupyter notebook style.

targets: 
# <SOL>
MSE = np.mean((m_y - Ytest)**2)
NLPD = 0.5 * np.mean(((Ytest - m_y)**2)/v_y) + 0.5*np.log(2*np.pi*v_y)
# </SOL>
inputs: 4.B Using the pywt.wavedec() for the decomposition of a signal into the frequency sub-bands
(and reconstrucing it again)

targets: time = np.linspace(0, 1, num=2048)
chirp_signal = np.sin(250 * np.pi * time**2)

coefficients_level1 = pywt.wavedec(chirp_signal, 'db2', 'smooth', level=1)
coefficients_level2 = pywt.wavedec(chirp_signal, 'db2', 'smooth', level=2)
coefficients_level3 = pywt.wavedec(chirp_signal, 'db2', 'smooth', level=3)
coefficients_level4 = pywt.wavedec(chirp_signal, 'db2', 'smooth', level=4)
coefficients_level5 = pywt.wavedec(chirp_signal, 'db2', 'smooth', level=5)

reconstructed_signal_level1 = pywt.waverec(coefficients_level1, 'db2', 'smooth')
reconstructed_signal_level2 = pywt.waverec(coefficients_level2, 'db2', 'smooth')
reconstructed_signal_level3 = pywt.waverec(coefficients_level3, 'db2', 'smooth')
reconstructed_signal_level4 = pywt.waverec(coefficients_level4, 'db2', 'smooth')
reconstructed_signal_level5 = pywt.waverec(coefficients_level5, 'db2', 'smooth')

fig, ax = plt.subplots(figsize=(12,4))
ax.plot(chirp_signal, label='signal')
ax.plot(reconstructed_signal_level1, label='reconstructed level 1', linestyle='--')
ax.plot(reconstructed_signal_level2, label='reconstructed level 2', linestyle='--')
ax.plot(reconstructed_signal_level3, label='reconstructed level 3', linestyle='--')
ax.plot(reconstructed_signal_level4, label='reconstructed level 4', linestyle='--')
ax.plot(reconstructed_signal_level5, label='reconstructed level 5', linestyle='--')
ax.legend(loc='upper right')
ax.set_title('single reconstruction', fontsize=20)
ax.set_xlabel('time axis', fontsize=16)
ax.set_ylabel('Amplitude', fontsize=16)
plt.show()