Muennighoff/xP3x-sample huggingface dataset:
inputs: "Assim, podemos calcular a probabilidade de um novo indivíduo ser do sexo masculino."
Please write code following the instructions in jupyter notebook style.

targets: 
P(sexo_m, PDSexo)
inputs: I am working on the file "Gurobi_v_Cplex__Pmedian.ipynb".
The first task is:
<font size='5' face='Times New Roman'><b>2.2b <u>Instantiate Selected Cplex <i>p</i>-median shapefile</u></b></font>
Can you write Python code for it?

targets: 
SHP_Median_CPLEX = shp.Writer(shp.POINT)
# Add Points
for idy,idx,x,y in NEW_Records_PMP_CPLEX:
    SHP_Median_CPLEX.point(float(x), float(y))
# Add Fields
SHP_Median_CPLEX.field('y_ID')
SHP_Median_CPLEX.field('x_ID')
SHP_Median_CPLEX.field('LAT')
SHP_Median_CPLEX.field('LON')
# Add Records
for idy,idx,x,y in NEW_Records_PMP_CPLEX:
    SHP_Median_CPLEX.record(idy,idx,x,y)
# Save Shapefile    
SHP_Median_CPLEX.save('shapefiles/Selected_Locations_Pmedian_CPLEX')
inputs: "And let's see how accurate we are:"
Please write code following the instructions in jupyter notebook style.

targets: 
np.sum(y_flip == predicted_y)
inputs: <hr/>

Voting Classifier
This is a very basic method of constructing an aggregated classifier from a finite dictionary.
Let $\mathcal{V}$ be the set of classifiers (voters), with each calssifier's class probablilites
given by $\hat{f}_v:\mathcal{X}\mapsto\mathbb{[0,1]}^K$ and prediction
$\hat{g}_v(x) = \mathtt{MAJ}(\hat{f}_v(x))$.
The majority vote over $K$ candidates with weights $(w_k){k=1}^K\in \mathbb{R}$ is defined as
$$ \mathtt{MAJ}(w) = \mathop{\text{argmax}}{k=1\,\ldots, K} w_k \,. $$
Hard voting collects label-prediction of each voter, counts the voting proportions and,
then predict the label with the most votes. Mathematically the following aggregation is
used:
$$ \hat{g}^{\text{maj}}\mathcal{V}(x)
    = \mathtt{MAJ}\Bigl( W^{-1} \sum{v\in \mathcal{V}} w_v e_{\hat{g}v(x)} \Bigr)
    \,, $$
where $e_k$ is the $k$-th unit vector in ${0,1}^{K\times 1}$, and $W = \sum{v\in \mathcal{V}} w_v$.
Soft voting uses the class-probabilities functions directly: it computes the weighted
average probability of each class over all voters, and then selects the class with the
highest posterior probability. Namely,
$$ \hat{g}^{\text{maj}}\mathcal{V}(x)
    = \mathtt{MAJ}\bigl( W^{-1} \sum{v\in \mathcal{V}} w_v \hat{f}_v(x) \bigr)
    \,. $$
As in Bagging, if the base classifiers are well calibrated, then hard voting
will ovrestimate probabilities.
Usage

targets: from sklearn.ensemble import VotingClassifier
inputs: I am working on the file "11-InfraredMeasurementAndAnalysis.ipynb".
The first task is:
The following graph plots the source radiance versus source temperature, for the instrument spectral response, as defined in the input files.
Can you write Python code for it?

targets: 
calData.LU.PlotCalTempRadiance()
# HTML('<img src="images/lwir100mm0150us10ND20090910-CalTempRadiance.png" width=800 />')
# display(Image(filename='lwir100mm0150us10ND20090910-CalTempRadiance.png'))
inputs: I am working on the file "Applied Plotting in Python/Week 2/.ipynb_checkpoints/Week 2 - course-checkpoint.ipynb".
The first task is:
Bar Charts
Can you write Python code for it?

targets: 
plt.figure()
xvals = range(len(linear_data))
plt.bar(xvals, linear_data, width = 0.3)

new_xvals = []

# plot another set of bars, adjusting the new xvals to make up for the first set of bars plotted
for item in xvals:
    new_xvals.append(item+0.3)

plt.bar(new_xvals, exponential_data, width = 0.3 ,color='red')

from random import randint
linear_err = [randint(0,15) for x in range(len(linear_data))] 

# This will plot a new set of bars with errorbars using the list of random error values
plt.bar(xvals, linear_data, width = 0.3, yerr=linear_err)

# stacked bar charts are also possible
plt.figure()
xvals = range(len(linear_data))
plt.bar(xvals, linear_data, width = 0.3, color='b')
plt.bar(xvals, exponential_data, width = 0.3, bottom=linear_data, color='r')

# or use barh for horizontal bar charts
plt.figure()
xvals = range(len(linear_data))
plt.barh(xvals, linear_data, height = 0.3, color='b')
plt.barh(xvals, exponential_data, height = 0.3, left=linear_data, color='r')

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]

plt.bar(pos, popularity, align='center')
plt.xticks(pos, languages)
plt.ylabel('% Popularity')
plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow', alpha=0.8)

#TODO: remove all the ticks (both axes), and tick labels on the Y axis

ax = plt.gca()
ax.set_yticklabels([])
ax.tick_params(top="off", bottom="off", left="off", right="off", labelleft="off", labelbottom="on")
plt.show()

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

languages =['Python', 'SQL', 'Java', 'C++', 'JavaScript']
pos = np.arange(len(languages))
popularity = [56, 39, 34, 34, 29]

plt.bar(pos, popularity, align='center')
plt.xticks(pos, languages)
plt.ylabel('% Popularity')
plt.title('Top 5 Languages for Math & Data \nby % popularity on Stack Overflow', alpha=0.8)

# remove all the ticks (both axes), and tick labels on the Y...
inputs: I am working on the file "Lightcurve/Lightcurve tutorial.ipynb".
The first task is:
Let's add some badly formatted GTIs:
Can you write Python code for it?

targets: 
gti = [(10, 100), (20, 30, 40), ((1, 2), (3, 4, (5, 6)))] # not a well-behaved GTI
lc = Lightcurve(time, counts, dt=0.1, skip_checks=True, gti=gti)

lc.check_lightcurve()
inputs: I am working on the file "2015_2016/lab12/Morse Complex.ipynb".
The first task is:
Let us try the code on the complex K (full triangle).
Can you write Python code for it?

targets: 
V, C = generate_field(K)
print(V, C)
inputs: #Get Parliament session dates from Parliament API
psd=pd.read_csv('http://lda.data.parliament.uk/sessions.csv?_view=Sessions&_pageSize=50')
psd

def getParliamentDate(session):
    start=psd[psd['display name']==session]['start date'].iloc[0]
    end=psd[psd['display name']==session]['end date'].iloc[0]
    return start, end

getParliamentDate('2015-2016')

#Check the columns in the Hansard dataset, along with example values
df=drill.query(''' SELECT * from dfs.tmp.`/senti_post_v2.parquet` LIMIT 1''').to_dataframe()
print(df.columns.tolist())
df.iloc[0]

# Example of count of speeches by person in the dataset as a whole
q='''
SELECT proper_name, COUNT(*) AS number 
FROM dfs.tmp.`/senti_post_v2.parquet`
GROUP BY proper_name
'''

df=drill.query(q).to_dataframe()
df.head()

# Example of count of speeches by gender in the dataset as a whole
q="SELECT gender, count(*) AS `Number of Speeches` FROM dfs.tmp.`/senti_post_v2.parquet` GROUP BY gender"
drill.query(q).to_dataframe()

#Query within session
session='2015-2016'

start,end=getParliamentDate(session)
q='''
SELECT '{session}' AS session, gender, count(*) AS `Number of Speeches`
FROM dfs.tmp.`/senti_post_v2.parquet`
WHERE speech_date>='{start}' AND speech_date<='{end}'
GROUP BY gender
'''.format(session=session, start=start, end=end)

drill.query(q).to_dataframe()

#Count number of speeches per person
start,end=getParliamentDate(session)
q='''
SELECT '{session}' AS session, gender, mnis_id, count(*) AS `Number of Speeches`
FROM dfs.tmp.`/senti_post_v2.parquet`
WHERE speech_date>='{start}' AND speech_date<='{end}'
GROUP BY mnis_id, gender
'''.format(session=session, start=start, end=end)

drill.query(q).to_dataframe().head()

# Example of finding the average number of speeches per person by gender in a particular session
q='''
SELECT AVG(gcount) AS average, gender, session
FROM (SELECT '{session}' AS session, gender, mnis_id, count(*) AS gcount
        FROM dfs.tmp.`/senti_post_v2.parquet`
        WHERE speech_date>='{start}' AND speech_date<='{end}'
       ...
Given the above code, generate some markdown instructions for it.

targets: 
The Hansard data gives the date of each speech but not the session. To search for speeches within a particular session, we need the session dates. We can get these from the Parliament data API.
inputs: "Create the bag of words"
Please write code following the instructions in jupyter notebook style.

targets: 
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(analyzer = "word",   \
                             tokenizer = None,    \
                             preprocessor = None, \
                             stop_words = None,   \
                             max_features = 5000) 

train_data_features = vectorizer.fit_transform(data['lower'])

# Numpy arrays are easy to work with, so convert the result to an 
# array
train_data_features = train_data_features.toarray()

# let's see what we have there
vectorizer.get_feature_names()[-5:]

len(data)
inputs: I am working on the file "Chapter2/chptr2.3.ipynb".
The first task is:
CI for continuous data, Pg 18
Can you write Python code for it?

targets: 
# import the t-distribution from scipy.stats
from scipy.stats import t

y = np.array([35,34,38,35,37])
y

n = len(y)
n

estimate = np.mean(y)
estimate
inputs: # Create Experiment with never resume.
kclient.create_experiment(experiment_never_resume,namespace=namespace)
# Create Experiment with from volume resume.
kclient.create_experiment(experiment_from_volume_resume,namespace=namespace)
Given the above code, generate some markdown instructions for it.

targets: 
Create other Experiments.
inputs: Coefficients to find

targets: w_true = [3,3,3]
w_true = w_true / np.sum(w_true)

mu_true = [3,10,20]

sigma_true = [2,4,1]
inputs: "2. A Simple Example
Before going too much into preprocessing, feature extraction and other more complicated tasks, we will do a relatively simple but complete example. In this example, we will use bag-of-words as features, and Naive Bayes as classifier to establish our baseline.
There are some built-in vectorizers, CountVectorizer and TfidfVectorizer that we can use to vectorizer our raw data and perform preprocessing and feature exctration on it. First, we will experiment with CountVectorizer which basically makes a token/ngram a feature and stores its count in the corresponding feature space. The fit_transform() function is the combination of fit() and transform(), and it's a more efficient implementation. fit() indexes the vocabulary/features, and transform() transforms the dataset into a matrix."
Please write code following the instructions in jupyter notebook style.

targets: 
from sklearn.feature_extraction.text import CountVectorizer
# initialize a CountVectorizer
cv = CountVectorizer()
# fit the raw data into the vectorizer and tranform it into a series of arrays
X_train_counts = cv.fit_transform(X_train)
X_train_counts.shape
inputs: I am working on the file "Chart_Samples.ipynb".
The first task is:
This graph shows a trend towards a lower average score, as well as a greater abundance of low scores, with time. This is probably at least partially a selection effect -- Rotten Tomatoes probably doesn't archive reviews for all movies, especially ones that came out before the website existed. Thus, reviews of old movies are more often "the classics". Mediocre old movies have been partially forgotten, and are underrepresented in the data. Other questions worth exploring:
Does the down trend mean:
* the quality of movies has dropped ?
* the top critics became more stringent in giving higher ratings?
* more top critics with stringent ratings entered the scene?
Can you write Python code for it?

targets: 
df=pd.read_csv("01_heights_weights_genders.csv")
df.head()

from sklearn.linear_model import LogisticRegression
clf_l, Xtrain_l, ytrain_l, Xtest_l, ytest_l  = do_classify(LogisticRegression(), {"C": [0.01, 0.1, 1, 10, 100]}, df, ['Weight', 'Height'], 'Gender','Male')

plt.figure(figsize =(12,8))
plt.xlabel("Weight")
plt.ylabel("Height")
ax=plt.gca()
points_plot(ax, Xtrain_l, Xtest_l, ytrain_l, ytest_l, clf_l, alpha=0.2);
inputs: Algorithm to simulate GMRF with block-circulant

targets: ## Simulate random noise (Normal distributed)
zr = scipy.stats.norm.rvs(size=(C.size,2),loc=0,scale=1)
zr.dtype=np.complex_
#plt.hist(zr.real)


from scipy.fftpack import ifft2, fft2

Lm = scipy.sqrt(C.shape[0]*C.shape[0]) * fft2(C)

Lm.shape

zr.shape

Lm.size

%time v = fft2(scipy.sqrt(Lm) * zr.reshape(Lm.shape))

x = v.real

x.shape

plt.imshow(x,interpolation='None')

cc = scipy.linalg.inv(C)

plt.plot(cc[:,0])

n = x.shape[0]
mm = scipy.stats.multivariate_normal(np.zeros(n),cc)

mmm = mm.rvs()

plt.imshow(mmm.reshape(100,100))

scipy.stats.multivariate_normal?

nn = mm.rvs()
inputs: "Create and execute an online query
Now that your index is deployed, you can make queries.
First, you construct a vector query using synthetic data, to use as the example to return matches for.
Next, you make the matching request using the method match(), with the following parameters:

deployed_index_id:  The identifier of the deployed index.
queries: A list of queries (instances).
num_neighbors: The number of closest matches to return."
Please write code following the instructions in jupyter notebook style.

targets: 
# The number of nearest neighbors to be retrieved from database for each query.
NUM_NEIGHBOURS = 10

# Test query
queries = [
    [
        -0.11333,
        0.48402,
        0.090771,
        -0.22439,
        0.034206,
        -0.55831,
        0.041849,
        -0.53573,
        0.18809,
        -0.58722,
        0.015313,
        -0.014555,
        0.80842,
        -0.038519,
        0.75348,
        0.70502,
        -0.17863,
        0.3222,
        0.67575,
        0.67198,
        0.26044,
        0.4187,
        -0.34122,
        0.2286,
        -0.53529,
        1.2582,
        -0.091543,
        0.19716,
        -0.037454,
        -0.3336,
        0.31399,
        0.36488,
        0.71263,
        0.1307,
        -0.24654,
        -0.52445,
        -0.036091,
        0.55068,
        0.10017,
        0.48095,
        0.71104,
        -0.053462,
        0.22325,
        0.30917,
        -0.39926,
        0.036634,
        -0.35431,
        -0.42795,
        0.46444,
        0.25586,
        0.68257,
        -0.20821,
        0.38433,
        0.055773,
        -0.2539,
        -0.20804,
        0.52522,
        -0.11399,
        -0.3253,
        -0.44104,
        0.17528,
        0.62255,
        0.50237,
        -0.7607,
        -0.071786,
        0.0080131,
        -0.13286,
        0.50097,
        0.18824,
        -0.54722,
        -0.42664,
        0.4292,
        0.14877,
        -0.0072514,
        -0.16484,
        -0.059798,
        0.9895,
        -0.61738,
        0.054169,
        0.48424,
        -0.35084,
        -0.27053,
        0.37829,
        0.11503,
        -0.39613,
        0.24266,
        0.39147,
        -0.075256,
        0.65093,
        -0.20822,
        -0.17456,
        0.53571,
        -0.16537,
        0.13582,
        -0.56016,
        0.016964,
        0.1277,
        0.94071,
        -0.22608,
        -0.021106,
    ],
    [
        -0.99544,
        -2.3651,
        -0.24332,
        -1.0321,
        0.42052,
        -1.1817,
        -0.16451,
        -1.683,
      ...
inputs: # Using the test sample conaining only selected predictors
yhat_test = linreg.predict(Xtest) # Predict 
mse_test = np.mean(np.power(yhat_test - ytest, 2))

# Form the matrix from the RAW set
Xm = Xtrain.as_matrix()
ym = ytrain.as_matrix()

from sklearn.model_selection import KFold

def doKFold(Xt, yt, K):
    # Using K = 5
    kf = KFold(n_splits=K)
    mse_cv = 0
    for train_indeces, test_indeces in kf.split(Xm):
        # Select only the most relevant attributes
        # In the previous section we chose attributes with index 2, 9 and 10
        # as the most relevant.
        Xtrain_k = Xtrain.iloc[train_indeces].as_matrix()
        Xtest_k = Xtrain.iloc[test_indeces].as_matrix()
        ytrain_k = ytrain.iloc[train_indeces].as_matrix()
        ytest_k = ytrain.iloc[test_indeces].as_matrix()

        # Perform linear regression for this fold
        linreg = lm.LinearRegression(fit_intercept = False)
        linreg.fit(Xtrain_k, ytrain_k)

        # Get the yhat for our test set
        yhat_val = linreg.predict(Xtest_k)

        # Calculate the MSE for the error
        mse_fold = np.mean(np.power(yhat_val - ytest_k, 2))
        mse_cv += mse_fold
    mse_cv = mse_cv / K
    return mse_cv


{"mse5": doKFold(Xtrain, ytrain, 5), "mse10": doKFold(Xtrain, ytrain, 10), "mse_test": mse_test}
Given the above code, generate some markdown instructions for it.

targets: 
Esto implica que los atributos seleccionados son similarmente importantes en la predicción del precio.
g) Estime el error de predicción del modelo usando validación cruzada con un número de folds igual a K
= 5 y K = 10. Recuerde que para que la estimación sea razonable, en cada configuración (fold) deberá
reajustar los pesos del modelo. Mida el error real del modelo sobre el conjunto de pruebas, compare y
concluya.
Asumiendo que se debe utilizar el modelo con la selección de atributos seleccionada anteriormente, se tiene:
inputs: # PROPERTY ID - DO NOT EDIT !  
DOC.set_id('cmip6.atmos.key_properties.resolution.range_horizontal_resolution')  

# PROPERTY VALUE: 
# Set as follows: DOC.set_value("value")  
# TODO - please enter value(s)

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

targets: 
2.3. Range Horizontal Resolution
Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1
Range of horizontal resolution with spatial details, eg. 1 deg (Equator) - 0.5 deg
inputs: I am working on the file "03_memmap/03_memmap.ipynb".
The first task is:
About groups and hierarchical organization...
An HDF5 file is a container for two kinds of objects: datasets, which are array-like collections of data, and groups, which are folder-like containers that hold datasets and other groups. The most fundamental thing to remember when using h5py is:
Groups work like folders, and datasets work like NumPy arrays!
<img src='data/hdf5.jpg' style="width: 600px;">
Can you write Python code for it?

targets: 
# The File object we created is itself a group, in this case the root group
print( f.name )
print( dset.name )

# Lets create a subgroup
f.create_group("subgroup")

# Lets create a new dataset inside this subgroup
dset2 = f.create_dataset('subgroup/dataset2', (10,), dtype='i')
print(dset2.name)

# Retrieving datasets/arrays from hdf5 file
print( f["dataset"] )
print( f["subgroup/dataset2"] )

f.close()
inputs: "Create Module
The most widely used module class is Module, which wraps a Symbol and one or more Executors.
We construct a module by specify

symbol : the network Symbol
context : the device (or a list of devices) for execution
data_names : the list of data variable names 
label_names : the list of label variable names

One can refer to data.ipynb for more explanations about the last two arguments. Here we have only one data named data, and one label, with the name softmax_label, which is automatically named for us following the name softmax we specified for the SoftmaxOutput operator."
Please write code following the instructions in jupyter notebook style.

targets: 
mod = mx.mod.Module(symbol=net, 
                    context=mx.cpu(),
                    data_names=['data'], 
                    label_names=['softmax_label'])
inputs: # Tehdään luokittelija
clf_dt = DecisionTreeClassifier()
clf_dt.fit(X_train.reshape(-1,28*28), y_train)
pred_dt = clf_dt.predict(X_test.reshape(-1,28*28))

# Piirretään tulokseksi alkupäästä luokituksia
pltsize=1
plt.figure(figsize=(10*pltsize, pltsize))
for i in range(10):
    plt.subplot(1,10,i+1)
    plt.axis('off')
    plt.imshow(X_test[i,:,:])
    plt.title(str(pred_dt[i]) + ' (' + str(y_test[i]) + ')')

# Raportoidaan tulokset
print('Luokiteltu', len(pred_dt), 'kuvaa, luokituksista oikein menneiden osuus on:', accuracy_score(y_test, pred_dt)*100, '%')
print('Alla kuvat ja analysoidut luokat, oikeat luokat ovat suluissa')
Given the above code, generate some markdown instructions for it.

targets: 
Voidaanko sanoa, että tämä satunnainen sotku on selvästi eri tulos kuin aiemmin tekemämme pääkomponenttianalyysin tuottama?
Merkkien tunnistaminen
Seuraavaksi pääsemme itse asiaan. Olemme nyt pöyhineet dataa ja päässeet varmuuteen, että se on järkevää ja analysoitavissa.
Rakennamme koneoppimismenetelmiä käyttäen nk. luokittelijan, joka kykenee oppimaan kuvien piirteet ja tunnistamaan niitä sen jälkeen. Nyt on syytä jälleen olla tarkkana: jos syötämme menetelmälle dataa, niin se varmasti osaa oppia ulkoa kyseisen datan kaikki yksityiskohdat. Mutta haluamme, että menetelmä "näkee metsän puilta", eli oppii tunnistamaan merkkien yleisiä hahmoja. Teemme siis koneoppimisen perustempun, eli jaamme datan kahteen osaan. Harjoitusdatalla opetetaan menetelmä, kun taas sen toimintaa testataan testidatalla. Koneoppijan tulee siis selvitä sellaisistakin kuvista, joita se ei ole aikaisemmin nähnyt. Tällä tavalla varmistetaan, että ei pelkästään opita ulkoa harjoitusdataa.
Alla oleva koodi tekee luokittelun ja tulostaa esimerkiksi 10 ensimmäistä luokiteltua merkkiä. Luokitteluun käytetään klassista koneoppimisen menetelmää, nk. päätöspuuta. Kuinka hyvin menetelmä pärjää?
inputs: I am working on the file "ML_SS2017/numpy_rachunek_rozniczkowy.ipynb".
The first task is:
Laplasjan
https://en.wikipedia.org/wiki/Discrete_Laplace_operator
Can you write Python code for it?

targets: 
import sympy
from sympy.abc import x,y
sympy.init_printing(use_latex='mathjax')

from IPython.display import display

f_symb = sympy.sin(x**2+y**2)
lap_f = f_symb.diff(x,2) + f_symb.diff(y,2)
display(lap_f.simplify())
inputs: "Dans cas précis, on ne souhaite pas trier sur les nombres mais sur leur parité. En quelque sorte, on ne s'intéresse pas de savoir dans quel ordre deux nombres pairs seront triés. Cela réduit le nombre d'opérations à effectuer. Une idée consiste à parcourir le tableau par les deux bouts et à échanger deux nombres dès que leur parité sont mal classées."
Please write code following the instructions in jupyter notebook style.

targets: 
def trie_parite(l):
    i = 0
    j = len(l)-1
    while i < j :
        while i < j and l[i]%2 == 0 : i += 1
        while i < j and l[j]%2 == 1 : j -= 1
        if i < j:
            ech = l[i]
            l[i] = l[j]
            l[j] = ech
            i += 1
            j -= 1
    
l = l.copy()
trie_parite(l)
l
inputs: # clf_sepal.score?

clf_sepal.score(X_train_sepal_only, y_train)

clf_sepal.score(X_test_sepal_only, y_test)
Given the above code, generate some markdown instructions for it.

targets: 
Evaluation: What perecentage in each set is corretly predicted?
inputs: "Custom Agent
<center>
<img src="https://storage.googleapis.com/dm-educational/assets/reinforcement_learning/random_policy.png" width="500" />
</center>
Let's now try and manually code a better behaviour into the agent. The code below defines a way to run a custom set of actions. A value of 0 for the action means the cart is pushed left, and a value of 1 means the cart is pushed right.
Currently, the code is set to a constant zero, which pushes the cart left all the time (you'll see this if you run it and play the video!).
You can modify the function to specify what action should be taken depending on the observation.
One thing you could try is to use an if statement, which in Python, looks like the following.
if [some_condition]:
  action = [some_value]
else:
  action = [some_other_value]
Looking at the code below, you have access to the cart_position, cart_velocity, pole_angle, and pole_velocity_at_tip.
Can you think of what conditions you might use to set the actions based on these?
Ask for help if you're not sure!"
Please write code following the instructions in jupyter notebook style.

targets: 
def custom_action_for_cartpole(state):
  # for cartpole only:
  cart_position = state[0]
  cart_velocity = state[1]
  pole_angle = state[2]
  pole_velocity_at_tip = state[3]

  # Instead of making the action 0 (in cartpole: go left), try to come up with
  # a better behavior.
  action = 0

  return action


output = environment.reset()

frames, actions = step_agent_in_environment(
    env=environment, agent=custom_action_for_cartpole, num_episodes=5)

show_video(frames)
inputs: # SelectKBest for selecting top-scoring features

from sklearn import datasets
from sklearn.feature_selection import SelectKBest, chi2

iris = datasets.load_iris()
X, y = iris.data, iris.target

print(X.shape)

# Do feature selection
#  input is scoring function (here chi2) to get univariate p-values
#  and number of top-scoring features (k) - here we get the top 2
X_t = SelectKBest(chi2, k = 2).fit_transform(X, y)

print(X_t.shape)
Given the above code, generate some markdown instructions for it.

targets: 
Selecting k top scoring features (also dimensionality reduction)

Considered unsupervised learning
inputs: I am working on the file "Examples/immune/Analyse_pMHC.ipynb".
The first task is:
Select Seed
Can you write Python code for it?

targets: 
notebook.select_seed.display()
inputs: I am working on the file "PySAL.Network_&_Spatial_Optimization.ipynb".
The first task is:
Integrating PySAL.Network with Gurobi, CPLEX, & COIN-OR for optimization of the p-Center facility location problem

James Gaboardi &nbsp;| &nbsp;Florida State University&nbsp;| &nbsp;Department of Geography
Can you write Python code for it?

targets: 
# Local path on user's machine
path = '/Users/jgaboardi/FacilityLocation/Data/'
inputs: I am working on the file "07_SH_waves_in_moons_and_planets/4_2D_SHaxi_FD_modelling_ganymede.ipynb".
The first task is:
As usual, we first define the modelling parameters for an axisymmetric Ganymede model. Unfortunately, Ganymede seem to have to solid core, which would require a special treatment of the centre to avoid the singularity at $r = 0\; m$. For simplicity, we assume that Ganymedes inner core with a radius of roughly 700 km is liquid, so we can handle the CMB as free-surface boundary.
Can you write Python code for it?

targets: 
# Definition of modelling parameters
# ----------------------------------
rcore = 693.0 * 1000.0      # Ganymede fluid core radius [m]
rplanet = 2634.1 * 1000.0   # Ganymede radius [m]

nr = 400      # number of spatial gridpoints in r-direction
dr = (rplanet - rcore) / nr # spatial gridpoint distance in r-direction

# calculate dtheta based on dr
dtheta = dr / rcore
ntheta = (int) (np.pi / dtheta)  # number of spatial gridpoints in theta-direction
ntheta += 2

# Define Ganymede model filename
name_model = "ganymede_model/ganymede_model.dat"

# Acquisition geometry
tmax = 2000.0           # maximum recording time of the seismogram (s)

isnap = 5  # snapshot interval (timesteps)
inputs: "Cluster 0 - Second Fewest Lead Changes (rank 3), Second Fewest Events(rank 3), Largest average goal differential (rank 4)
Cluster 1 - Most Lead Changes (rank 1), Second Most Events (rank 2), Second largest avg goal diff (rank 3)
Cluster 2 - Second most lead changes (rank 2), most events (rank 1), third largest avg goal diff (rank 2)
Cluster 3 - fewest lead chanegs (rank 4), fewest events (rank 4), smallest avg goal diff (rank 1)

Save match df with clusters and engineered features
python
match_df.to_csv('match_cluster.csv', encoding='utf-8')"
Please write code following the instructions in jupyter notebook style.

targets: 
match_df = pd.read_csv('match_cluster.csv')

match_df = match_df.drop(['Unnamed: 0','link_odsp','adv_stats'], axis = 1)

england = match_df[match_df.country == 'england']
spain = match_df[match_df.country == 'spain']
germany = match_df[match_df.country == 'germany']
france = match_df[match_df.country == 'france']
italy = match_df[match_df.country == 'italy']
inputs: I am working on the file "PyIndex.ipynb".
The first task is:
Compare results to Whoosh
Can you write Python code for it?

targets: 
def make_clean_index(ix_dirname, paths, procs=1):
    ix = whoosh.index.create_in(ix_dirname, schema=simple_schema())
    writer = ix.writer(procs=procs)

    for filepath in paths:
        add_doc(writer, filepath)

    writer.commit()
    
    return ix

def add_doc(writer, filepath):
    with open(filepath, 'rb') as f:
        text = f.read().decode('latin')
    writer.add_document(doc=text, filepath=filepath)

t = time.time()
ix = make_clean_index('wind', sorted(glob.glob('Lincoln/*.txt')))
print("TIME:", time.time() - t)

with ix.searcher() as searcher:
    results = searcher.search(q)
    print(results)
    for hit in results:
        print('{:f}'.format(hit.score), ' | ', hit['filepath'])
inputs: "A simple function to plot the initial condition:"
Please write code following the instructions in jupyter notebook style.

targets: 
def plotIC():
    fig = plt.figure()
    axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    axes.plot(xPoints, initialCondition, 'ro')
    axes.set_xlabel('Distance $x$')
    axes.set_ylabel('Concentration of Stuff $c(x,t)$')
    axes.set_title('Initial Conditions');

plotIC()
inputs: I am working on the file "DL0110EN/1.3.1_simple_data_set_v2.ipynb".
The first task is:
Now, let us create our <code>toy_set</code> object, and find out the value on index 1 and the length of the inital dataset
Can you write Python code for it?

targets: 
# Create Dataset Object. Find out the value on index 1. Find out the length of Dataset Object.

our_dataset = toy_set()
print("Our toy_set object: ", our_dataset)
print("Value on index 0 of our toy_set object: ", our_dataset[0])
print("Our toy_set length: ", len(our_dataset))
inputs: <a id='counting'></a>
3. What can we do with a DTM?
We can do a number of calculations using a DTM. For a toy example, we can quickly identify the most frequent words (compare this to how many steps it took using NLTK).

targets: print(dtm_df.sum().sort_values(ascending=False))

##Ex: print the average number of times each word is used in a review
#Print this out sorted from highest to lowest.
inputs: BPE (Byte pair encoding) model
Sentencepiece supports BPE (byte-pair-encoding) for subword segmentation with --model_type=bpe flag.   We do not find empirical differences in translation quality between BPE and unigram model, but unigram model can perform sampling and n-best segmentation. See subword regularization paper [kudo18] for more detail.

targets: spm.SentencePieceTrainer.train('--input=botchan.txt --model_prefix=m_bpe --vocab_size=2000 --model_type=bpe')
sp_bpe = spm.SentencePieceProcessor()
sp_bpe.load('m_bpe.model')

print('*** BPE ***')
print(sp_bpe.encode_as_pieces('thisisatesthelloworld'))
print(sp_bpe.nbest_encode_as_pieces('hello world', 5))  # returns an empty list.

spm.SentencePieceTrainer.train('--input=botchan.txt --model_prefix=m_unigram --vocab_size=2000 --model_type=unigram')
sp_unigram = spm.SentencePieceProcessor()
sp_unigram.load('m_unigram.model')

print('*** Unigram ***')
print(sp_unigram.encode_as_pieces('thisisatesthelloworld'))
print(sp_unigram.nbest_encode_as_pieces('thisisatesthelloworld', 5))
inputs: %%time
y_pred = [tagger.tag(xseq) for xseq in X_test]
Given the above code, generate some markdown instructions for it.

targets: 
Predict entity labels for all sentences in our testing set ('testb' Spanish data):
inputs: I am working on the file "2016/assignment 3.ipynb".
The first task is:
Use this cell to explain / expand your answer.
Can you write Python code for it?

targets: 
## 10

# Your code goes here
inputs: %matplotlib inline
#don't forget the line above!
import glob
import numpy as np

from matplotlib import pyplot as plt

#do something here to take the first 3 files from the list.
data = np.loadtxt(fname='inflammation-01.csv', delimiter=',')
plt.figure(figsize=(10.0, 3.0))

plt.subplot(1, 3, 1)
plt.ylabel('average')
plt.plot(data.mean(axis=0))

plt.subplot(1, 3, 2)
plt.ylabel('max')
plt.plot(data.max(axis=0))

plt.subplot(1, 3, 3)
plt.ylabel('min')
plt.plot(data.min(axis=0))

plt.tight_layout()
plt.show()
Given the above code, generate some markdown instructions for it.

targets: 
Convert the following code (copied from above) to process the first 3 inflammation files and draw 3 graphs (ie. mean, max, min) for each file using "for" loop
inputs: "9 Order Topic Construct

<font color=red>countvector， lda transform</font>
由商品的Topic构造订单的Topic表达
商品加入购物车的次序？？？ 先忽视次序
每个用户学习：加购物车次序 VS 重购？ VS下张订单的Topic？？"
Please write code following the instructions in jupyter notebook style.

targets: 
order_topic = pd.merge(order_products_prior[['order_id', 'product_id']],
                       topic_product,
                       on = ['product_id'],
                       how = 'inner')#throw stop words

order_topic = order_topic.groupby(['order_id'])[["topic_%d"%x for x in range(10)]].sum().reset_index()

unorm = order_topic[["topic_%d"%x for x in range(10)]].values

order_topic[["topic_%d"%x for x in range(10)]] = unorm / unorm.sum(axis = 1)[:,np.newaxis]

len(order_products_prior.product_id.unique())

len(topic_product.product_id.unique())
inputs: I am working on the file "18_TFRecords_Dataset_API.ipynb".
The first task is:
Load Data
Can you write Python code for it?

targets: 
import knifey
inputs: I am working on the file "CarND-Traffic-Sign-Classifier-Project/traffic-sign-classification-with-keras_transfer_cifar10.ipynb".
The first task is:
Overview
Here are the steps you'll take to build the network:

Load the training data.
Preprocess the data.
Build a feedforward neural network to classify traffic signs.
Build a convolutional neural network to classify traffic signs.
Evaluate the final neural network on testing data.

Keep an eye on the network’s accuracy over time. Once the accuracy reaches the 98% range, you can be confident that you’ve built and trained an effective model.
Can you write Python code for it?

targets: 
import pickle
import numpy as np
import math

# Fix error with TF and Keras
import tensorflow as tf
tf.python.control_flow_ops = tf

print('Modules loaded.')
inputs: "<div class="alert alert-success">

<b>EXERCISE</b>:

 <ul>
  <li>How many roles in the movie "Inception" are NOT ranked by an "n" value?</li>
</ul>
</div>"
Please write code following the instructions in jupyter notebook style.

targets: 
inception = cast[cast['title'] == 'Inception']

len(inception[inception['n'].isna()])

inception['n'].isna().sum()
inputs: "2. Распределение роста для мужчин и женщин
Как мы увидели, в процессе исследования уникальных значений, пол кодируется значениями 1 и 2, расшифровка изначально не была нам дана в описании данных, но мы догадались, кто есть кто, посчитав средние значения роста (или веса) при разных значениях признака gender. Теперь сделаем то же самое, но графически. 
Постройте violinplot для роста и пола. Используйте:
- hue – для разбивки по полу
- scale – для оценки количества каждого из полов 
Для корректной отрисовки, преобразуйте DataFrame в "Long Format"-представление с помощью функции melt в pandas.
<br>
еще один пример
Постройте на одном графике два отдельных kdeplot роста, отдельно для мужчин и женщин. На нем разница будет более наглядной, но нельзя будет оценить количество мужчин/женщин."
Please write code following the instructions in jupyter notebook style.

targets: 
train.head()

filtered_df = train[(train['ap_lo'] <= train['ap_hi']) & 
                 (train['height'] >= train['height'].quantile(0.025)) &
                 (train['height'] <= train['height'].quantile(0.975)) &
                 (train['weight'] >= train['weight'].quantile(0.025)) & 
                 (train['weight'] <= train['weight'].quantile(0.975))]

df = pd.melt(filtered_df, value_vars=['weight'], id_vars='gender')
sns.violinplot(x='variable', y='value', hue='gender', data=df)

female = filtered_df[filtered_df['gender'] == 1]
male = filtered_df[filtered_df['gender'] == 2]

ax = sns.kdeplot(female.height, female.height,
                 cmap="Reds", shade=True, shade_lowest=False)
ax = sns.kdeplot(male.height, male.height,
                cmap="Blues", shade=True, shade_lowest=False)
inputs: I am working on the file "03_PrettyTensor.ipynb".
The first task is:
Using this helper-function we can retrieve the variables. These are TensorFlow objects. In order to get the contents of the variables, you must do something like: contents = session.run(weights_conv1) as demonstrated further below.
Can you write Python code for it?

targets: 
weights_conv1, biases_conv1 = get_weights_variable(layer_name='layer_conv1')
#weights_conv2 = get_weights_variable(layer_name='layer_conv2')
inputs: "22.2. Growth Respiration
Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1
Describe the general method used for growth respiration"
Please write code following the instructions in jupyter notebook style.

targets: 
# PROPERTY ID - DO NOT EDIT !  
DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.growth_respiration')  

# PROPERTY VALUE: 
# Set as follows: DOC.set_value("value")  
# TODO - please enter value(s)
inputs: """
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt


x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
Given the above code, generate some markdown instructions for it.

targets: 
Prettier plot
Matplotlib has many options for making pretty plots. Here is an example
of a simulated damped oscillator. In this example we're using numpy to generate and keep track of the numerical data.
Demo source:
http://matplotlib.org/users/screenshots.html
inputs: I am working on the file "GPy-phil/ease-of-use.ipynb".
The first task is:
In order to add coregionalization to a model we merely have to create the right kernel, which understands the coregionalization structure in the data:
Can you write Python code for it?

targets: 
kern_coreg = GPy.kern.Coregionalize(1, # Dimensionality of coregionalize input
                                    len(sex_uniques), # How many different tasks do we have?
                                    rank=3, # How deep is the coregionaliztion,
                                    # the higher the rank, the more flexible the
                                    # coregionalization, rank >= 1
                                    active_dims=[X_train.columns.get_loc('sex')] ,
                                    # Which dimension of the input carries the task information?
                                    name = 'sex',
                                   ) * kern_numeric.copy()

full_model = GPy.models.SparseGPRegression(X_train.values, Y_train.values, kernel=kern_coreg, num_inducing=40)

full_model.optimize(messages=1, max_iters=3e3)

W, k = full_model.kern.sex.parameters
coregionalization_matrix = GPy.util.linalg.tdot(W)
GPy.util.diag.add(coregionalization_matrix, k)

fig, ax = plt.subplots()
c = ax.matshow(coregionalization_matrix, cmap=plt.cm.hot)
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(sex_uniques[[0, 1, 2]], fontdict=dict(size=23))
ax.set_yticks([0, 1, 2])
ax.set_yticklabels(sex_uniques[[0, 1, 2]], fontdict=dict(thickness='bold'))
ax.xaxis.tick_top()
plt.colorbar(c, ax=ax)
fig.tight_layout()

full_model.kern.kernel.plot_ARD()
_ = plt.legend()

# Evaluate the log likelihood for the whole numerical model with coregionalization:
result_df['coreg'] = (
    log_likelihood(full_model, X_test.values, Y_test.values),
    RMSE(full_model, X_test.values, Y_test.values)
)

result_df
inputs: "Any time you need more info on a numpy function, we encourage you to look at the official documentation. 
You can also create a new cell in the notebook and write np.exp? (for example) to get quick access to the documentation.
Exercise: Implement the sigmoid function using numpy. 
Instructions: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices...) are called numpy arrays. You don't need to know more for now.
$$ \text{For } x \in \mathbb{R}^n \text{,     } sigmoid(x) = sigmoid\begin{pmatrix}
    x_1  \
    x_2  \
    ...  \
    x_n  \
\end{pmatrix} = \begin{pmatrix}
    \frac{1}{1+e^{-x_1}}  \
    \frac{1}{1+e^{-x_2}}  \
    ...  \
    \frac{1}{1+e^{-x_n}}  \
\end{pmatrix}\tag{1} $$"
Please write code following the instructions in jupyter notebook style.

targets: 
# GRADED FUNCTION: sigmoid

import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()

def sigmoid(x):
    """
    Compute the sigmoid of x

    Arguments:
    x -- A scalar or numpy array of any size

    Return:
    s -- sigmoid(x)
    """
    
    ### START CODE HERE ### (≈ 1 line of code)
    s = 1. / (1. + np.exp(-x))
    ### END CODE HERE ###
    
    return s

x = np.array([1, 2, 3])
sigmoid(x)
inputs: I am working on the file "Clustering_6_hierarchical_clustering_blank.ipynb".
The first task is:
Let's visualize the two child clusters:
Can you write Python code for it?

targets: 
display_single_tf_idf_cluster(left_child, map_index_to_word)

display_single_tf_idf_cluster(right_child, map_index_to_word)
inputs: "Building a grid
In the sample below, we'll create a simple square grid and fill the grid with households.  The parameters below will guide our model as follows:

grid_size: the number of cells per row or column; the total number of cells is $grid_size^2$.
group_proportion: the percentage of households that will be of type 1
density: the percentage of grid cells that will be populated with a household

The logic for our grid initialization can be described as follows:

For each cell in every row and column
Draw a random value on $[0, 1)$ and compare to $density$ to determine if we will fill this cell
If the cell will be filled, draw a random value on $[0, 1)$ and compare to $group_proportion$ to determine whether the household will be 1 or 2"
Please write code following the instructions in jupyter notebook style.

targets: 
# Set parameters
grid_size = 20
group_proportion = 0.25
density = 0.5

# Create the space and activate random cells
space = numpy.zeros((grid_size, grid_size), dtype=numpy.int8)

# Now sample the agents.
for row_id in range(grid_size):
    for col_id in range(grid_size):
        # Determine if this cell will be populated
        if numpy.random.random() <= density:
            # Determine this cell's initial group
            if numpy.random.random() <= group_proportion:
                cell_type = 1
            else:
                cell_type = 2
            
            # Set the space
            space[row_id, col_id] = cell_type
        
# Now show the space
f = plt.figure()
p = plt.pcolor(space, snap=True)
c = plt.colorbar()
inputs: I am working on the file "02_Classification/03.0 - TF Classification Model - DNN Wide & Deep + Train_And_Evaluate + Dataset + TFRecords.ipynb".
The first task is:
d. Run the experiment via train_and_evaluate
Can you write Python code for it?

targets: 
if not RESUME_TRAINING:
    print("Removing previous artifacts...")
    shutil.rmtree(model_dir, ignore_errors=True)
else:
    print("Resuming training...") 

    
tf.logging.set_verbosity(tf.logging.INFO)

time_start = datetime.utcnow() 
print("Experiment started at {}".format(time_start.strftime("%H:%M:%S")))
print(".......................................") 

estimator = create_estimator(run_config, hparams, True)

tf.estimator.train_and_evaluate(
    estimator=estimator,
    train_spec=train_spec, 
    eval_spec=eval_spec
)

time_end = datetime.utcnow() 
print(".......................................")
print("Experiment finished at {}".format(time_end.strftime("%H:%M:%S")))
print("")
time_elapsed = time_end - time_start
print("Experiment elapsed time: {} seconds".format(time_elapsed.total_seconds()))
inputs: "By day:"
Please write code following the instructions in jupyter notebook style.

targets: 
# Plot
daily_counts.index = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
daily_counts['counts'].plot(title='Daily tweet counts', figsize=(12, 8), legend=True)
plt.show()
inputs: Capture image from the camera

targets: ImageRecorder(stream=camera)
inputs: "3 Frequency
A frequency plot is a graph that shows the pattern in a set of data by plotting how often particular values of a measure occur. They often take the form of an histogram or a box plot.
Reproduce the plots with the following three libraries, which provide high-level declarative syntax for statistical visualization as well as a convenient interface to pandas:
* Seaborn is a statistical visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics. Its advantage is that you can modify the produced plots with matplotlib, so you loose nothing.
* ggplot is a (partial) port of the popular ggplot2 for R. It has his roots in the influencial book the grammar of graphics. Convenient if you know ggplot2 already.
* Vega is a declarative format for statistical visualization based on D3.js, a low-level javascript library for interactive visualization. Vincent (discontinued) and altair are Python libraries to vega. Altair is quite new and does not provide all the needed functionality yet, but it is promising !
Hints:
* Seaborn, look at distplot() and boxplot().
* ggplot, we are interested by the geom_histogram geometry."
Please write code following the instructions in jupyter notebook style.

targets: 
import seaborn as sns
import os
df = sns.load_dataset('iris', data_home=os.path.join('..', 'data'))

fig, axes = plt.subplots(1, 2, figsize=(15, 5))

# Your code for Seaborn: distplot() and boxplot().

import ggplot

# Your code for ggplot.

import altair

# altair.Chart(df).mark_bar(opacity=.75).encode(
#     x=...,
#     y=...,
#     color=...
# )
inputs: 3.2.1 Stack 3 - Encoder Layer 3 => Decoder layer 2

targets: with tf.variable_scope("Encoder"):
    s3_enc_l3_act = tf.layers.dense(
        inputs=tf.stop_gradient(s2_dec_noisy_input),
        units=2000,
        activation=tf.nn.relu,
        kernel_initializer=tf.contrib.layers.xavier_initializer(seed=RANDOM_SEED),
        name="FC_3",
    )

with tf.variable_scope("Decoder"):
    s3_dec_noisy_input = tf.layers.dropout(inputs=s3_enc_l3_act, rate=0.2, seed=RANDOM_SEED, training=tf_apply_dropout)
    s3_dec_l2_act = tf.layers.dense(
        inputs=s3_dec_noisy_input,
        units=500,
        activation=tf.nn.relu,
        kernel_initializer=tf.contrib.layers.xavier_initializer(seed=RANDOM_SEED),
        name="FC_2",
    )
inputs: I am working on the file "EVI - 2018/EVI 04/Modulo1.ipynb".
The first task is:
<br>
add_numbers es una función que toma dos números y los suma.
Can you write Python code for it?

targets: 
def add_numbers(x, y):
    return x + y

add_numbers(1, 2)
inputs: <span style="text-align: right; direction: rtl; float: right; clear: both;">עיגול</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
    אפשר גם לעגל מספרים בעזרת הפונקציה <code>round</code>: 
</p>

targets: number = 5.9
round(number)

numbers = [6, 3.1415, 0.9, -0.9, 0.5, -0.5]
for number in numbers:
    print(f"round({number:>6}) = {round(number)}")
inputs: 1. Upload the model artefacts to Google Cloud Storage bucket

targets: %%bash

gsutil -m rm -r gs://${BUCKET}/tf-model-optimisation

%%bash

saved_models_base=models/mnist/cnn_classifier/export/
saved_model_dir=${saved_models_base}$(ls ${saved_models_base} | tail -n 1)

echo ${saved_model_dir}

gsutil -m cp -r ${saved_model_dir} gs://${BUCKET}/tf-model-optimisation/original

%%bash

saved_models_base=models/mnist/cnn_classifier/export/
saved_model_dir=${saved_models_base}$(ls ${saved_models_base} | tail -n 1)/optimised

echo ${saved_model_dir}

gsutil -m cp -r ${saved_model_dir} gs://${BUCKET}/tf-model-optimisation