Muennighoff/xP3x-sample huggingface dataset:
inputs: <h2>13.Area of Figures</h2>

Write a program that introduces the dimensions of a geometric figure and calculates its face.
The figures are four types: a square, a rectangle, a circle, and a triangle.
On the first line of the input reads the shape of the figure (square, rectangle, circle or triangle).
If the figure is a square, the next line reads one number- the length of its country.
If the figure is a rectangle, the next one two lines read two numbers- the lengths of his sides.
If the figure is a circle, the next line reads one number
the radius of the circle.
If the figure is a triangle, the next two lines read two numbers - the length of the
its side and the length of the height to it. Score to round to 3 digits after the decimal  point.

targets: import math

figure = input()


if figure == "square":
    side = float(input())

    area = side ** 2

    print(format(area,'.3f'))

elif figure == "rectangle":
    side_a = float(input())
    side_b = float(input())

    area = side_a * side_b

    print(format(area,'.3f'))

elif figure == "circle":
     radius = float(input())

     area = radius ** 2 * math.pi

     print(format(area,'.3f'))


elif figure == "triangle":
    side = float(input())
    height = float(input())

    area = (side * height) / 2

    print(format(area,'.3f'))
inputs: "Code Documentation
Astro Hack Week 2017
The notebook contains problems for documenting code.
These probablems assume you've done the "code repo" problem set, or otherwise are familiar with code repositories and packaging enough to have a functioning test repository with a Python package.

E Tollerud, B Sipocz
Problem 1: Making and using docstrings
One of Python's most powerful documentation tools are docstrings.  These are basically just little strings you put at the top of a class, function, or similar, which then gets bound as sort of a glorified comment.  But with internal consistency and tenacity, these can do most of the work you need to document your code.
Note that all of this problem can be done in the notebook, and it is shown that way to make the notebook internally consistent.  But you might find it more useful to use a function from your code repository, as that makes it clearer why docstrings are useful (i.e., the code is not immediately visible, as it is in the notebook).
1a: Create a function with a docstring
Make a function (or just use one from your pre-existing repo) and give it a docstring.   The docstring can be anything in principal, but the example case below shows one of the most standard conventions used for scientific Python code. (The format originated in numpy, although with some "flavors" like that in astropy.)
Hint: you might want to keep the code part of your function secret from your neighbor, as it will reduce the work for 1c if you do so"
Please write code following the instructions in jupyter notebook style.

targets: 
def do_something(arg1, arg2):
    """
    A short sentence describing what this function does.
    
    More description
    
    Parameters
    ----------
    arg1 : type1
        Description of the parameter ``arg1``
    arg2 : type2
        Description of the parameter ``arg2``
        
    Returns
    -------
    type of return value (e.g. int, float, string, etc.)
        A description of the thing the function returns (if anything)
    """ # complete
    # complete
inputs: I am working on the file "Autumn2017/02-Python-and-Data/Lecture-Python-And-Data-Completed.ipynb".
The first task is:
Note: strings in Python can be defined either with double quotes or single quotes
Viewing Pandas Dataframes
The head() and tail() methods show us the first and last rows of the data
Can you write Python code for it?

targets: 
data.head()

data.tail()
inputs: #@title Sementic search
#@markdown Enter a set of words to find matching sentences. 'results_returned' can beused to modify the number of matching sentences retured. To view the code behind this cell, use the menu in the top right to unhide...
search_string = "code of ethics" #@param {type:"string"}
results_returned = "3" #@param [1, 2, 3]

from sklearn.metrics.pairwise import cosine_similarity


embeddings2 = embed(
    [search_string],
    signature="default",
    as_dict=True)["default"]

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  sess.run(tf.tables_initializer())
  search_vect = sess.run(embeddings2)
  

cosine_similarities = pd.Series(cosine_similarity(search_vect, x).flatten())
output =""
for i,j in cosine_similarities.nlargest(int(results_returned)).iteritems():
  output +='<p style="font-family:verdana; font-size:110%;"> '
  for i in sentences[i].split():
    if i.lower() in search_string:
      output += " <b>"+str(i)+"</b>"
    else:
      output += " "+str(i)
  output += "</p><hr>"
    
output = '<h3>Results:</h3>'+output
display(HTML(output))
#   print(sentences[i])
#   print('\n')

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

targets: 
Create a semantic search engine:
inputs: Bootstrap Median Differences
http://faculty.psy.ohio-state.edu/myung/personal/course/826/bootstrap_hypo.pdf
Between groups

targets: ## Pilot vs Controls d'
dp_pilot_controls = dict()

stim_key = 'ss_us'
diffs = [x - y for x in pilot_dprimes[stim_key] for y in controls_dprimes[stim_key]]
dp_pilot_controls[stim_key] = bayes_bootstrap(diffs, scipy.median, 1000, len(diffs))

#plt.hist(dp_pilot_controls[stim_key]['bootstrap_data'])
print(dp_pilot_controls[stim_key]['CIs'])
print(dp_pilot_controls[stim_key]['central_tendency'])

stim_key = 'ss_cs'
diffs = [x - y for x in pilot_dprimes[stim_key] for y in controls_dprimes[stim_key]]
dp_pilot_controls[stim_key] = bayes_bootstrap(diffs, scipy.median, 1000, len(diffs))

#plt.hist(dp_pilot_controls[stim_key]['bootstrap_data'])
print(dp_pilot_controls[stim_key]['CIs'])
print(dp_pilot_controls[stim_key]['central_tendency'])

stim_key = 'ss_cp'
diffs = [x - y for x in pilot_dprimes[stim_key] for y in controls_dprimes[stim_key]]
dp_pilot_controls[stim_key] = bayes_bootstrap(diffs, scipy.median, 1000, len(diffs))

#plt.hist(dp_pilot_controls[stim_key]['bootstrap_data'])
print(dp_pilot_controls[stim_key]['CIs'])
print(dp_pilot_controls[stim_key]['central_tendency'])

## Controls vs Patients d'
dp_controls_patients = dict()

stim_key = 'ss_us'
diffs = [x - y for x in controls_dprimes[stim_key] for y in patients_dprimes[stim_key]]
dp_controls_patients[stim_key] = bayes_bootstrap(diffs, scipy.median, 1000, len(diffs))

#plt.hist(dp_controls_patients[stim_key]['bootstrap_data'])
print(dp_controls_patients[stim_key]['CIs'])
print(dp_controls_patients[stim_key]['central_tendency'])

stim_key = 'ss_cs'
diffs = [x - y for x in controls_dprimes[stim_key] for y in patients_dprimes[stim_key]]
dp_controls_patients[stim_key] = bayes_bootstrap(diffs, scipy.median, 1000, len(diffs))

#plt.hist(dp_controls_patients[stim_key]['bootstrap_data'])
print(dp_controls_patients[stim_key]['CIs'])
print(dp_controls_patients[stim_key]['central_tendency'])

stim_key = 'ss_cp'
diffs = [x - y for x in controls_dprimes[stim_key] 
         for y in list(filter(None, patients_dprimes[stim_key]))]
dp_controls_patients[stim_key] =...
inputs: # Read mouse data
df_mm = pd.read_table("GSE59992_counts_table.txt.gz")
df_mm["loc"] = df_mm["chrom"] + ":" + df_mm["start"].astype(str) + "-" + df_mm["end"].astype(str)
df_mm = df_mm.set_index("loc")

df_mm = df_mm[["Lsk", "CMP", "GMP", "MEP", "Monocytes", "EryA", "CD4", "CD8", "B-cells", "NK"]]
df_mm.columns = ["MPP", "CMP", "GMP", "MEP", "Monocytes", "Erythroblast", "CD4", "CD8", "Bcell", "Nkcell"]

df_mm = np.log2(df_mm + 1)
Given the above code, generate some markdown instructions for it.

targets: 
Read mouse ATAC-seq table
inputs: "<p style="text-align: right; direction: rtl; float: right; clear: both;">
    ננסה לאחזר את התוכן של הקובץ castle.txt:
</p>"
Please write code following the instructions in jupyter notebook style.

targets: 
princess_location = get_file_content('castle.txt')
inputs: "By default all the layers of the VGG16 model are trainable."
Please write code following the instructions in jupyter notebook style.

targets: 
print_layer_trainable()
inputs: Astropy can read a variety of formats easily.
The following example uses a quite

targets: # Read the data from the source
table = ascii.read("ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/snrs.dat",
                   readme="ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/ReadMe")

# See the stats of the table
table.info('stats')

# If we want to see the first 10 entries
table[0:10]

# the units are also stored, we can extract them too
table['MajDiam'].quantity.to('rad')[0:3]

# Adding values of different columns
(table['RAh'] + table['RAm'] + table['RAs'])[0:3]


# adding values of different columns but being aware of column units
(table['RAh'].quantity + table['RAm'].quantity + table['RAs'].quantity)[0:3]

# Create a new column in the table
table['RA'] = table['RAh'].quantity + table['RAm'].quantity + table['RAs'].quantity

# Show table's new column 
table['RA'][0:3]

# add a description to the new column
table['RA'].description = table['RAh'].description

# Now it does show the values
table['RA'][0:3]


# Using numpy to calculate the sin of the RA
import numpy as np
np.sin(table['RA'].quantity)

# Let's change the units...
import astropy.units as u
table['RA'].unit = u.hourangle

# does the sin now works?
np.sin(table['RA'].quantity)
inputs: "Comment on your results.
Answer: Interestingly, there's not a huge performance improvement between the two approaches! In my run, using mean imputation corresponded to about a 3 point increase in model performance. Some ideas for why this might be:

This is a small dataset to start out with, so removing ~half its samples doesn't change performance very much
There's not much information contained in the features with missing data
There are other effects underlying poor performance of the model (e.g. regularization parameters) that are having a greater impact

Preprocessing categorical variables
Load the TA evaluation dataset. As before, the data and header are split into two files, so you'll have to combine them yourself."
Please write code following the instructions in jupyter notebook style.

targets: 
data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/tae/tae.data'

names = ['native_speaker', 'instructor', 'course', 'season', 'class_size', 'rating']

df = pandas.read_csv(data_url, header=None, index_col=False, names=names)
print(df)
inputs: # no changes are required to this cell
# obtain SparkSession
sparkSession = SparkSession.builder.getOrCreate()
# load data
if username:
    conversation_df = sparkSession.read.format("com.cloudant.spark").\
                                        option("cloudant.host", host).\
                                        option("cloudant.username", username).\
                                        option("cloudant.password", password).\
                                        load(database)
else:
    conversation_df = sparkSession.read.format("com.cloudant.spark").\
                                        option("cloudant.host", host).\
                                        load(database)
Given the above code, generate some markdown instructions for it.

targets: 
Load documents from the database
Load the documents into an Apache Spark DataFrame.
inputs: # Ecrivez votre code ci-dessous et éxecutez le. 

# Une correction est donnée à titre indicatif :
poppy.motors





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

targets: 
Comme toute chose en language Python, notre robot poppy est un objet qui contient d'autres objets qui sont ses moteurs.
Ca y est, si vous arrivez à accéder aux moteurs de Poppy, vous pourrez le faire bouger...
Vous devez donc accéder aux moteurs de poppy (qui se nomment "motors") et qui se trouve à l'intérieur de Poppy pour cela tapez :

<span style="color:green">nom_du_robot</span><span style="color:red">.motors</span>
inputs: # complete
Given the above code, generate some markdown instructions for it.

targets: 
Generally speaking, the procedure for scikit-learn is uniform across all machine-learning algorithms. Models are accessed via the various modules (ensemble, SVM, neighbors, etc), with user-defined tuning parameters. The features (or data) for the models are stored in a 2D array, X, with rows representing individual sources and columns representing the corresponding feature values.$^\dagger$  In cases where there is a known classification or scalar value (typically supervised methods), this information is stored in a 1D array y. 
$^\dagger$In a minority of cases, X, represents a similarity or distance matrix where each entry represents the distance to every other source in the data set.
Unsupervised models are fit by calling .fit(X) and supervised models are fit by calling .fit(X, y). In both cases, predictions for new observations, Xnew, can be obtained by calling .predict(Xnew). Those are the basics and beyond that, the details are algorithm specific, so ...
read the docs!
Problem 1a What is the pythonic type of iris?
inputs: I am working on the file "Pic-ozone/Apprent-Python-Ozone.ipynb".
The first task is:
Régression logistique ou modèle binomial
La même démarche est déroulée mais en modélisant directement la variable binaire Yb de dépassement ou non du seuil. Il s'agit d'une régression logistique avec toujours une pénalisation Lasso pour opérer une sélection de variables.
Can you write Python code for it?

targets: 
from sklearn.linear_model import LogisticRegression

# Optimisation du paramètre de pénalisation
# grille de valeurs
param=[{"C":[1,1.2,1.5,1.7,2,3,4]}]
logit = GridSearchCV(LogisticRegression(penalty="l1",solver="liblinear"), param,cv=5,n_jobs=-1)
logitOpt=logit.fit(Xr_train, Yb_train)  # GridSearchCV est lui même un estimateur
# paramètre optimal
logitOpt.best_params_["C"]
print("Meilleur score = %f, Meilleur paramètre = %s" % (1.-logitOpt.best_score_,logitOpt.best_params_))

# erreur sur l'échantillon test
1-logitOpt.score(Xr_test, Yb_test)
inputs: I am working on the file "0.14/_downloads/plot_mixed_source_space_inverse.ipynb".
The first task is:
Set up our source space.
Can you write Python code for it?

targets: 
# List substructures we are interested in. We select only the
# sub structures we want to include in the source space
labels_vol = ['Left-Amygdala',
              'Left-Thalamus-Proper',
              'Left-Cerebellum-Cortex',
              'Brain-Stem',
              'Right-Amygdala',
              'Right-Thalamus-Proper',
              'Right-Cerebellum-Cortex']

# Get a surface-based source space. We could set one up like this::
#
#     >>> src = setup_source_space(subject, fname=None, spacing='oct6',
#                                  add_dist=False, subjects_dir=subjects_dir)
#
# But we already have one saved:

src = mne.read_source_spaces(op.join(bem_dir, 'sample-oct-6-src.fif'))

# Now we create a mixed src space by adding the volume regions specified in the
# list labels_vol. First, read the aseg file and the source space bounds
# using the inner skull surface (here using 10mm spacing to save time):

vol_src = setup_volume_source_space(
    subject, mri=fname_aseg, pos=7.0, bem=fname_model,
    volume_label=labels_vol, subjects_dir=subjects_dir, verbose=True)

# Generate the mixed source space
src += vol_src

# Visualize the source space.
src.plot(subjects_dir=subjects_dir)

n = sum(src[i]['nuse'] for i in range(len(src)))
print('the src space contains %d spaces and %d points' % (len(src), n))

# We could write the mixed source space with::
#
#    >>> write_source_spaces(fname_mixed_src, src, overwrite=True)
#
inputs: # Get model resource ID
models = aiplatform.Model.list(filter="display_name=claritin_" + TIMESTAMP)

# Get a reference to the Model Service client
client_options = {"api_endpoint": f"{REGION}-aiplatform.googleapis.com"}
model_service_client = aiplatform.gapic.ModelServiceClient(
    client_options=client_options
)

model_evaluations = model_service_client.list_model_evaluations(
    parent=models[0].resource_name
)
model_evaluation = list(model_evaluations)[0]
print(model_evaluation)
Given the above code, generate some markdown instructions for it.

targets: 
Review model evaluation scores
After your model has finished training, you can review the evaluation scores for it.
First, you need to get a reference to the new model. As with datasets, you can either use the reference to the model variable you created when you deployed the model or you can list all of the models in your project.
inputs: I am working on the file "2.0/tutorials/RV.ipynb".
The first task is:
If rv_method is set to 'dynamical' then the computed radial velocities are simply the z-velocities of the centers of mass of each component.  In this case, only the dynamical options are relevant.  For more details on these, see the section on the orb dataset.
If rv_method is set to 'flux-weighted' then radial velocities are determined by the z-velocity of each visible surface element of the mesh, weighted by their respective intensities.  Since the stars are placed in their orbits by the dynamic options, the section on the orb dataset is still applicable.  So are the meshing options described in mesh dataset and the options for computing fluxes in lc dataset.
rv_grav
Can you write Python code for it?

targets: 
print ps_compute['rv_grav']
inputs: (2c) RMSE do baseline para os conjuntos de treino, validação e teste 
Vamos calcular o RMSE para nossa baseline. Primeiro crie uma RDD de (rótulo, predição) para cada conjunto, e então chame a função calcRMSE.

targets: # EXERCICIO
labelsAndPredsTrain = parsedTrainData.map(lambda p: (p.label, averageTrainYear))
rmseTrainBase = calcRMSE(labelsAndPredsTrain)

labelsAndPredsVal = parsedValData.map(lambda p: (p.label, averageTrainYear))
rmseValBase = calcRMSE(labelsAndPredsVal)

labelsAndPredsTest = parsedTestData.map(lambda p: (p.label, averageTrainYear))
rmseTestBase = calcRMSE(labelsAndPredsTest)

print ('Baseline Train RMSE = {0:.3f}'.format(rmseTrainBase))
print ('Baseline Validation RMSE = {0:.3f}'.format(rmseValBase))
print ('Baseline Test RMSE = {0:.3f}'.format(rmseTestBase))

# TEST Training, validation and test RMSE (2c)
assert np.allclose([rmseTrainBase, rmseValBase, rmseTestBase],[21.506125957738682, 20.877445428452468, 21.260493955081916]), 'incorrect RMSE value'
print("OK")
inputs: <img src="array_multiplication.jpg">
Question 4.3.2. Suppose the total charge at a restaurant is the original bill plus the tip.  That means we can multiply the original bill by 1.2 to get the total charge.  Compute the total charge for each bill in restaurant_bills.

targets: total_charges = ...
total_charges

_ = tests.grade('q432')
inputs: # use default connection (TD_API_KEY is used)
engine = td.create_engine('presto:sample_datasets')
Given the above code, generate some markdown instructions for it.

targets: 
create_engine uses "default" connection if apikey and host are omitted.  In this case, the environment variables "TD_API_KEY" and "TD_API_SERVER" are used to initialize a connection:
inputs: I am working on the file "Day 1 - Unit 1.3.ipynb".
The first task is:
As with lists, tuples can also be indexed and sliced. However, once assigned, individual components of a tuple cannot be changed. For example, the following code will raise and error
Can you write Python code for it?

targets: 
pair[0] = 2
inputs: And here's what the result looks like:

targets: from utils import decorate

def decorate_dice(title=''):
    decorate(xlabel='Outcome',
             ylabel='PMF',
             title=title)

twice = add_dist(die, die)
twice.bar(color='C1', alpha=0.5)
decorate_dice()
inputs: An Ordered Dictionary:

targets: print 'Dictionaries are equal? '

d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'


d2 = collections.OrderedDict()

d2['b'] = 'B'
d2['a'] = 'A'

print d1 == d2
inputs: %%matlab
figure
plot(x,y,'b.');
hold on
plot(x,ftheta(theta_chap,x),'r');
            
Given the above code, generate some markdown instructions for it.

targets: 
<font color="red"> Quelles sont les valeurs de theta_chap? A quoi sert l’argument [1 1]? Essayez de reproduire l’estimation avec d’autres valeurs pour cet argument, est-ce que cela affecte le résultat?</font>

<font color="blue">Le paramètre theta_chap vaut [-237.5729 1.7794]. L'argument [1 1] est une valeur initiale de la méthode qui cherche la valeur theta_chap. En répétant l'expérience pour plusieurs valeurs ([2 2], [30 30], [-30 -30]) on voit que la résultat theta_chap ne semble pas dépendre ici de ce paramètre. </font>
<ol start="5">
  <h4><li>Maintenant représenter le résultat de la régression. </li></h4>
</ol>
inputs: # TODO: Calculate number of students
n_students = student_data.shape[0]

# TODO: Calculate number of features
n_features = student_data.shape[1] -1

# TODO: Calculate passing students
n_passed = np.sum(student_data.passed == 'yes')

# TODO: Calculate failing students
n_failed = np.sum(student_data.passed =='no')

# TODO: Calculate graduation rate
grad_rate = 100 * np.mean(student_data.passed == 'yes')

# Print the results
print "Total number of students: {}".format(n_students)
print "Number of features: {}".format(n_features)
print "Number of students who passed: {}".format(n_passed)
print "Number of students who failed: {}".format(n_failed)
print "Graduation rate of the class: {:.2f}%".format(grad_rate)
Given the above code, generate some markdown instructions for it.

targets: 
Implementation: Data Exploration
Let's begin by investigating the dataset to determine how many students we have information on, and learn about the graduation rate among these students. In the code cell below, you will need to compute the following:
- The total number of students, n_students.
- The total number of features for each student, n_features.
- The number of those students who passed, n_passed.
- The number of those students who failed, n_failed.
- The graduation rate of the class, grad_rate, in percent (%).
inputs: "Change True to 1, False to 0"
Please write code following the instructions in jupyter notebook style.

targets: 
diabetes_map = {True : 1, False : 0}

df['diabetes'] = df['diabetes'].map(diabetes_map)

df.head(5)
inputs: "<a id='save'></a>
Here we cover two main ways to save data files for use again later, one that is Python-specific, and the other a simple text format.

np.save('file_path', array_name) - Creates a .npy file (Python readable only!)
np.savetxt('file_path', array_name) - Creates a plain text (or .txt) file (more generally readable)

The basic syntax is pretty much the same for each. What differs is the type of file that the functions create. Below is an example of how each function can be called to store the same data."
Please write code following the instructions in jupyter notebook style.

targets: 
np.save('./lecture2_data/dataFix.npy',dataFix)
np.savetxt('./lecture2_data/dataFix.txt',dataFix)
inputs: # include 1-grams and 2-grams
vect = CountVectorizer(ngram_range=(1, 2), min_df=5)
X_train_dtm = vect.fit_transform(X_train)
X_train_dtm.shape

# last 50 features
print(vect.get_feature_names()[-50:])
Given the above code, generate some markdown instructions for it.

targets: 
ngram_range: tuple (min_n, max_n)
The lower and upper boundary of the range of n-values for different n-grams to be extracted. All values of n such that min_n <= n <= max_n will be used.
inputs: "2.3 Prediction (10 points)
The predictive distribution of Bayesian linear regression is:
$$ p(t \;|\; \bx, \bt, \alpha, \beta) = \mathcal{N}(t \;|\; \bm_N^T \phi(\bx), \sigma_N^2(\bx))$$
$$ \sigma_N^2 = \frac{1}{\beta} + \phi(\bx)^T \bS_N \phi(\bx) $$
where $\phi(\bx)$ are the computed features for a new datapoint $\bx$, and $t$ is the predicted variable for datapoint $\bx$. 
Write a function that predict_polynomial_bayes(x, m, S, beta) that returns the predictive mean, variance and design matrix $\bPhi$ given a new datapoint x, posterior mean m, posterior variance S and a choice of model variance beta."
Please write code following the instructions in jupyter notebook style.

targets: 
def predict_polynomial_bayes(x, m, S, beta):
    """
    Predict the target values for input x
    and return the predictions, the posterior variance and Phi.
    """
    Phi = designmatrix(x, len(m)-1)
    sigma = [(1 / beta + np.asscalar(Phi[i] * S * Phi[i].T))
             for i in range(len(x))]
    mean = [np.asscalar(m*Phi[i].T) for i in range(len(x))]

    return np.array(mean), np.array(sigma), Phi


### Test your function
np.random.seed(5)
N = 10
x = np.linspace(-1, 1, N)
m = np.empty(3)
S = np.empty((3, 3))
beta = 25
mean, sigma, Phi = predict_polynomial_bayes(x, m, S, beta)

assert mean.shape == (N,), "the shape of mean is incorrect"
assert sigma.shape == (N,), "the shape of sigma is incorrect"
assert Phi.shape == (N, m.shape[0]), "the shape of Phi is incorrect"
inputs: Accuracy
Decreasing tolerance below improves the shape of responses, at the expense of increased number of timesteps.

targets: reltol = 1e-5  # decrease to increase quality and runtime
inputs: I am working on the file "04_Visualisation/4_Visualisation.ipynb".
The first task is:
J'ai utilisé le format d'image png, utile pour les images de type graphique, avec des changements de couleurs drastiques. Pour les photos, vous préférerez le format jpg. Des éditeurs demandront peut-être des formats vectoriels comme pdf ou eps. Si vous désirez éditer vos graphiques (bouger des étiquettes ou des légendes, ajouter des éléments graphiques), vous pouvez exporter voter graphique en format svg, puis l'éditer dans le logiciel libre Inkscape. Quoi qu'il en soit, voici les format d'exportation disponibles.
Can you write Python code for it?

targets: 
fig.canvas.get_supported_filetypes()
inputs: 8.3.1 Matches and Perfect Matches
matching: a matching is a subset of the edges such that no node is an end of two or more edges.
perfect matching: a matching is said to be perfect if every node appears in the matching.
maximal matching: a matching that is as large as any other matching for the graph in question is said to be maximal.

targets: plt.figure(figsize=(8,8))
plt.imshow(plt.imread('./res/fig8_2.png'))
inputs: "Bal
Балкона может не быть, балкон может быть, а еще балконов может быть больше одного. Информации о балконе может не быть.
Так что будем готовы к значениям > 1. Прочерк будет говорить о том, что информации нет, слово "нет" - о том, что есть информация о том, что нет балкона."
Please write code following the instructions in jupyter notebook style.

targets: 
def getBal(flat_page):
    table = flat_page.find('table', attrs = {'class':'object_descr_props'})
    table = html_stripper(table)
    
    space_block = re.split('Общая площадь', table)[1]
    optional_block = re.split('Жилая площадь', space_block)[1]
    
    balcony = np.nan
    if 'Балкон' in optional_block:
        balcony_block = re.split('Балкон', optional_block)[1]
        if re.split('\n', balcony_block)[1] != 'нет':
            if re.split('\n', balcony_block)[1] != '–':
                balcony = int(re.split('\n', balcony_block)[1][0])
        else:
            balcony = 0
            
    return balcony

def getAllBal(l, r):
    
    bal = []
    
    for i in range(l, r):
        flat_url = 'http://www.cian.ru/sale/flat/' + str(links[i]) + '/'
        flat_page = requests.get(flat_url)
        flat_page = flat_page.content
        flat_page = BeautifulSoup(flat_page, 'lxml')
        bal.append(getBal(flat_page))
        
    return bal

bal = getAllBal(0, len(links))
inputs: # Calculate losses
labels_real = tf.ones_like(d_logits_real) * (1 - smooth)
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=labels_real))

labels_fake = tf.zeros_like(d_logits_fake)
d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=labels_fake))

d_loss = d_loss_real + d_loss_fake

g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_logits_fake)))
Given the above code, generate some markdown instructions for it.

targets: 
Discriminator and Generator Losses
Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropies, which we can get with tf.nn.sigmoid_cross_entropy_with_logits. We'll also wrap that in tf.reduce_mean to get the mean for all the images in the batch. So the losses will look something like 
python
tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=labels))
For the real image logits, we'll use d_logits_real which we got from the discriminator in the cell above. For the labels, we want them to be all ones, since these are all real images. To help the discriminator generalize better, the labels are reduced a bit from 1.0 to 0.9, for example,  using the parameter smooth. This is known as label smoothing, typically used with classifiers to improve performance. In TensorFlow, it looks something like labels = tf.ones_like(tensor) * (1 - smooth)
The discriminator loss for the fake data is similar. The logits are d_logits_fake, which we got from passing the generator output to the discriminator. These fake logits are used with labels of all zeros. Remember that we want the discriminator to output 1 for real images and 0 for fake images, so we need to set up the losses to reflect that.
Finally, the generator losses are using d_logits_fake, the fake image logits. But, now the labels are all ones. The generator is trying to fool the discriminator, so it wants to discriminator to output ones for fake images.

Exercise: Calculate the losses for the discriminator and the generator. There are two discriminator losses, one for real images and one for fake images. For the real image loss, use the real logits and (smoothed) labels of ones. For the fake image loss, use the fake logits with labels of all zeros. The total discriminator loss is the sum of those two losses. Finally, the generator loss again uses the fake logits from the...
inputs: "Considerations
model_card.considerations contains qualifying information about your model - what are the appropriate use cases, what are limitations that users should keep in mind, what are the ethical considerations of application, etc."
Please write code following the instructions in jupyter notebook style.

targets: 
model_card.considerations.use_cases = [
    mctlib.UseCase(description='This model classifies images of cats and dogs.')
]
model_card.considerations.limitations = [
    mctlib.Limitation(description='This model is not able to classify images of other classes.')
]
model_card.considerations.ethical_considerations = [mctlib.Risk(
    name=
        'While distinguishing between cats and dogs is generally agreed to be '
        'a benign application of machine learning, harmful results can occur '
        'when the model attempts to classify images that don’t contain cats or '
        'dogs.',
    mitigation_strategy=
        'Avoid application on non-dog and non-cat images.'
)]
inputs: # FIXME
n = 20

x = np.random.uniform(-1,1,(n,1))
y = 4*x[:,0] + np.random.normal(0,0.3, (n,))

plt.scatter(x,y)

# simple univariate regression 

for n in range(20):
    ridge = sklearn.linear_model.Ridge(alpha=1*np.exp(-n), fit_intercept=True)
    ridge.fit(x,y)
    # predict output
    xs = np.linspace(-1,1,100)[:, None]
    ys = ridge.predict(xs)
    plt.plot(xs,ys,c=[n/20.0, n/20.0, n/20.0, 1])
    plt.ylim(-5,5)



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

targets: 
Overfitting and regularisation
Overfitting
We saw examples of overfitting in the previous lecture. Preventing overfitting is one of the major challenges of machine learning. It is easy to build models that can approximate any function; but approximating in a way that generalises to unseen data is much harder.
Enforcing structure to minimise overfitting is called regularisation. Techniques such as bagging or bootstrap methods that we saw in the previous lecture are examples of randomised approaches to regularisation.  By forcing learning algorithms to learn from impoverished datasets and then averaging the results, we can prevent the learning from conforming into the irrelvant "nooks and crannies" of the functions to be learned.
Penalisation
An alternative approach is to explicitly penalise functions for getting too complicated. This is called penalisation and is widely used in statistical modelling. An explicit penalty function is defined which applies a constraint to the optimisation of parameters to force the function being learned to stay "smooth".
Developing a penalty function is tricky, as it is not always clear how enforcing constraints of the parameters of a learning algorithm affects the generalisation properties of the result. However, there are many well-developed techniques for which good penalty function are known. 
These functions often try to make the parameters small or to make as many of them as possible zero (maximising sparseness).
Lasso / ridge regression
One common approach is to apply penalties when fitting a linear model (i.e. $y=w^Tx$) that constrain the values of linear fit to be small. The specific norm used to measure the size of the coefficients gives rise to various regularisation approaches.
An approach which forces the coefficients to be small in the $L_2$ norm (i.e. the Euclidean distance of the coefficient vector to the origin) is called ridge regression; using the $L_1$ norm (the sum of coefficient values) is called lasso regression.
inputs: By default our triple has an equal mass inner binary, so the octupole order term is zero!  We can see this explicitly by looking at the $C_3$ coefficient:

targets: triple.C3
inputs: And then a second model with extinction.

targets: b.set_value('Av',2.0)
b.run_compute(model='ext',overwrite=True)
inputs: 6. Which variables are binary?

targets: result=getDfSummary(ads)
result.loc[(result.Number_Distinct==2)]

#We can use Number_Distinct as an indicator of binary variables since the value of the below four variables can either be 0 or 1.
#Number_Distinct of the below four variables is 2 and max and min is 1 and 0 respectively.
inputs: 18.
Let us inspect the weights (coefficients) of the simple_model. First, build a table to store (word, coefficient) pairs. If you are using SFrame with scikit-learn, you can combine words with coefficients by running

targets: simple_model_coef_table = pd.DataFrame({'word':significant_words,
                                         'coefficient':simple_model.coef_.flatten()})
#simple_model_coef_table
simple_model_coef_table.sort_values(['coefficient'], ascending=False)
inputs: # We know that MNIST images are 28 pixels in each dimension.
img_size = 28

# Images are stored in one-dimensional arrays of this length.
img_size_flat = img_size * img_size

# Tuple with height and width of images used to reshape arrays.
# This is used for plotting the images.
img_shape = (img_size, img_size)

# Tuple with height, width and depth used to reshape arrays.
# This is used for reshaping in Keras.
img_shape_full = (img_size, img_size, 1)

# Number of colour channels for the images: 1 channel for gray-scale.
num_channels = 1

# Number of classes, one class for each of 10 digits.
num_classes = 10
Given the above code, generate some markdown instructions for it.

targets: 
Data Dimensions
The data dimensions are used in several places in the source-code below. They are defined once so we can use these variables instead of numbers throughout the source-code below.
inputs: Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
    - Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the following tuple (Cell, InitialState)

targets: lstm_layers = 1
keep_prob = 1

def get_init_cell(batch_size, rnn_size):
    """
    Create an RNN Cell and initialize it.
    :param batch_size: Size of batches
    :param rnn_size: Size of RNNs
    :return: Tuple (cell, initialize state)
    """
    # TODO: Implement Function
    lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
    drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
    cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers)
    cell_state = cell.zero_state(batch_size, tf.float32)
    cell_state = tf.identity(cell_state, name = 'initial_state')
    return cell, cell_state


"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_init_cell(get_init_cell)
inputs: I am working on the file "Python/5 Linear Regression/Simple-Linear-Regression.ipynb".
The first task is:
Next, we compute the residual sum of squares RSS as follows:
$$ \mathtt{RSS} := \sum\limits_{i=1}^m \bigl(\vartheta_1 \cdot x_i + \vartheta_0 - y_i\bigr)^2 $$
Can you write Python code for it?

targets: 
RSS = np.sum((ϑ1 * X + ϑ0 - Y) ** 2)
RSS
inputs: "Create the model
It's time to create your neural network:"
Please write code following the instructions in jupyter notebook style.

targets: 
embedding_dim = 16

# Create your neural network
model = tf.keras.Sequential([
  layers.Embedding(max_features + 1, embedding_dim),
  layers.Dropout(0.2),
  layers.GlobalAveragePooling1D(),
  layers.Dropout(0.2),
  layers.Dense(1)])

model.summary()
inputs: "Creating Dictionary through assignment.
We can create a dictionary by assignment also. As with lists, dictionary are also not of fixed size. You can add any number of values to a dictionary."
Please write code following the instructions in jupyter notebook style.

targets: 
d = {}
inputs: "As an example, let's use the celltypes column to make a list of each celltype color first. Notice that we can use cell_metadata.celltype or cell_metadata['celltype'] to get the column we want.
We can only use the 'dot' notation because our column name has no unfriendly characters like spaces, dashes, or dots -- characters that mean something special in Python."
Please write code following the instructions in jupyter notebook style.

targets: 
celltypes = cell_metadata.celltype.unique()  # Could also use cell_metadata['celltype'].unique()
celltypes

celltype_to_color = dict(zip(celltypes, sns.color_palette('Accent', n_colors=len(celltypes))))
celltype_to_color
inputs: I am working on the file "09-Topic-Modeling/01-Topic-Modeling.ipynb".
The first task is:
Now we can use our cv to fit_transform our training list of novels (strings!):
Can you write Python code for it?

targets: 
dtm = cv.fit_transform(train)
inputs: # Initialize the structured data classifier.
clf = ak.StructuredDataClassifier(
    overwrite=True, max_trials=3
)  # It tries 3 different models.
# Feed the structured data classifier with training data.
clf.fit(
    # The path to the train.csv file.
    train_file_path,
    # The name of the label column.
    "survived",
    epochs=10,
)
# Predict with the best model.
predicted_y = clf.predict(test_file_path)
# Evaluate the best model with testing data.
print(clf.evaluate(test_file_path, "survived"))

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

targets: 
The second step is to run the
StructuredDataClassifier.
As a quick demo, we set epochs to 10.
You can also leave the epochs unspecified for an adaptive number of epochs.
inputs: Again, also for writing we can use a with statement, which is very handy.
But let's have a look at what happens here, so we understand a bit better why "write mode" must be used carefully!

targets: with open("test.txt", "w") as out:
    out.write("Oooops! new content")
inputs: After two vanilla cookies, the high-numbered bowls have the highest posterior probabilities because they contain the most vanilla cookies; the low-numbered bowls have the lowest probabilities.
But suppose we draw again and get a chocolate cookie.
Here's the update:

targets: likelihood_chocolate = 1 - hypos/100

posterior3 = posterior2 * likelihood_chocolate
posterior3.normalize()
inputs: 2.2 Loading and Transforming the Data
The data is loaded and transformed as follows:

targets: training = np.loadtxt("data/in.dta")
X_train = add_ones_column(training[:,:-1])
y_train = training[:,-1]
X_train = add_nonlinear_features(X_train,7)
n_train = y_train.shape[0]

testing  = np.loadtxt("data/out.dta")
X_test  = add_ones_column(testing[:,:-1])
y_test  = testing[:,-1]
X_test  = add_nonlinear_features(X_test,7)
n_test = y_test.shape[0]

n_features = X_train.shape[1]
inputs: Access to the Image Mosaics
Additional to the data, we also provide the image mosaics used to extract the information in the MVM-VAC. To access these mosaics use the instruction: morp.show_mosaic('survey')
Version_1.0.1 (DR16). For this version there are two sets of mosaics: 
i) the SDSS mosaic, containing a gray logarithmic-scaled r-band image, a filter-enhanced r-band image and the corresponding gri colour composite image, from the SDSS images. 'survey'='sdss'
ii) the DESI mosaic, containing a filter-enhanced r-band image and the corresponding gri colour composite image, from the DESI images. 'survey'='desi'
Version_2.0.1 (DR17).
For this version, we have combined the relevant information from SDSS and DESI surveys in one mosaic. This mosacis contains the gri colour composite image from SDSS; the grz colour composite image, the residual image after subtraction of a best surface brightness model and the filter-enhanced r-band image from the DESI Legacy Surveys. 'survey'='mos'

targets: morp.show_mosaic('sdss')
inputs: # Solution

# We'll need an object to keep track of the number of cookies in each bowl. 
# I use a Hist object, defined in thinkbayes2:

bowl1 = Hist(dict(vanilla=30, chocolate=10))
bowl2 = Hist(dict(vanilla=20, chocolate=20))

bowl1.Print()

# Solution

# Now I'll make a Pmf that contains the two bowls, giving them equal probability.

pmf = Pmf([bowl1, bowl2])
pmf.Print()

# Solution

# Here's a likelihood function that takes `hypo`, which is one of 
# the Hist objects that represents a bowl, and `data`, which is either 
# 'vanilla' or 'chocolate'.

# `likelihood` computes the likelihood of the data under the hypothesis, 
# and as a side effect, it removes one of the cookies from `hypo`

def likelihood(hypo, data):
    like = hypo[data] / hypo.Total()
    if like:
        hypo[data] -= 1
    return like

# Solution

# Now for the update.  We have to loop through the hypotheses and 
# compute the likelihood of the data under each hypothesis.

def update(pmf, data):
    for hypo in pmf:
        pmf[hypo] *= likelihood(hypo, data)
    return pmf.Normalize()

# Solution

# Here's the first update.  The posterior probabilities are the 
# same as what we got before, but notice that the number of cookies 
# in each Hist has been updated.

update(pmf, 'vanilla')
pmf.Print()

# Solution

# So when we update again with a chocolate cookies, we get different 
# likelihoods, and different posteriors.

update(pmf, 'chocolate')
pmf.Print()

# Solution

# If we get 10 more chocolate cookies, that eliminates Bowl 1 completely

for i in range(10):
    update(pmf, 'chocolate')
    print(pmf[bowl1])
Given the above code, generate some markdown instructions for it.

targets: 
Exercise In Section 2.3 I said that the solution to the cookie problem generalizes to the case where we draw multiple cookies with replacement.
But in the more likely scenario where we eat the cookies we draw, the likelihood of each draw depends on the previous draws.
Modify the solution in this chapter to handle selection without replacement. Hint: add instance variables to Cookie to represent the hypothetical state of the bowls, and modify Likelihood accordingly. You might want to define a Bowl object.
inputs: I am working on the file "5-sympy.ipynb".
The first task is:
La función subs también puede ser usada para substituir símbolos y expresiones:
Can you write Python code for it?

targets: 
y.subs(x, a+sym.pi)
inputs: # Train the model on our training data while validating on our validation set
history_1 = model_1.fit(x_train, y_train, epochs=1000, batch_size=16,
                    validation_data=(x_validate, y_validate))
Given the above code, generate some markdown instructions for it.

targets: 
Train the model
Once we've defined the model, we can use our data to train it. Training involves passing an x value into the neural network, checking how far the network's output deviates from the expected y value, and adjusting the neurons' weights and biases so that the output is more likely to be correct the next time.
Training runs this process on the full dataset multiple times, and each full run-through is known as an epoch. The number of epochs to run during training is a parameter we can set.
During each epoch, data is run through the network in multiple batches. Each batch, several pieces of data are passed into the network, producing output values. These outputs' correctness is measured in aggregate and the network's weights and biases are adjusted accordingly, once per batch. The batch size is also a parameter we can set.
The code in the following cell uses the x and y values from our training data to train the model. It runs for 1000 epochs, with 16 pieces of data in each batch. We also pass in some data to use for validation. As you will see when you run the cell, training can take a while to complete:
inputs: 1.d)  Grafica un histograma de numeros aleatorios con $n=10,50,100,1k,10k$
Para graficar histogramas usa plt.hist().

targets: import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

a = np.random.randint(1,10,10)
plt.hist(a)
inputs: %%bash
OUTDIR=babyweight_trained
rm -rf ${OUTDIR}
export PYTHONPATH=${PYTHONPATH}:${PWD}/babyweight
python3 -m trainer.task \
    --train_data_path=gs://${BUCKET}/babyweight/data/train*.csv \
    --eval_data_path=gs://${BUCKET}/babyweight/data/eval*.csv \
    --output_dir=${OUTDIR} \
    --batch_size=# TODO: Add batch size
    --num_epochs=# TODO: Add the number of epochs to train for
    --train_examples=# TODO: Add the number of examples to train each epoch for
    --eval_steps=# TODO: Add the number of evaluation batches to run
Given the above code, generate some markdown instructions for it.

targets: 
Train locally
After moving the code to a package, make sure it works as a standalone. Note, we incorporated the --train_examples flag so that we don't try to train on the entire dataset while we are developing our pipeline. Once we are sure that everything is working on a subset, we can change it so that we can train on all the data. Even for this subset, this takes about 3 minutes in which you won't see any output ...
Lab Task #3: Run trainer module package locally.
Fill in the missing code in the TODOs below so that we can run a very small training job over a single file with a small batch size, 1 epoch, 1 train example, and 1 eval step.
inputs: I am working on the file "01_openlibs/tensorflow/03_segmentfault/00_introduction.ipynb".
The first task is:
下面我们来剖析一下关键代码。TensorFlow的代码往往由两个部分组成：

A construction phase, that assembles a graph 
An execution phase that uses a session to execute ops in the graph.

Session是一个类，作用是把graph ops部署到Devices（CPUs/GPUs），并提供具体执行这些op的方法。
为什么要这么设计呢？考虑到Python运行性能较低，我们在执行numerical computing的时候，都会尽量使用非python语言编写的代码，比如使用NumPy这种预编译好的C代码来做矩阵运算。
在Python内部计算环境和外部计算环境（如NumPy）切换需要花费的时间称为overhead cost。对于一个简单运算，比如矩阵运算，从Python环境切换到Numpy，Numpy运算得到结果，再从Numpy切回Python，这个成本，比纯粹在Python内部做同类运算的成本要低很多。但是，一个复杂数值运算由多个基本运算组合而成，如果每个基本运算来一次这种环境切换，overhead cost就不可忽视了。为了减少来回的环境切换，TensorFlow的做法是，先在Python内定义好整个Graph，然后在Python外运行整个完整的Graph。因此TensorFlow的代码结构也就对应为两个阶段了。
Build Graph
Can you write Python code for it?

targets: 
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))