Muennighoff/xP3x-sample huggingface dataset:
inputs: (3e) Exercise: Average Number of Daily Requests per Hosts
Next, let's determine the average number of requests on a day-by-day basis. We'd like a list by increasing day of the month and the associated average number of requests per host for that day. Make sure you cache the resulting RDD avgDailyReqPerHost so that we can reuse it in the next exercise.
To compute the average number of requests per host, get the total number of request across all hosts and divide that by the number of unique hosts.
Since the log only covers a single month, you can skip checking for the month.
Also to keep it simple, when calculating the approximate average use the integer value - you do not need to upcast to float

targets: reqsPerDay = access_logs.map(lambda log: (log.date_time.day, 1)).reduceByKey(lambda a, b: a + b).sortByKey()
groupedByDay = reqsPerDay.join(dailyHosts)
avgDailyReqPerHost = groupedByDay.map(lambda (day, (r, h)): (day, r / h)).sortByKey().cache()
avgDailyReqPerHostList = avgDailyReqPerHost.take(30)

print 'Average number of daily requests per Hosts is %s' % avgDailyReqPerHostList

# TEST Average number of daily requests per hosts (3e)
Test.assertEquals(avgDailyReqPerHostList, [(1, 13), (3, 12), (4, 14), (5, 12), (6, 12), (7, 13), (8, 13), (9, 14), (10, 13), (11, 14), (12, 13), (13, 13), (14, 13), (15, 13), (16, 13), (17, 13), (18, 13), (19, 12), (20, 12), (21, 13), (22, 12)], 'incorrect avgDailyReqPerHostList')
Test.assertTrue(avgDailyReqPerHost.is_cached, 'incorrect avgDailyReqPerHost.is_cache')
inputs: %%bash

./foo < numbers.txt
Given the above code, generate some markdown instructions for it.

targets: 
Feed data via re-direction
inputs: # Where am I running?
!hostname

# How much memory is left on this compute node?
!free

# On GPU node, you can check the status of the GPU using `nvidia-smi` command:
!nvidia-smi
Given the above code, generate some markdown instructions for it.

targets: 
Standard UNIX programs can also be run from Jupyter by prepending it with "!".
They better be non-interactive program, not asking for input or output. For example:
inputs: # %load _solutions/case2_observations_processing26.py

len(unique_species)
Given the above code, generate some markdown instructions for it.

targets: 
<div class="alert alert-success">

**EXERCISE 21**

- Extract the unique combinations of genus and species in the `survey_data_plots` using `groupby`. Save the result as the variable `unique_species`.

<details><summary>Hints</summary>

- As `groupby` needs an aggregation function, this can be `first()` (the first of each group) as well.
- Do not forget to `reset_index` after the `groupby`.

</details>

</div>
inputs: # Get your Google Cloud project ID from gcloud
shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null

try:
    PROJECT_ID = shell_output[0]
except IndexError:
    PROJECT_ID = None

print("Project ID:", PROJECT_ID)
Given the above code, generate some markdown instructions for it.

targets: 
Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.


Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.


Make sure that billing is enabled for your project.


Enable the Vertex API.


Enable the Compute Engine API.


If you are running this notebook locally, you will need to install the Cloud SDK.


Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.


Note: Jupyter runs lines prefixed with ! or % as shell commands, and it interpolates Python variables with $ or {} into these commands.
Set your project ID
If you don't know your project ID, you may be able to get your project ID using gcloud.
inputs: As always, let's do imports and initialize a logger and a new bundle.  See Building a System for more details.

targets: %matplotlib inline

import phoebe

logger = phoebe.logger()

b = phoebe.default_binary()
inputs: 2) Using this generator to generate a 100nt sequence (as a string)

targets: d = DNA_generator()

---
inputs: I am working on the file "Code/notebooks/bootcamp_pandas_adv2-shape.ipynb".
The first task is:
Exercise. Use the dataframe ddts to plot Debt and Surplus across time for Argentina.  Hint: In the plot method, set subplots=True so that each variable is in a separate subplot.  
SOL
<!--
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
ddts['Argentina']['Surplus'].plot(ax=ax[0])
ax[0].legend(['Surplus'])
ddts['Argentina']['Debt'].plot(ax=ax[1])
ax[1].legend(['Debt'])

ax[0].axhline(0, color='k')
ax[0].set_ylim([-10, 10])
-->

The xs method
Another approach to extracting data that cuts across levels of the row or column index:  the xs method. This is recent addition to Pandas and an extremely good method once you get the hang of it. 
The basic syntax is 
python
df.xs(item, axis=X, level=N)
where N is the name or number of an index level and X describes if we are extracting from the index or column names. Setting X=0 (so axis=0) will slice up the data along the index, X=1 extracts data for column labels.
Here's how we could use xs to get the Argentina data without swapping the level of the column labels
Can you write Python code for it?

targets: 
# ddt.xs?

ddt.xs("Argentina", axis=1, level="Country")

ddt.xs("Argentina", axis=1, level="Country")["Debt"]
inputs: %%bash

# TODO 5

MODEL_NAME=title_model
VERSION_NAME=swivel

if [[ $(gcloud ai-platform models list --format='value(name)' | grep ^$MODEL_NAME$) ]]; then
    echo "$MODEL_NAME already exists"
else
    echo "Creating $MODEL_NAME"
    gcloud ai-platform models create --region=$REGION $MODEL_NAME
fi

if [[ $(gcloud ai-platform versions list --model $MODEL_NAME --format='value(name)' | grep ^$VERSION_NAME$) ]]; then
    echo "Deleting already existing $MODEL_NAME:$VERSION_NAME ... "
    echo yes | gcloud ai-platform versions delete --model=$MODEL_NAME $VERSION_NAME
    echo "Please run this cell again if you don't see a Creating message ... "
    sleep 2
fi

echo "Creating $MODEL_NAME:$VERSION_NAME"
gcloud ai-platform versions create \
  --model=$MODEL_NAME $VERSION_NAME \
  --framework=tensorflow \
  --python-version=3.7 \
  --runtime-version=2.1 \
  --origin=$EXPORT_PATH \
  --staging-bucket=gs://$BUCKET \
  --machine-type n1-standard-4 \
  --region=$REGION
Given the above code, generate some markdown instructions for it.

targets: 
Then we can deploy the model using the gcloud CLI as before:
inputs: !cat ch06/ex7.csv

import csv
f = open('ch06/ex7.csv')

reader = csv.reader(f)

for line in reader:
    print(line)

lines = list(csv.reader(open('ch06/ex7.csv')))
header, values = lines[0], lines[1:]
data_dict = {h: v for h, v in zip(header, zip(*values))}
data_dict

class my_dialect(csv.Dialect):
    lineterminator = '\n'
    delimiter = ';'
    quotechar = '"'
    quoting = csv.QUOTE_MINIMAL

with open('mydata.csv', 'w') as f:
    writer = csv.writer(f, dialect=my_dialect)
    writer.writerow(('one', 'two', 'three'))
    writer.writerow(('1', '2', '3'))
    writer.writerow(('4', '5', '6'))
    writer.writerow(('7', '8', '9'))

%cat mydata.csv
Given the above code, generate some markdown instructions for it.

targets: 
Manually working with delimited formats
Most forms of tabular data can be loaded from disk using functions like pan das.read_table. In some cases, however, some manual processing may be necessary. It’s not uncommon to receive a file with one or more malformed lines that trip up read_table. To illustrate the basic tools, consider a small CSV file:
inputs: After only 1 epoch, our model is able to acheive about 65% accuracy on testset(If not, try more times).
We can save our model by calling either save or using pickle.

targets: # using pickle
import pickle
smodel = pickle.dumps(model)
# using saving (recommended)
# We get the benefit being able to directly load/save from cloud storage(S3, HDFS)
prefix = "cifar10"
model.save(prefix)
inputs: # Instanciando
lista_eg = [6,10,'Paulo']
print('Os valores do "lista_eg" estão:', lista_eg)
print('O tipo do "lista_eg" está:', type(lista_eg))
print('\n')

# Chamando
print('O valor do segundo índice está:', lista_eg[1]) # Nota nas listas de Python o primeiro índice é 0 (não 1)
print('\n')

# Substiuindo/Mudando os valores 
lista_eg[1] = lista_eg[1]*4
print('O valor do segundo índice está:', lista_eg[1])
print('\n')

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

targets: 
Variáveis com vários valores
As listas são um tipo de variável com vários valores. 

Estes tem um conjunto das variávels em uma lista, você busca sobre dando o índice da variável voce quer
O índice é um inteiro
O valor é qualquer tipo de variável
As listas tem ordem
Os valores podem ter tipos das variáveis diferentes em uma lista
inputs: Creating the circuits
The function below creates a Loschmidt echo using a random circuit for $U$ on a given set of qubits for a given number of cycles. A pause can be optionally applied after $U$ and before $U^\dagger$.

targets: def create_loschmidt_echo_circuit(
    qubits: Sequence[cirq.GridQubit],
    cycles: int,
    twoq_gate: cirq.Gate = cirq.FSimGate(np.pi / 4, 0.0),
    pause: Optional[cirq.Duration] = None,
    seed: Optional[int] = None,
) -> cirq.Circuit:
    """Returns a Loschmidt echo circuit using a random unitary U.
    
    Args:
        qubits: Qubits to use.
        cycles: Depth of random rotations in the forward & reverse unitary.
        twoq_gate: Two-qubit gate to use.
        pause: Optional duration to pause for between U and U^\dagger.
        seed: Seed for circuit generation.
    """
    # Forward (U) operations.
    forward = random_rotations_between_grid_interaction_layers_circuit(
        qubits, 
        depth=cycles,
        two_qubit_op_factory=lambda a, b, _: twoq_gate.on(a, b),
        pattern=cirq.experiments.GRID_STAGGERED_PATTERN,
        single_qubit_gates=[cirq.PhasedXPowGate(phase_exponent=p, exponent=0.5)
                            for p in np.arange(-1.0, 1.0, 0.25)],
        seed=seed
    )

    # Optional pause.
    if pause is not None:
        wait = cirq.Moment(cirq.WaitGate(pause).on(q) for q in qubits)
    else:
        wait = []
    
    # Reverse (U^\dagger) operations.
    reverse = cirq.inverse(forward)

    # Measure all qubits.
    measure = cirq.measure(*qubits, key="z")

    return forward + wait + reverse + measure
inputs: %matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

first_500_sm = [float(problem_5(n)) for n in range(1, 501)]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_yscale('log')
ax.set_title('Smallest Multiple of the x First Numbers, up to 500\n Axes: log-normal\n')
ax.plot(first_500_sm, color='#348ABD', lw=1.4, alpha=0.6)
plt.show()
Given the above code, generate some markdown instructions for it.

targets: 
Addendum: Problem 5
Out of curiosity, what is the value for the first 500 integers?
inputs: I am working on the file "Getting Started With Badfish.ipynb".
The first task is:
The pattern plot below gives a nice understanding of the amount of data missing with different combinations of samples. Blue tiles indicate the presence of data whereas red tiles indicate missing data. 
We see that Ozone has the highest amount of missing data (27 samples) where-as 8 samples are missing a combination of Ozone and Temp data.
Note- The raw counts are given on the left.
Can you write Python code for it?

targets: 
mf.plot(kind='pattern', norm = False, threshold=0.0)

mf.pattern(columns = ['Ozone', 'Temp', 'Solar.R'], norm = False, threshold=0.0)
inputs: I am working on the file "02 Variable Strings and Numbers.ipynb".
The first task is:
Note
The first instruction of the previous cell is an exmaple of selective module import.
So far, just note that the syntax pattern of the selective import is:
from module import something[,something else comma separated]

See more about this in the notebook specifically devoted to this!
<a name='exercises_numbers'></a>Exercises
Arithmetic

Write a program that prints out the results of at least one calculation for each of the basic operations: addition, subtraction, multiplication, division, and exponents.

Order of Operations

Find a calculation whose result depends on the order of operations.
Print the result of this calculation using the standard order of operations.
Use parentheses to force a nonstandard order of operations. Print the result of this calculation.

Long Decimals

On paper, 0.1+0.2=0.3. But you have seen that in Python, 0.1+0.2=0.30000000000000004.
Find at least one other calculation that results in a long decimal like this.
Can you write Python code for it?

targets: 
# Ex 2.8 : Arithmetic
a = 6
b = 5
print("a + b = ", end='')
o = a+b
print(o)

# Ex 2.9 : Order of Operations
result = (3*4)+2
print('The result of the calculation of (3*4)+2', result, sep=' = ')

# Ex 2.10 : Long Decimals
print(3.125 / 0.2)
inputs: %%bigquery myDataframe
WITH MonthlyData AS
(
SELECT FORMAT_DATE("%B", taxi_trips.Pickup_DateTime) AS MonthName,
       FORMAT_DATE("%m", taxi_trips.Pickup_DateTime) AS MonthNumber,
       CASE WHEN taxi_trips.Payment_Type_Id = 1 THEN 'Credit'
            WHEN taxi_trips.Payment_Type_Id = 2 THEN 'Cash'
            WHEN taxi_trips.Payment_Type_Id = 3 THEN 'NoCharge'
            WHEN taxi_trips.Payment_Type_Id = 4 THEN 'Dispute'
         END AS PaymentDescription,
       SUM(taxi_trips.Total_Amount) AS Total_Amount
  FROM `taxi_dataset.taxi_trips` AS taxi_trips
 WHERE taxi_trips.Pickup_DateTime BETWEEN '2020-01-01' AND '2020-12-31' 
   AND Passenger_Count IS NOT NULL
   AND Payment_Type_Id IN (1,2,3,4)
 GROUP BY 1, 2, 3   
)
SELECT MonthName,
       CAST(Credit   AS INTEGER) AS Credit,
       CAST(Cash     AS INTEGER) AS Cash,
       CAST(NoCharge AS INTEGER) AS NoCharge,
       CAST(Dispute  AS INTEGER) AS Dispute
  FROM MonthlyData
 PIVOT(SUM(Total_Amount) FOR PaymentDescription IN ('Credit', 'Cash', 'NoCharge', 'Dispute'))
ORDER BY MonthNumber;

# Show the results
display(myDataframe)

# Loop through the dataframe
# You can now use BigQuery data just like any other datasource
for index, row in myDataframe.iterrows():
    print(("MonthName: {MonthName} | Credit: {Credit} | Cash {Cash}").format(MonthName=row['MonthName'].ljust(10),Credit=str(row['Credit']).ljust(10),Cash=str(row['Cash']).ljust(10)))
Given the above code, generate some markdown instructions for it.

targets: 
Place your SQL Results directly into a Dataframe
inputs: # Convert J into a set of feature vectors using F
L1 = em.extract_feature_vecs(J, feature_table=F,
                            attrs_after='label', show_progress=False)

# Predict on L 
predictions = dt.predict(table=L1, exclude_attrs=['_id', 'ltable_id', 'rtable_id', 'label'])

# Show the predictions
predictions[0:10]
Given the above code, generate some markdown instructions for it.

targets: 
Getting Predictions with the ML Matcher
Since we now have a trained decision tree, we can use our matcher to get predictions on the test set. Below, we will show four different ways to get the predictions with the predict command that will be useful in various contexts. 
Getting a List of Predictions
First up, we will demonstrate how to get just a list of predictions using the predict command. This is the default method of getting predictions. As shown below, the resulting variable, predictions, is just an array containing the predictions for each of the feature vectors in the test set.
inputs: I am working on the file "Day2/titanic_svm_advanced.ipynb".
The first task is:
Are we nessary perform better than the simpler model?
The real test is to submit the file to kaggle and let their hold out set decide.
I did improve my result by ~0.03 with the newly added in name features.
Can you write Python code for it?

targets: 
model.fit(X,y)
holdout_data = pd.read_csv('data/test_processed.csv')

# rescale age and fare as we did for training data.  This is critical
# Note that we can (and should) use the same scaler object we fit above to the training data
holdout_data[['Age', 'Fare']] = scaler.transform(holdout_data[['Age', 'Fare']])
holdout_data["PSA"] = holdout_data["Pclass"]*holdout_data["Female"]*holdout_data["Age"]
holdout_data["SP"] = holdout_data["SibSp"]+holdout_data["Parch"]

#use our new features.
#feature_cols=['Pclass','Age','SibSp','Parch','Fare','Female','Title_Dr','Title_Lady','Title_Master','Title_Miss','Title_Mr','Title_Mrs','Title_Rev','Title_Sir']
X_holdout=holdout_data[feature_cols]
X_holdout.head()

y_holdout=model.predict(X_holdout)
samplesubmit = pd.read_csv("data/titanic_submit_example.csv")
samplesubmit["Survived"]=np.int32(y_holdout)
samplesubmit.to_csv("data/titanic_submit_fancytitle.csv",index=False)
inputs: C = 1000
When C = 1000, the classifier starts to become very intolerant to misclassified data points and thus the decision boundary becomes less biased and has more variance (i.e. more dependent on the individual data points).

targets: # Create a SVC classifier using an RBF kernel
svm = SVC(kernel='rbf', random_state=0, gamma=.01, C=1000)
# Train the classifier
svm.fit(X_xor, y_xor)

# Visualize the decision boundaries
plot_decision_regions(X_xor, y_xor, classifier=svm)
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
inputs: 19.4. Name
Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1
Descriptive text for lateral tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...)

targets: # PROPERTY ID - DO NOT EDIT !  
DOC.set_id('cmip6.ocean.advection.lateral_tracers.name')  

# PROPERTY VALUE: 
# Set as follows: DOC.set_value("value")  
# TODO - please enter value(s)
inputs: 6.
Haz una lista de la compra e imprime los siguientes elementos:

Penúltimo elemento
Del segundo al cuarto elemento
Los tres últimos
Todos!

Por último, elimina el tercer elemento de la lista usando la sentencia del

targets: lista_compra = ['Leche', 'Chocolate', 'Arroz', 'Macarrones']

print("Penúltimo elemento: ", lista_compra[-2])
print("Del segundo al cuarto elemento: ", lista_compra[1:5])
print("Los tres últimos elementos: ", lista_compra[-3:])
print("Todos: ", lista_compra)

del lista_compra[2]
print(lista_compra)
inputs: I am working on the file "Calcul symbolique.ipynb".
The first task is:
On peut ajouter des contraintes sur les symboles lors de leur création :
Can you write Python code for it?

targets: 
x = Symbol('x', real=True)

x.is_imaginary

x = Symbol('x', positive=True)

x > 0
inputs: I am working on the file "Homework6_Soma.ipynb".
The first task is:
3) The first daily forecast is the forecast for today. For the place you decided on up above, how much of the moon is currently visible?
Can you write Python code for it?

targets: 
print(forecast['daily'].keys())

forecast['daily']['data']

print(type(forecast['daily']['data']))
print(forecast['daily']['data'][0])

first_daily_forecast = forecast['daily']['data']


for item in first_daily_forecast[:1]: 
    print("In the first daily forecast", item['moonPhase'], "of the moon is currently visible")
inputs: "2.2. Summary
Summarizing, the steps to design a Bayesian parametric regresion algorithm are the following:

Assume a parametric data model $p(s| {\bf x},{\bf w})$ and a prior distribution $p({\bf w})$.
Using the data model and the i.i.d. assumption, compute $p({\bf s}|{\bf w})$.
Applying the bayes rule, compute the posterior distribution $p({\bf w}|{\bf s})$.
Compute the MSE estimate of $s$ given ${\bf x}$.

3. Bayesian regression for a Gaussian model.
We will apply the above steps to derive a Bayesian regression algorithm for a Gaussian model.
3.1. Step 1: The Gaussian model.
Let as assume that the likelihood function is given by the Gaussian model described in Sec. 1.3.2.
$$
s~|~{\bf w} \sim {\cal N}\left({\bf z}^\top{\bf w}, \sigma_\varepsilon^2 {\bf I} \right)
$$
and that the prior is also Gaussian
$$
{\bf w} \sim {\cal N}\left({\bf 0},{\pmb \Sigma}_{p} \right)
$$
3.2. Step 2: Complete data likelihood
Using the i.i.d. assumption, 
$$
{\bf s}~|~{\bf w} \sim {\cal N}\left({\bf Z}{\bf w},\sigma_\varepsilon^2 {\bf I} \right)
$$
3.3. Step 3: Posterior weight distribution
The posterior distribution of the weights can be computed using the Bayes rule
$$p({\bf w}|{\bf s}) = \frac{p({\bf s}|{\bf w})~p({\bf w})}{p({\bf s})}$$
Since both $p({\bf s}|{\bf w})$ and $p({\bf w})$ follow a Gaussian distribution, we know also that the joint distribution and the posterior distribution of ${\bf w}$ given ${\bf s}$ are also Gaussian. Therefore,
$${\bf w}~|~{\bf s} \sim {\cal N}\left({\bf w}\text{MSE}, {\pmb\Sigma}{\bf w}\right)$$
After some algebra, it can be shown that mean and the covariance matrix of the distribution are:
$${\pmb\Sigma}{\bf w} = \left[\frac{1}{\sigma\varepsilon^2} {\bf Z}^{\top}{\bf Z} + {\pmb \Sigma}_p^{-1}\right]^{-1}$$
$${\bf w}\text{MSE} = {\sigma\varepsilon^{-2}} {\pmb\Sigma}_{\bf w} {\bf Z}^\top {\bf s}$$
Exercise 1:
Consider the dataset with one-dimensional inputs given by"
Please write code following the instructions in jupyter notebook style.

targets: 
# True data parameters
w_true = 3
std_n = 0.4

# Generate the whole dataset
n_max = 64
X_tr = 3 * np.random.random((n_max,1)) - 0.5
S_tr =  w_true * X_tr + std_n * np.random.randn(n_max,1)
inputs: I am working on the file "07_ivp.ipynb".
The first task is:
Similar to forward Euler is the backward Euler method which, as you may have guessed, evaluates the function $f$ at the updated time so that
$$
    U^{n+1} = U^n + \Delta t f(t_{n+1}, U^{n+1}).
$$
Schemes where the function $f$ is evaluated at the unknown time are called implicit methods.
Can you write Python code for it?

targets: 
t = numpy.linspace(0.0, 1.6e3, 100)
c_0 = 1.0
decay_constant = numpy.log(2.0) / 1600.0

fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(t, c_0 * numpy.exp(-decay_constant * t), label="True Solution")

# Plot Euler step
dt = 1e3
u_np = c_0 + dt * (-decay_constant * c_0 * numpy.exp(-decay_constant * dt))
axes.plot((0.0, dt), (c_0, u_np), 'k')
axes.plot((dt, dt), (u_np, c_0 * numpy.exp(-decay_constant * dt)), 'k--')
axes.plot((0.0, 0.0), (c_0, c_0 * numpy.exp(-decay_constant * dt)), 'k--')
axes.plot((0.0, dt), (c_0 * numpy.exp(-decay_constant * dt), c_0 * numpy.exp(-decay_constant * dt)), 'k--')
axes.text(400, u_np - 0.05, '$\Delta t$', fontsize=16)

axes.set_title("Radioactive Decay with $t_{1/2} = 1600$ years")
axes.set_xlabel('t (years)')
axes.set_ylabel('$c$')
axes.set_xlim(-1e2, 1.6e3)
axes.set_ylim((0.5,1.0))
plt.show()

c_0 = 1.0
decay_constant = numpy.log(2.0) / 1600.0
f = lambda t, u: -decay_constant * u

t_exact = numpy.linspace(0.0, 1.6e3, 100)
u_exact = c_0 * numpy.exp(-decay_constant * t_exact)

# Implement backwards Euler
t_backwards = numpy.linspace(0.0, 1.6e3, 10)
delta_t = t_backwards[1] - t_backwards[0]
u_backwards = numpy.empty(t_backwards.shape)
u_backwards[0] = c_0
for n in xrange(0, t_backwards.shape[0] - 1):
    u_backwards[n + 1] = u_backwards[n] / (1.0 + decay_constant * delta_t)

fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(t_backwards, u_backwards, 'or', label="Backwards Euler")
axes.plot(t_exact, u_exact, 'k--', label="True Solution")

axes.set_title("Backwards Euler")
axes.set_xlabel("t (years)")
axes.set_xlabel("$c(t)$")
axes.set_ylim((0.4,1.1))
axes.legend()
plt.show()
inputs: <div class="alert alert-warning">
<b>What has been the effect of excluding best matches that do not have an RBBH reverse match?</b>
</div>

Next, we can inspect the query and subject coverage of RBBH results, compared to the one-way forward BLAST matches by executing the cell below.

targets: # Plot 2D histograms of query coverage against subject coverage for the 
# one-way forward matches, and those retained after calculating RBBH
rbbh.plot_hist2d(data_fwd.query_coverage, data_fwd.subject_coverage,
                      "one-way query COV", "one-way subject COV", 
                      "one-way coverage comparison")
rbbh.plot_hist2d(data_rbbh.query_coverage_x, data_rbbh.subject_coverage_x,
                      "RBBH (fwd) query COV", "RBBH (fwd) subject COV", 
                      "RBBH_comparisons.ipynbH coverage comparison")
inputs: I am working on the file "Investigate Data.ipynb".
The first task is:
Here is the difference between the player getting the highest salary and the one participating the more winning games.
Can you write Python code for it?

targets: 
plot_correlation2(data=highest_salaries_players_with_score, x_var="score", y_var="salary", title='Correlation between Salary and Score')
inputs: "Comparing NFW, Einasto and Hernquist profiles $\rho(r) /\rho_m$"
Please write code following the instructions in jupyter notebook style.

targets: 
# Colossus density profiles
col_rho_nfw = col_nfw.density (r * cosmo.h () * 1.0e3) * (cosmo.h2 () * 1.0e9)

# NumCosmo density profiles
nc_rho_nfw  = np.array (nc_nfw.eval_density_array (cosmo, r, 1.0, 1.0, z))

# CCL density profiles
# CCL input: comoving distance 
ccl_rho_nfw = ccl_nfw.real (cosmo_ccl, r / a, Mvir, a, mdef) / a**3

# CT density profile

plt.figure()
fig, axs = plt.subplots (2, sharex=True, gridspec_kw={'hspace': 0}, figsize=(14,7))

axs[0].set_xscale ('log')
axs[0].set_yscale ('log')
axs[1].set_yscale ('log')
axs[1].set_xlabel(r'$r$[Mpc]')
axs[0].set_ylabel(r'$\rho (r) / \rho_m$')
axs[1].set_ylabel(r'$\rho_{\mathrm{i}} (r) / \rho_{\mathrm{nc}} - 1$')
axs[0].plot (r, col_rho_nfw, '-', label = 'NFW - Col')
axs[0].plot (r, nc_rho_nfw,  '-', label = 'NFW - NC')
axs[0].plot (r, ccl_rho_nfw, '-', label = 'NFW - CCL')
axs[0].plot (r, ct_rho_nfw,  '-', label = 'NFW - CT')

axs[1].plot (r, np.abs (col_rho_nfw / nc_rho_nfw  - 1.0), '-', label = "NFW - CMP - Col")
axs[1].plot (r, np.abs (ccl_rho_nfw / nc_rho_nfw - 1.0),  '-', label = "NFW - CMP - CCL")
axs[1].plot (r, np.abs (ct_rho_nfw / nc_rho_nfw - 1.0),   '-', label = "NFW - CMP - CT")

axs[0].legend(loc='best')
axs[1].legend(loc='best')
axs[1].grid()

plt.show ()
inputs: # create a new list of tokens by applying the metaphone method to all tokens from the words list
words2=list(map(metaphone,words))
term_labels=list(zip(words2,words))

print("Number of words in metaphone format: %i" % len(words2))
for i,val in enumerate(words2):
    print(str(i)+":\t "+str(val))

# calculate the triangle dis tance list as above
r=np.triu_indices(n=len(words2), k=1)
r

r2=np.apply_along_axis(d, 0, r)
r2

method_name='single'
Z=scipycluster.linkage(r2,method=method_name)

plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram - Method: '+method_name.title())
plt.xlabel('Term (in Metaphone/Original)')
plt.ylabel('Distance')
scipycluster.dendrogram(
        Z,
        leaf_rotation=90.,  # rotates the x axis labels
        leaf_font_size=16.,  # font size for the x axis labels
        labels=term_labels
    )
plt.show()

words2=list(map(metaphone,words))
term_labels=list(zip(words2,words))

print("Number of words in metaphone format: %i" % len(words2))
for i,val in enumerate(words2):
    print(str(i)+":\t "+str(val))
    
r=np.triu_indices(n=len(words2), k=1)
r

r2=np.apply_along_axis(d, 0, r)
r2

method_name='average'
Z=scipycluster.linkage(r2,method=method_name)

plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram - Method: '+method_name.title())
plt.xlabel('Term (in Metaphone/Original)')
plt.ylabel('Distance')
scipycluster.dendrogram(
        Z,
        leaf_rotation=90.,  # rotates the x axis labels
        leaf_font_size=16.,  # font size for the x axis labels
        labels=term_labels
    )
plt.show()

words2=list(map(soundex,words))
term_labels=list(zip(words2,words))

print("Number of words in soundex format: %i" % len(words2))
for i,val in enumerate(words2):
    print(str(i)+":\t "+str(val))
    
r=np.triu_indices(n=len(words2), k=1)
r

r2=np.apply_along_axis(d, 0, r)
r2

method_name='single'
Z=scipycluster.linkage(r2,method=method_name)

plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram - Method:...
Given the above code, generate some markdown instructions for it.

targets: 
Samples with Phonetic Preprocessing
The following examples follow the logic presented above. However, the make use of the metaphone and soundex methods provided by Jellyfish to convert the tokens to their phonetic equivalents before creating the distance matrix and visualizing the results.
inputs: "After specifying an experiment above, run the next block to get files for that experiment."
Please write code following the instructions in jupyter notebook style.

targets: 
mtools = reload(mtools)
files = mtools.get_files_for_experiment(experiment.value)
inputs: "Again, the prediction is shown as the color of the cross. You can see that the prediction for the new data point at the top left is not the same as the prediction when we used only one neighbor.
While this illustration is for a binary classification problem, this method can be applied to datasets with any number of classes. For more classes, we count how many neighbors belong to each class and again predict the most common class.
Analyzing Decision Boundary as k varies
For two-dimensional datasets, we can also illustrate the prediction for all possible test points in the xy-plane. We color the plane according to the class that would be assigned to a point in this region. This lets us view the decision boundary, which is the divide between where the algorithm assigns class 0 versus where it assigns class 1. The following code produces the visualizations of the decision boundaries for one, three, and nine neighbors."
Please write code following the instructions in jupyter notebook style.

targets: 
from matplotlib.colors import ListedColormap
cm2 = ListedColormap(['#0000aa', '#ff2020'])

def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None, alpha=1,
                      cm=cm2, linewidth=None, threshold=None, linestyle="solid"):
    # binary?
    if eps is None:
        eps = X.std() / 2.

    if ax is None:
        ax = plt.gca()

    x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
    y_min, y_max = X[:, 1].min() - eps, X[:, 1].max() + eps
    xx = np.linspace(x_min, x_max, 100)
    yy = np.linspace(y_min, y_max, 100)

    X1, X2 = np.meshgrid(xx, yy)
    X_grid = np.c_[X1.ravel(), X2.ravel()]
    try:
        decision_values = classifier.decision_function(X_grid)
        levels = [0] if threshold is None else [threshold]
        fill_levels = [decision_values.min()] + levels + [decision_values.max()]
    except AttributeError:
        # no decision_function
        decision_values = classifier.predict_proba(X_grid)[:, 1]
        levels = [.5] if threshold is None else [threshold]
        fill_levels = [0] + levels + [1]
    if fill:
        ax.contourf(X1, X2, decision_values.reshape(X1.shape),
                    levels=fill_levels, alpha=alpha, cmap=cm)
    else:
        ax.contour(X1, X2, decision_values.reshape(X1.shape), levels=levels,
                   colors="black", alpha=alpha, linewidths=linewidth,
                   linestyles=linestyle, zorder=5)

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    ax.set_xticks(())
    ax.set_yticks(())


fig, axes = plt.subplots(1, 3, figsize=(10, 3))

for n_neighbors, ax in zip([1, 3, 9], axes):
    # the fit method returns the object self, so we can instantiate
    # and fit in one line
    clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X, y)
    plot_2d_separator(clf, X, fill=True, eps=0.5, ax=ax, alpha=.4)
    discrete_scatter(X[:, 0], X[:, 1], y, ax=ax)
    ax.set_title("{} neighbor(s)".format(n_neighbors))
    ax.set_xlabel("feature 0")
    ax.set_ylabel("feature 1")
axes[0].legend(loc=3)
inputs: Creating and Running ODESimulator
You can create a Simulator with Model and World like

targets: with reaction_rules():
    A + B > C | 0.01  # equivalent to create_binding_reaction_rule
    C > A + B | 0.3   # equivalent to create_unbinding_reaction_rule

m = get_model()

sim = ode.ODESimulator(m, w)
sim.run(10.0)
inputs: I am working on the file "L5 - Decision Tree.ipynb".
The first task is:
And we use Sun_level as labels
Can you write Python code for it?

targets: 
y_train = train.Sun_level
y_test = test.Sun_level
inputs: I am working on the file "Crawling_Basics.ipynb".
The first task is:
or the stripped strings(unnecessary spaces are removed)
Can you write Python code for it?

targets: 
for string in soup.stripped_strings:
    print(repr(string))
inputs: I am working on the file "Huntsman Telephoto Array specifications.ipynb".
The first task is:
Each imaging unit shall deliver an instantaneous field of view of $2.6 \pm 0.1 \times 1.9 \pm 0.1$ degrees 

Exposure time
Individual exposure times of 5-30 minutes are anticipated (5-10 minutes for broadband observations, 30 minutes for narrowband).
Can you write Python code for it?

targets: 
exposure_times = ((5, 10, 30) * u.minute)
exposure_times
inputs: I am working on the file "Intro-Numerical-Computing-Python.ipynb".
The first task is:
In the first example we retrieved all the elements of x that are larger than 5 (read "x where x is greater than 5"). In the second example we retrieved those elements of x that did not equal six.   The third example is slightly more complicated. We combined the logical_or function with comparison and indexing.  This allowed us to return those elements of the array x that are either less than four or greater than six. Combining indexing and comparison is a powerful concept. See the numpy documentation on logical functions for more information.
Generating Regular Sequences
Creating sequences of numbers that are separated by a specified value or that follow a particular patterns turns out to be a common task in programming. Python and NumPy have functions to simplify this task.
Can you write Python code for it?

targets: 
arange(10)

# generate numbers from 3 to 12 (non-inclusive) stepping by 4
arange(3, 12, 4)  

arange(1,10,0.5)
inputs: I am working on the file "Cal3-PythonGraphes.ipynb".
The first task is:
Or, alternatively, we can request that matplotlib uses LaTeX to render the text elements in the figure:
Can you write Python code for it?

targets: 
matplotlib.rcParams.update({'font.size': 18, 'text.usetex': True})

fig, ax = plt.subplots()

ax.plot(x, x**2, label=r"$y = \alpha^2$")
ax.plot(x, x**3, label=r"$y = \alpha^3$")
ax.legend(loc=2) # upper left corner
ax.set_xlabel(r'$\alpha$')
ax.set_ylabel(r'$y$')
ax.set_title('title');
show()

# restore
matplotlib.rcParams.update({'font.size': 12, 'font.family': 'sans', 'text.usetex': False})
inputs: I am working on the file "2.1/tutorials/MESH.ipynb".
The first task is:
include_times
Can you write Python code for it?

targets: 
print b['include_times']
inputs: I am working on the file "DEEP LEARNING/NLP/LSTM RNN/Toxic multiclass prediction Glove + Bidirection LSTM.ipynb".
The first task is:
Standard keras preprocessing, to turn each comment into a list of word indexes of equal length (with truncation or padding as needed).
Can you write Python code for it?

targets: 
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(list(list_sentences_train))
list_tokenized_train = tokenizer.texts_to_sequences(list_sentences_train)
list_tokenized_test = tokenizer.texts_to_sequences(list_sentences_test)
X_t = pad_sequences(list_tokenized_train, maxlen=maxlen)
X_te = pad_sequences(list_tokenized_test, maxlen=maxlen)
inputs: # f, ax = plt.subplots(2, 2)

# for i in range(2):
#     for j in range(2):
#         plt.sca(ax[i,j])
#         plt.plot(np.random.rand(20))
#         plt.xlabel('x')
#         plt.ylabel('y')

# plt.tight_layout()

print (year[0,99])
Given the above code, generate some markdown instructions for it.

targets: 
In many cases, it is easier to use the subplots function, which creates a new Figure along with an array of Axes objects that can be indexed in a rational manner:
inputs: I am working on the file "HW01-Intro_to_Pandas/Intro to Pandas.ipynb".
The first task is:
We can use the drop method to remove rows or columns, which by default drops rows. We can be explicit by using the axis argument:
Can you write Python code for it?

targets: 
data_nomonth = data.drop('month', axis=1)
data_nomonth
inputs: "Dashboard Heading
This widget summarizes the topic used to track your meetups and the parameters used to filter the RSVP stream."
Please write code following the instructions in jupyter notebook style.

targets: 
%%html
<template is="urth-core-bind" channel="meetups">
    <style>
        .topics-desc {
            font-size: larger;
        }
        .topics-desc span {
            font-style: italic;
        }
    </style>
    <div class="topics-desc">
       Showing upcoming meetups for the <span>[[upcoming_label]]</span> topic. Meetup candidates are generated using the following topic filters: <span>[[cand_topics_label]]</span>
    </div>
</template>
inputs: %store -r averagediff_real

plt.xlabel('Day') 
plt.ylabel('Average number of tweets')
plt.step(range(1,len(averagediff)+1),averagediff, 'r', label="fake news")
plt.step(range(1,len(averagediff_real)+1),averagediff_real, 'g', label="real news")
plt.legend()
plt.title('Average diffusion for both types of news')
plt.show()
Given the above code, generate some markdown instructions for it.

targets: 
Plot average diffusion for both real and fake news on one graph
inputs: !pip install pulp

from pulp import LpMaximize, LpProblem, lpSum, LpVariable

prob = LpProblem("Melhor_Escalacao", LpMaximize)
y = LpVariable.dicts("Atl",df_rodada.index,0,1,cat='Binary')
prob += lpSum([z[i] * y[i] for i in y])
Given the above code, generate some markdown instructions for it.

targets: 
Primeiro, iniciamos o problema de otimização e definimos uma função objetivo.
inputs: Create site profile
This is about the simplest profile that we can create. Linear-elastic soil and rock.

targets: profile = pysra.site.Profile(
    [
        pysra.site.Layer(
            pysra.site.DarendeliSoilType(18.0, plas_index=0, ocr=1, stress_mean=100),
            10,
            400,
        ),
        pysra.site.Layer(
            pysra.site.DarendeliSoilType(18.0, plas_index=0, ocr=1, stress_mean=200),
            10,
            450,
        ),
        pysra.site.Layer(
            pysra.site.DarendeliSoilType(18.0, plas_index=0, ocr=1, stress_mean=400),
            30,
            600,
        ),
        pysra.site.Layer(pysra.site.SoilType("Rock", 24.0, None, 0.01), 0, 1200),
    ]
)
inputs: "Creating a new Benchmark object
To instantiate the Benchmark class, a recommender object of type RecoBasedOn is required (think: "What do I want to benchmark?"), like so:"
Please write code following the instructions in jupyter notebook style.

targets: 
benchmark = Benchmark(recommender)
inputs: # Weight vector:
w = [4, 8]   # Try different weights

# Create a rectangular grid.
x_min = -1
x_max = 1
h = (x_max - x_min) / 200
xgrid = np.arange(x_min, x_max, h)
xx0, xx1 = np.meshgrid(xgrid, xgrid)

# Compute the logistic map for the given weights, and plot
Z = logistic(w[0]*xx0 + w[1]*xx1)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx0, xx1, Z, cmap=plt.cm.copper)
ax.contour(xx0, xx1, Z, levels=[0.5], colors='b', linewidths=(3,))
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
ax.set_zlabel('P(1|x,w)')
plt.show()
Given the above code, generate some markdown instructions for it.

targets: 
It is straightforward to see that the logistic function has the following properties:

P1: Probabilistic output: $\quad 0 \le g(t) \le 1$
P2: Symmetry: $\quad g(-t) = 1-g(t)$
P3: Monotonicity: $\quad g'(t) = g(t)\cdot [1-g(t)] \ge 0$

Exercise 1: Verify properties P2 and P3.
Exercise 2: Implement a function to compute the logistic function, and use it to plot such function in the inverval $[-6,6]$.
2.2. Classifiers based on the logistic model.
The MAP classifier under a logistic model will have the form
$$P_{Y|{\bf X}}(1|{\bf x}, {\bf w}) = g({\bf w}^\intercal{\bf x}) \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0} \quad \frac{1}{2} $$
Therefore
$$
2 \quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0} \quad
1 + \exp(-{\bf w}^\intercal{\bf x}) $$
which is equivalent to
$${\bf w}^\intercal{\bf x} 
\quad\mathop{\gtrless}^{\hat{y}=1}_{\hat{y}=0}\quad 
0 $$
Thus, the classifiers based on the logistic model are given by linear decision boundaries passing through the origin, ${\bf x} = {\bf 0}$.
inputs: "Absolutely any Python installation will come with these. However, you still have to import them to access them in your program.
If you are so inclined, you can see the full Python default module index here: https://docs.python.org/3/py-modindex.html.
It's quite a bit! These are all available to you when using Python (don't even bother trying to memorize these; in looking over this list just now, I'm amazed at how many I didn't even know existed).
Once you've imported the module, you can access all its functions via the "dot-notation":"
Please write code following the instructions in jupyter notebook style.

targets: 
import random
random.randint(0, 1)
inputs: Branching
We need to store the paths and whether we have been there before, and if yes, then which route were we taking. A simple queue should suffice.
The approach we are going to use is that of breadth-first-search. In this approach, we identify all possible directions we can currently move in and put them in the queue. Then while the stack is not empty, we pop a move out, and repeat the directions it can take and so on until we reach the end-point, at which, we store the length of the path we took.
To store the length of the path, each move put on the stack must have an accompanying count of the steps it took to reach there. It is possible to apply heuristic by storing an index of paths sorted by the length and giving priority to pursuing paths with a shorter length first, or those that are nearer to the end-point.
One very important thing to note: we must not travel to the same point again - otherwise we'll keep chasing our own tails in recursive cycles (or an infinite while loop, take your pick). To prevent that, we have to maintain an index of points we have already traversed. We use a dictionary to hold this index, which stores the number of steps we took to traverse to this point. If there comes a move that reaches the same point in lesser number of steps, we know that it is a shorter route, and we continue traversing it. If the move has more number of steps to reach the same point, then it is not an optimum path, and do not need to continue along it.

targets: queue = []
points_traversed = {}
inputs: <h2>1. Un exemple jouet

targets: alpha = 4
size = 100
a = np.random.uniform(-1, alpha - 1, (size, 2))
b = np.random.uniform(-2, alpha - 2, (size, 2))
c = np.random.uniform(-3, alpha - 3, (size, 2))
d = np.random.uniform(0, alpha, (size, 2))
e = np.random.uniform(1, 1 + alpha, (size, 2))
f = np.random.uniform(2, 2 + alpha, (size, 2))
X = np.concatenate((a,b,c,d,e,f),axis=0)
pca = PCA(n_components=2)
plt.scatter(X[:,0],X[:,1])
pca.fit(X)
print(pca.explained_variance_ratio_)
inputs: %%time
X = vectorizer.transform( graphs )
print 'Instances: %d ; Features: %d with an avg of %d features per instance' % (X.shape[0], X.shape[1],  X.getnnz()/X.shape[0])
Given the above code, generate some markdown instructions for it.

targets: 
compute the vector encoding of each instance in a sparse data matrix
inputs: I am working on the file ".ipynb_checkpoints/Getting_Started-checkpoint.ipynb".
The first task is:
Not much information here. Let's print out information on the builds associated with the build executions:
Can you write Python code for it?

targets: 
print([(i, i.build) for i in rs.build_execs])
inputs: # ignore this, it is just technical code
# should come from a lib, consider it to appear magically 
# http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

cmap_print = ListedColormap(['#AA8888', '#004000', '#FFFFDD'])
cmap_bold = ListedColormap(['#AA4444', '#006000', '#AAAA00'])
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#FFFFDD'])
font_size=25

def meshGrid(x_data, y_data):
    h = 1  # step size in the mesh
    x_min, x_max = x_data.min() - 1, x_data.max() + 1
    y_min, y_max = y_data.min() - 1, y_data.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    return (xx,yy)
    
def plotPrediction(clf, x_data, y_data, x_label, y_label, colors, title="", mesh=True, fname=None):
    xx,yy = meshGrid(x_data, y_data)
    plt.figure(figsize=(20,10))

    if clf and mesh:
        Z = clf.predict(np.c_[yy.ravel(), xx.ravel()])
        # Put the result into a color plot
        Z = Z.reshape(xx.shape)
        plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
    
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    if fname:
        plt.scatter(x_data, y_data, c=colors, cmap=cmap_print, s=200, marker='o', edgecolors='k')
    else:
        plt.scatter(x_data, y_data, c=colors, cmap=cmap_bold, s=80, marker='o', edgecolors='k')
    plt.xlabel(x_label, fontsize=font_size)
    plt.ylabel(y_label, fontsize=font_size)
    plt.title(title, fontsize=font_size)
    if fname:
        plt.savefig(fname)

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y)

X_train.shape, y_train.shape, X_test.shape, y_test.shape

X_train_kmh_age = X_train[:, :2]
X_test_kmh_age = X_test[:, :2]
X_train_2_dim = X_train_kmh_age
X_test_2_dim = X_test_kmh_age

# 0: red
# 1: green
# 2: yellow

class ClassifierBase:
    def predict(self, X):
        return...
Given the above code, generate some markdown instructions for it.

targets: 
Second Step: Visualizing Prediction
inputs: "Calgary View
Notice that upLevelSymbolId for this view is equal to the symbolId of the Alberta view shown in the previous example. we can see that this is a child of the Canada Custom View."
Please write code following the instructions in jupyter notebook style.

targets: 
get_custom_views(url=auth.url, auth=auth.creds, name="Calgary")
inputs: Create structure matrices and across-feature distance matrix

targets: #%% Structure matrices and across-features distance matrix
C1 = ot.dist(xs)
C2 = ot.dist(xt)
M = ot.dist(ys, yt)
w1 = ot.unif(C1.shape[0])
w2 = ot.unif(C2.shape[0])
Got = ot.emd([], [], M)
inputs: I am working on the file "05_support_vector_machines.ipynb".
The first task is:
That's much better (we cut the error rate in two), but still not great at all for MNIST. If we want to use an SVM, we will have to use a kernel. Let's try an SVC with an RBF kernel (the default).
Warning: if you are using Scikit-Learn ≤ 0.19, the SVC class will use the One-vs-One (OvO) strategy by default, so you must explicitly set decision_function_shape="ovr" if you want to use the OvR strategy instead (OvR is the default since 0.19).
Can you write Python code for it?

targets: 
svm_clf = SVC(decision_function_shape="ovr")
svm_clf.fit(X_train_scaled[:10000], y_train[:10000])

y_pred = svm_clf.predict(X_train_scaled)
accuracy_score(y_train, y_pred)
inputs: I am working on the file "DL0110EN/4.3.2mist1layer.ipynb".
The first task is:
<a id="ref5"></a>
<h2 align=center>Analyze Results</h2>

Compare the training loss for each activation:
Can you write Python code for it?

targets: 
plt.plot(training_results_tanch['training_loss'],label='tanh')
plt.plot(training_results['training_loss'],label='sim')
plt.plot(training_results_relu['training_loss'],label='relu')
plt.ylabel('loss')
plt.title('training loss iterations')
plt.legend()