markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Time to evaluate the GP likelihood: | %%time
ln_gp_likelihood(t, y, sigma) | Sessions/Session13/Day2/02-Fast-GPs.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
george
Let's time how long it takes to do the same operation using the george package (pip install george).
The kernel we'll use is
python
kernel = amp ** 2 * george.kernels.ExpSquaredKernel(tau ** 2)
where amp = 1 and tau = 1 in this case.
To instantiate a GP using george, simply run
python
gp = george.GP(kernel)
The ... | import george
%%time
kernel = george.kernels.ExpSquaredKernel(1.0)
gp = george.GP(kernel)
gp.compute(t, sigma)
%%time
print(gp.log_likelihood(y)) | Sessions/Session13/Day2/02-Fast-GPs.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
george also offers a fancy GP solver called the HODLR solver, which makes some approximations that dramatically speed up the matrix algebra. Let's instantiate the GP object again by passing the keyword solver=george.HODLRSolver and re-compute the log likelihood. How long did that take? Did we get the same value for the... | %%time
gp = george.GP(kernel, solver=george.HODLRSolver)
gp.compute(t, sigma)
%%time
gp.log_likelihood(y) | Sessions/Session13/Day2/02-Fast-GPs.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
celerite
The george package is super useful for GP modeling, and I recommend you read over the docs and examples. It implements several different kernels that come in handy in different situations, and it has support for multi-dimensional GPs. But if all you care about are GPs in one dimension (in this case, we're only... | import celerite
from celerite import terms
%%time
kernel = terms.Matern32Term(np.log(1), np.log(1))
gp = celerite.GP(kernel)
gp.compute(t, sigma)
%%time
gp.log_likelihood(y) | Sessions/Session13/Day2/02-Fast-GPs.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
<div style="background-color: #D6EAF8; border-left: 15px solid #2E86C1;">
<h1 style="line-height:2.5em; margin-left:1em;">Exercise (the one and only)</h1>
</div>
Let's use what we've learned about GPs in a real application: fitting an exoplanet transit model in the presence of correlated noise.
Here is a (fictitio... | import matplotlib.pyplot as plt
t, y, yerr = np.loadtxt("data/sample_transit.txt", unpack=True)
plt.errorbar(t, y, yerr=yerr, fmt=".k", capsize=0)
plt.xlabel("time")
plt.ylabel("relative flux"); | Sessions/Session13/Day2/02-Fast-GPs.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Notes
If a file with the same name doesn't already exist, then this creates a new database otherwise it connects to the existing database contained in the file. You can also use ':memory:' to create an "in-memory" database that has no file, but then you can't connect to that from another process.
We'll have to close th... | # we can use Python triple quoted strings to span multiple lines, but use single quotes, since SQL only uses double quotes
# first create a materials table
cur.execute('''CREATE TABLE materials (
material_id TEXT PRIMARY KEY,
long_name TEXT UNIQUE NOT NULL,
alpha REAL NOT NULL,
beta REAL NOT NULL,
... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
FOREIGN KEY
A foreign key constraint creates a relationship between two tables. The FOREIGN KEY is implied when the REFERENCES column constraint is applied. In the experiments table above, the column constraint on material_id is the same as adding this table constriant:
FOREIGN KEY (material_id) REFERENCES materials (m... | # add a EVA as a material
cur.execute('INSERT INTO materials VALUES ("EVA", "ethylene vinyl acetate", 0.123, 4.56, "polymer")')
conn.commit() # you must commit for it to become permanent
cur.rowcount # tells you how many rows written, sometimes, it's quirky | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Placeholders
You can use placeholders to loop over insert statements to add multiple records.
WARNING: Never use string formatters to in lieu of placeholders or you may be subject to a SQL injection attack.
SQLite uses ? but other relational databases may use %s or another placeholder.
Also, in sqlite3 executemany is... | # add some more fake materials
fake_materials = [
('PMMC', 'poly methyl methacrylate', 0.789, 10.11, 'polymer'),
('KBr', 'potassium bromide', 1.213, 14.15, 'crystal')
]
for mat in fake_materials:
# must have same number of place holders as values
cur.execute('INSERT INTO materials VALUES (?, ?, ?, ?, ?)... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
DELETE and UPDATE
Oops I made a mistake. How do I fix it? The opposite of INSERT is DELETE. But don't throw the baby out with the bathwater, you can also [UPDATE] a record. Other relational databases use the same SQL syntax to manipulate data. | cur.execute('DELETE FROM materials WHERE material_id = "SiO2"')
cur.execute('UPDATE materials SET alpha=1.23E-4, beta=8.910E+11 WHERE material_id = "CaF2"')
conn.commit() | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Queries
The way you select data is by executing queries. The language is the same for all relational databases. The star * means select all columns, or you can give the columns explicitly. | cur.execute('SELECT * FROM materials')
cur.fetchall() # fetch all the results of the query | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Conditions
You can limit a query using WHERE and LIMIT. You can combine WHERE with a conditional expression, IN to check a set, or LIKE to compare with strings. Use AND and OR to combine conditions.
Python DB-API Cursor Methods
The Python DB-API cursor can be used as an iterator or you can call it's fetch methods. | # limit the query using WHERE and LIMIT
cur.execute('SELECT material_id, long_name FROM materials WHERE alpha < 1 LIMIT 2')
for c in cur: print('{} is {}'.format(*c)) # user the cursor as an iterator
materials_list = ("EVA", "PMMC")
cur.execute('SELECT alpha, beta FROM materials WHERE material_id IN (?, ?)', material... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Aggregates
Your query can aggregate results like AVG, SUM, COUNT, MAX, MIN, etc. | cur.execute('SELECT COUNT(*) FROM materials')
print(cur.fetchone()) | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
GROUP BY
You can group queries by a column or a condition such as an expression, IN, or LIKE, if your selection is an aggregate. | cur.execute('SELECT material_type, COUNT(*), AVG(alpha), MAX(beta) FROM materials GROUP BY material_type')
cur.fetchmany(2) # use fetchmany() with size parameter, just for fun | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
More Practice
Add a fictitious experiment schedule and doctor up some data! | # use defaults, let primary key auto-increment, just supply material ID
cur.execute('INSERT INTO experiments (material_id) VALUES ("EVA")') # use defaults,
conn.commit()
# set up a test matrix for EVA
temp = range(300, 400, 25)
irrad = range(400, 800, 100)
try:
for T in temp:
for E in irrad:
... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
ORDER BY
Does what it says; order the query results by a column. Default is ascending, but use ASC or DESC to change the order. | # Python's SQLite let's you use either '==' or '=', but I think SQL only allows '=', okay?
pd.read_sql('SELECT * FROM experiments WHERE irradiance = 700 ORDER BY temperature', conn, index_col='experiment_id')
# descending order
pd.read_sql('SELECT * FROM experiments WHERE temperature = 375 ORDER BY irradiance DESC', c... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Dr. Data | # Dr. Data
start_time, end_time = '2018-02-21T17:00-0800', '2018-02-21T18:30-0800'
timestamps = pd.DatetimeIndex(start=start_time, end=end_time, freq='T')
# use http://poquitopicante.blogspot.com/2016/11/panda-pop.html to help you recall what offset alias to use
size = len(timestamps)
data = {
'temperature': np.ran... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
JOIN
The foreign keys relate tables, but how do we use this relation? By joining the tables. | # add the results for experiment 17: T=375[K], E=700[W/m^2]
experiment_id, temperature, irradiance = list(cur.execute(
'SELECT experiment_id, temperature, irradiance FROM experiments WHERE (temperature = 375 AND irradiance = 700)'
))[0]
start_time, end_time = '2018-02-28T17:00-0800', '2018-02-28T18:30-0800'
timesta... | code_examples/SQL/SQL_Tutorial-0.ipynb | thehackerwithin/berkeley | bsd-3-clause |
Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using S, T, and Y Phosphorylation.
Included is N Phosphorylation however no benchmarks are available, yet.
Training data is from phospho.elm and benchmarks are from dbptm. | par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
benchmarks = ["Data/Benchmarks/phos_CDK1.csv", "Data/Benchmarks/phos_CK2.csv", "Data/Benchmarks/phos_MAPK1.csv", "Data/Benchmarks/phos_PKA.csv", "Data/Benchmarks/phos_PKC.csv"]
for j in benchmarks:
for i in par:
print("y", i, " ... | old/Phosphorylation Sequence Tests -MLP -dbptm+ELM -EnzymeBenchmarks-VectorAvr..ipynb | vzg100/Post-Translational-Modification-Prediction | mit |
Y Phosphorylation | par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
benchmarks = ["Data/Benchmarks/phos_CDK1.csv", "Data/Benchmarks/phos_CK2.csv", "Data/Benchmarks/phos_MAPK1.csv", "Data/Benchmarks/phos_PKA.csv", "Data/Benchmarks/phos_PKC.csv"]
for j in benchmarks:
for i in par:
try:
... | old/Phosphorylation Sequence Tests -MLP -dbptm+ELM -EnzymeBenchmarks-VectorAvr..ipynb | vzg100/Post-Translational-Modification-Prediction | mit |
T Phosphorylation | par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
benchmarks = ["Data/Benchmarks/phos_CDK1.csv", "Data/Benchmarks/phos_CK2.csv", "Data/Benchmarks/phos_MAPK1.csv", "Data/Benchmarks/phos_PKA.csv", "Data/Benchmarks/phos_PKC.csv"]
for j in benchmarks:
for i in par:
print("y", i, " ... | old/Phosphorylation Sequence Tests -MLP -dbptm+ELM -EnzymeBenchmarks-VectorAvr..ipynb | vzg100/Post-Translational-Modification-Prediction | mit |
This is a very simple dataset. There is only one input value for each record and then there is the output value. Our goal is to determine the output value or dependent variable, shown on the y-axis, from the input or independent variable, shown on the x-axis.
Our approach should scale to handle multiple input, or indep... | intercept_x = np.hstack((np.ones((n,1)), x))
intercept_x | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
Numpy contains the linalg module with many common functions for performing linear algebra. Using this module finding a solution is quite simple. | np.linalg.lstsq(intercept_x,y) | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
The values returned are:
The least-squares solution
The sum of squared residuals
The rank of the independent variables
The singular values of the independent variables
Exercise
Calculate the predictions our model would make
Calculate the sum of squared residuals from our predictions. Does this match the value return... | coeff, residuals, rank, sing_vals = np.linalg.lstsq(intercept_x,y)
intercept_x.shape, coeff.T.shape
np.sum(intercept_x * coeff.T, axis=1)
predictions = np.sum(intercept_x * coeff.T, axis=1)
plt.plot(x, y, 'bo')
plt.plot(x, predictions, 'ko')
plt.show()
predictions.shape
np.sum((predictions.reshape((20,1)) - y) **... | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
Least squares refers to the cost function for this algorithm. The objective is to minimize the residual sum of squares. The difference between the actual and predicted values is calculated, it is squared and then summed over all records. The function is as follows:
$$RSS(\beta) = \sum_{i=1}^{N}(y_i - x_i^T\beta)^2$$
Ma... | our_coeff = np.dot(np.dot(np.linalg.inv(np.dot(intercept_x.T, intercept_x)), intercept_x.T), y)
print(coeff, '\n', our_coeff)
our_predictions = np.dot(intercept_x, our_coeff)
predictions, our_predictions
plt.plot(x, y, 'ko', label='True values')
plt.plot(x, our_predictions, 'ro', label='Predictions')
plt.legend(num... | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
Exercise
Plot the residuals. The x axis will be the independent variable (x) and the y axis the residual between our prediction and the true value.
Plot the predictions generated for our model over the entire range of 0-1. One approach is to use the np.linspace method to create equally spaced values over a specified r... | plt.plot(x, y - our_predictions, 'ko')
plt.show()
plt.plot(x, y, 'ko', label='True values')
all_x = np.linspace(0, 1, 1000).reshape((1000,1))
intercept_all_x = np.hstack((np.ones((1000,1)), all_x))
print(intercept_all_x.shape, our_coeff.shape)
#all_x_predictions = np.dot(intercept_all_x, our_coeff)
all_x_prediction... | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
Types of independent variable
The independent variables can be many different types.
Quantitative inputs
Categorical inputs coded using dummy values
Interactions between multiple inputs
Tranformations of other inputs, e.g. logs, raised to different powers, etc.
It is important to note that a linear model is only line... | x_expanded = np.hstack((x**i for i in range(1,20)))
b, residuals, rank, s = np.linalg.lstsq(x_expanded, y)
print(b)
plt.plot(x, y, 'ko', label='True values')
plt.plot(x, np.dot(x_expanded, b), 'ro', label='Predictions')
plt.legend(numpoints=1, loc=4)
plt.show() | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
There is a tradeoff with model complexity. As we add more complexity to our model we can fit our training data increasingly well but eventually will lose our ability to generalize to new data.
Very simple models underfit the data and have high bias.
Very complex models overfit the data and have high variance.
The goal ... | n = 20
p = 12
training = []
val = []
for i in range(1, p):
np.random.seed(0)
x = np.random.random((n,1))
y = 5 + 6 * x ** 2 + np.random.normal(0,0.5, size=(n,1))
x = np.hstack((x**j for j in np.arange(i)))
our_coeff = np.dot(
np.dot(
np.linalg.inv(
... | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
Gradient descent
One limitation of our current implementation is that it is resource intensive. For very large datasets an alternative is needed. Gradient descent is often preferred, and particularly stochastic gradient descent for very large datasets.
Gradient descent is an iterative process, repetitively calculating ... | np.random.seed(0)
n = 200
x = np.random.random((n,1))
y = 5 + 6 * x ** 2 + np.random.normal(0,0.5, size=(n,1))
intercept_x = np.hstack((np.ones((n,1)), x))
coeff, residuals, rank, sing_vals = np.linalg.lstsq(intercept_x,y)
print('lstsq', coeff)
def gradient_descent(x, y, rounds = 1000, alpha=0.01):
theta = np.ze... | Wk08/Wk08_Numpy_model_package_survey_inclass_exercises.ipynb | briennakh/BIOF509 | mit |
The Game of Ur problem
In the Royal Game of Ur, players advance tokens along a track with 14 spaces. To determine how many spaces to advance, a player rolls 4 dice with 4 sides. Two corners on each die are marked; the other two are not. The total number of marked corners -- which is 0, 1, 2, 3, or 4 -- is the number... | die = Pmf([0, 1]) | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
And here's the outcome of a single roll. | roll = sum([die]*4) | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
I'll start with a simulation, which helps in two ways: it makes modeling assumptions explicit and it provides an estimate of the answer.
The following function simulates playing the game over and over; after every roll, it yields the number of rolls and the total so far. When it gets past the 14th space, it starts ove... | def roll_until(iters):
"""Generates observations of the game.
iters: number of observations
yields: number of rolls, total
"""
for i in range(iters):
total = 0
for n in range(1, 1000):
total += roll.Random()
if total > 14:
break
... | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Now I'll the simulation many times and, every time the token is observed on space 13, record the number of rolls it took to get there. | pmf_sim = Pmf()
for n, k in roll_until(1000000):
if k == 13:
pmf_sim[n] += 1 | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Here's the distribution of the number of rolls: | pmf_sim.Normalize()
pmf_sim.Print()
thinkplot.Hist(pmf_sim, label='Simulation')
thinkplot.decorate(xlabel='Number of rolls to get to space 13',
ylabel='PMF') | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
Bayes
Now let's think about a Bayesian solution. It is straight forward to compute the likelihood function, which is the probability of being on space 13 after a hypothetical n rolls.
pmf_n is the distribution of spaces after n rolls.
pmf_13 is the probability of being on space 13 after n rolls. | pmf_13 = Pmf()
for n in range(4, 15):
pmf_n = sum([roll]*n)
pmf_13[n] = pmf_n[13]
pmf_13.Print()
pmf_13.Total() | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
The total probability of the data is very close to 1/2, but it's not obvious (to me) why.
Nevertheless, pmf_13 is the probability of the data for each hypothetical values of n, so it is the likelihood function.
The prior
Now we need to think about a prior distribution on the number of rolls. This is not easy to reason... | posterior = pmf_13.Copy()
posterior.Normalize()
posterior.Print() | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
That sure looks similar to what we got by simulation. Let's compare them. | thinkplot.Hist(pmf_sim, label='Simulation')
thinkplot.Pmf(posterior, color='orange', label='Normalized likelihoods')
thinkplot.decorate(xlabel='Number of rolls (n)',
ylabel='PMF') | examples/game_of_ur_soln.ipynb | AllenDowney/ThinkBayes2 | mit |
On ouvre la connexion au cluster et au blob | #%blob_close
cl, bs = %hd_open
cl,bs | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
On upload les fichiers qui contient tous les ratings des users. | %blob_up data/ratings_mean.csv hdblobstorage/imdd/ratings_mean.csv | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
On vérifie que tous les fichiers sont présents dans le blob | #List files in blob storage
df=%blob_ls hdblobstorage/imdd/
df | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
On code l'algorithme en PIG. La difficulté est que PIG gère très mal l'imbrication de FOREACH, absolument nécessaire à l'algorithme. Notre solution s'est portée sur la mise à plat totale des données. D'où le FLATTEN puis nous avons effectué un JOIN pour la deuxième boucle. Puis nous avons appliqué les règles définies p... | %%PIG_azure dimsum.pig
-- Macro de calcul des normes par colonne (movieID)
DEFINE computeMatrixNorms(cData,sqrt_gamma) RETURNS Matrix_Norms {
cData_grp = GROUP $cData BY MovieID;
-- On calcule la norme et le gamma sur la norme
$Matrix_Norms = FOREACH cData_grp {
tmp_out = FOREACH $cData GENERATE Ra... | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Dans la partie de code suivante, nous supprimons les fichiers générés par l'algorithme précédent pour pouvoir les regénérer une deuxième fois. | cl.delete_blob(bs, "hdblobstorage", 'imdd/dom/matrix_all.txt')
cl.delete_blob(bs, "hdblobstorage", 'imdd/dom/similarities.txt')
df = %blob_ls hdblobstorage/imdd/dom/matrix_all.txt/
df
for name in df["name"]:
cl.delete_blob(bs, "hdblobstorage", name)
df = %blob_ls hdblobstorage/imdd/dom/similarities.txt/
df
for name... | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Upload du script dimsum.pig et lancement de son exécution : | jid = %hd_pig_submit dimsum.pig
jid
st = %hd_job_status jid["id"]
st["id"],st["percentComplete"],st["completed"],st["status"]["jobComplete"],st["status"]["state"]
df=%blob_ls hdblobstorage/imdd/
list(df["name"]) | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Test
L'algorithme DimSum ayant été bien exécuté , nous allons maintenant exploiter notre matrice de similarités à l'aide d'un autre script PIG qui se base sur le fichier de similarités généré par le script PIG vu auparavant.
A partir d'un id d'un film, qui existe dans notre base, nous nous attendrons à récupérer les id... | %%PIG_azure load_results.pig
cData = LOAD '$CONTAINER/$PSEUDO/dom/similarities.txt'
using PigStorage (',')
AS (MovieID1:int, MovieID2:int, sim:double) ;
filtered = FILTER cData BY MovieID1 == $MvID ;
ordered = ORDER filtered BY sim DESC;
ordered_limit = LIMIT ordered $size;
movies = FOREACH ordered_... | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Nous supprimons d'abord le fichier généré par la dernière exécution, ensuite nous lançons le script PIG afin de récupérer les ids des films similaires. Pour cet exemple, nous souhaitons récupérer les 20 films les plus proches à celui dont l'id est 1610. | if cl.exists(bs, cl.account_name, "$PSEUDO/imdd/dom/recom.txt"):
r = cl.delete_folder (bs, cl.account_name, "$PSEUDO/imdd/dom/recom.txt")
jid = cl.pig_submit(bs, blobstorage, "load_results.pig",params={"MvID":'1610',"size":"20"})
jid
st = %hd_job_status jid["id"]
(st["id"],st["percentComplete"],st["completed"],
st... | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Nous récupérons ensuite le fichier généré recom.txt, contenant les ids : | if os.path.exists("recom.txt"):os.remove("recom.txt")
%blob_downmerge /imdd/dom/recom.txt recom.txt | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Et nous affichons enfin les résultats : | with open('recom.txt', 'r') as f:
ids = f.read()
print(ids) | DIMSUM_FINAL_MACHRAOUI_DUONGPRUNIER.ipynb | dduong1/DIMSUM-Algorithm | gpl-3.0 |
Observations
Observations can be thought of as the probability of being in any given state at each time step. For this demonstration, observations are randomly initialized. In a real case, these observations would be the output of a neural network | observations = np.random.random((1, 90, 2)) * 4 - 2
plot(observations[0,:,:])
grid()
observations_variable = tf.Variable(observations)
posterior_graph, _, _ = hmm_tf.forward_backward(tf.sigmoid(observations_variable))
# build error function
sum_error_squared = tf.reduce_sum(tf.square(truth - posterior_graph))
# ca... | notebooks/gradient_descent_example.ipynb | dwiel/tensorflow_hmm | apache-2.0 |
Posterior vs Truth
The posterior is the probability assigned by the hmm of being in each state at each time step.
This is a plot if the posterior output compared to the truth. | posterior = session.run(posterior_graph)
print 'sum error squared: %.03f' % sum((truth[:,1] - posterior[:,1])**2)
plot(posterior[0,:,1], label='posterior')
plot(truth[0,:,1], label='truth')
grid()
legend() | notebooks/gradient_descent_example.ipynb | dwiel/tensorflow_hmm | apache-2.0 |
Gradients
This plot shows the gradients which are flowing back to the input of the hmm. | gradients = session.run(gradients_graph)[0]
def plot_gradients(gradients):
gradients = gradients[0]
# whiten gradients
gradients = gradients / np.std(gradients)
plot(-gradients[:,1], label='gradients')
plot(truth[0,:,1], label='truth')
# plot(sigmoid(observations[0,:,1]), label='observations'... | notebooks/gradient_descent_example.ipynb | dwiel/tensorflow_hmm | apache-2.0 |
Long Description
From version 0.4.0, py2cytoscape has wrapper modules for cyREST RESTful API. This means you can access Cytoscape features in more Pythonic way instead of calling raw REST API via HTTP.
Features
Pandas for basic data exchange
Since pandas is a standard library for data mangling/analysis in Python, th... | # HTTP Client for Python
import requests
# Standard JSON library
import json
# Basic Setup
PORT_NUMBER = 1234
BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/'
# Header for posting data to the server as JSON
HEADERS = {'Content-Type': 'application/json'}
# Define dictionary of empty network
empty_network = {
... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
With py2cytoscape | network = cy.network.create(name='My Network', collection='My network collection')
print('New network created with py2cytoscape. Its SUID is ' + str(network.get_id())) | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Status
As of 6/4/2015, this is still in alpha status and feature requests are always welcome. If youi have questions or feature requests, please send them to our Google Groups:
https://groups.google.com/forum/#!forum/cytoscape-discuss
Quick Tour of py2cytoscape Features
Create a client object to connect to Cytosca... | # Create an instance of cyREST client. Default IP is 'localhost', and port number is 1234.
# cy = CyRestClient() - This default constructor creates connection to http://localhost:1234/v1
cy = CyRestClient(ip='127.0.0.1', port=1234)
# Cleanup: Delete all existing networks and tables in current Cytoscape session
cy.ses... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Creating empty networks | # Empty network
empty1 = cy.network.create()
# With name
empty2 = cy.network.create(name='Created in Jupyter Notebook')
# With name and collection name
empty3 = cy.network.create(name='Also created in Jupyter', collection='New network collection') | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Load networks from files, URLs or web services | # Load a single local file
net_from_local2 = cy.network.create_from('../tests/data/galFiltered.json')
net_from_local1 = cy.network.create_from('sample_yeast_network.xgmml', collection='My Collection')
net_from_local2 = cy.network.create_from('../tests/data/galFiltered.gml', collection='My Collection')
# Load from mult... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Create networks from various types of data
Currently, py2cytoscape accepts the following data as input:
Cytoscape.js
NetworkX
Pandas DataFrame
igraph (TBD)
Numpy adjacency matrix (binary or weighted) (TBD)
GraphX (TBD) | # Cytoscape.js JSON
n1 = cy.network.create(data=cyjs.get_empty_network(), name='Created from Cytoscape.js JSON')
# Pandas DataFrame
# Example 1: From a simple text table
df_from_sif = pd.read_csv('../tests/data/galFiltered.sif', names=['source', 'interaction', 'target'], sep=' ')
df_from_sif.head()
# By default, it ... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Get Network from Cytoscape
You can get network data in the following forms:
Cytoscape.js
NetworkX
DataFrame | # As Cytoscape.js (dict)
yeast1_json = yeast1.to_json()
# print(json.dumps(yeast1_json, indent=4))
# As NetworkX graph object
sf100 = scale_free100.to_networkx()
num_nodes = sf100.number_of_nodes()
num_edges = sf100.number_of_edges()
print('Number of Nodes: ' + str(num_nodes))
print('Number of Edges: ' + str(num_ed... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Working with CyNetwork API
CyNetwork class is a simple wrapper for network-related cyREST raw REST API. It does not hold the actual network data. It's a reference to a network in current Cytoscape session. With CyNetwork API, you can access Cytoscape data objects in more Pythonista-friendly way. | network_suid = yeast1.get_id()
print('This object references to Cytoscape network with SUID ' + str(network_suid) + '\n')
print('And its name is: ' + str(yeast1.get_network_value(column='name')) + '\n')
nodes = yeast1.get_nodes()
edges = yeast1.get_edges()
print('* This network has ' + str(len(nodes)) + ' nodes and '... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Get references from existing networks
And of course, you can grab references to existing Cytoscape networks: | # Create a new CyNetwork object from existing network
network_ref1 = cy.network.create(suid=yeast1.get_id())
# And they are considered as same objects.
print(network_ref1 == yeast1)
print(network_ref1.get_network_value(column='name')) | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Tables as DataFrame
Cytoscape has two main data types: Network and Table. Network is the graph topology, and Tables are properties for those graphs. For simplicity, this library has access to three basic table objects:
Node Table
Edge Table
Network Table
For 99% of your use cases, you can use these three to store p... | # Get table from Cytoscape
node_table = scale_free100.get_node_table()
edge_table = scale_free100.get_edge_table()
network_table = scale_free100.get_network_table()
node_table.head()
network_table.transpose().head()
names = scale_free100.get_node_column('Degree')
print(names.head())
# Node Column information. "nam... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Edit Network Topology
Adding and deleteing nodes/edges | # Add new nodes: Simply send the list of node names. NAMES SHOULD BE UNIQUE!
new_node_names = ['a', 'b', 'c']
# Return value contains dictionary from name to SUID.
new_nodes = scale_free100.add_nodes(new_node_names)
# Add new edges
# Send a list of tuples: (source node SUID, target node SUID, interaction type
new_ed... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Update Table
Let's do something a bit more realistic. You can update any Tables by using DataFrame objects.
1. ID conversion with external service
Let's use ID Conversion web service by Uniprot to add more information to existing yeast network in current session. | # Small utility function to convert ID sets
import requests
def uniprot_id_mapping_service(query=None, from_id=None, to_id=None):
# Uniprot ID Mapping service
url = 'http://www.uniprot.org/mapping/'
payload = {
'from': from_id,
'to': to_id,
'format':'tab',
'query': query
... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Create / Delete Table Data
Currently, you cannot delete the table or rows due to the Cytoscape data model design. However, it is easy to create / delete columns: | # Delete columns
yeast1.delete_node_table_column('kegg')
# Create columns
yeast1.create_node_column(name='New Empty Double Column', data_type='Double', is_immutable=False, is_list=False)
# Default is String, mutable column.
yeast1.create_node_column(name='Empty String Col')
yeast1.get_node_table().head() | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Visual Styles
You can also use wrapper API to access Visual Styles.
Current limitations are:
You need to use unique name for the Styles
Need to know how to write serialized form of objects | # Get all existing Visual Styles
import json
styles = cy.style.get_all()
print(json.dumps(styles, indent=4))
# Create a new style
style1 = cy.style.create('sample_style1')
# Get a reference to the existing style
default_style = cy.style.create('default')
print(style1.get_name())
print(default_style.get_name())
# Ge... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Set default values
To set default values for Visual Properties, simply pass key-value pairs as dictionary. | # Prepare key-value pair for Style defaults
new_defaults = {
# Node defaults
'NODE_FILL_COLOR': '#eeeeff',
'NODE_SIZE': 20,
'NODE_BORDER_WIDTH': 0,
'NODE_TRANSPARENCY': 120,
'NODE_LABEL_COLOR': 'white',
# Edge defaults
'EDGE_WIDTH': 3,
'EDGE_STROKE_UNSELECTED_PAINT': '#aaaaaa',... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Visual Mappings | # Passthrough mapping
style1.create_passthrough_mapping(column='name', col_type='String', vp='NODE_LABEL')
# Discrete mapping: Simply prepare key-value pairs and send it
kv_pair = {
'pp': 'pink',
'pd': 'green'
}
style1.create_discrete_mapping(column='interaction',
col_type='Stri... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Layouts
Currently, this supports automatic layouts with default parameters. | # Get list of available layout algorithms
layouts = cy.layout.get_all()
print(json.dumps(layouts, indent=4))
# Apply layout
cy.layout.apply(name='circular', network=yeast1)
yeast1.get_views()
yeast_view1 = yeast1.get_first_view()
node_views = yeast_view1['elements']['nodes']
df3 = pd.DataFrame(node_views)
df3.head() | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
Embed Interactive Widget | from py2cytoscape.cytoscapejs import viewer as cyjs
cy.layout.apply(network=scale_free100)
view1 = scale_free100.get_first_view()
view2 = yeast1.get_first_view()
# print(view1)
cyjs.render(view2, 'default2', background='#efefef')
# Use Cytoscape.js style JSON
cyjs_style = cy.style.get(minimal_style.get_name(), data_fo... | examples/New_wrapper_api_sample.ipynb | idekerlab/py2cytoscape | mit |
That is, there are eight feature vectors where each of them belongs to one out of three different classes (identified by either 0, 1, or 2). Let us have a look at this data: | import matplotlib.pyplot as pyplot
%matplotlib inline
def plot_data(feats,labels,axis,alpha=1.0):
# separate features according to their class
X0,X1,X2 = feats[labels==0], feats[labels==1], feats[labels==2]
# class 0 data
axis.plot(X0[:,0], X0[:,1], 'o', color='green', markersize=12, alpha=alpha)... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
In the figure above, we can see that two of the classes are represented by two points that are, for each of these classes, very close to each other. The third class, however, has four points that are close to each other with respect to the y-axis, but spread along the x-axis.
If we were to apply kNN (k-nearest neighb... | def make_covariance_ellipse(covariance):
import matplotlib.patches as patches
import scipy.linalg as linalg
# the ellipse is centered at (0,0)
mean = numpy.array([0,0])
# eigenvalue decomposition of the covariance matrix (w are eigenvalues and v eigenvectors),
# keeping only the ... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
A possible workaround to improve the performance of kNN in a data set like this would be to input to the kNN routine a distance measure. For instance, in the example above a good distance measure would give more weight to the y-direction than to the x-direction to account for the large spread along the x-axis. Nonethel... | from shogun import features, MulticlassLabels
feats = features(x.T)
labels = MulticlassLabels(y.astype(numpy.float64)) | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Secondly, perform LMNN training: | from shogun import LMNN
# number of target neighbours per example
k = 1
lmnn = LMNN(feats,labels,k)
# set an initial transform as a start point of the optimization
init_transform = numpy.eye(2)
lmnn.put('maxiter', 2000)
lmnn.train(init_transform) | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
LMNN is an iterative algorithm. The argument given to train represents the initial state of the solution. By default, if no argument is given, then LMNN uses PCA to obtain this initial value.
Finally, we retrieve the distance measure learnt by LMNN during training and visualize it together with the data: | # get the linear transform from LMNN
L = lmnn.get_real_matrix('linear_transform')
# square the linear transform to obtain the Mahalanobis distance matrix
M = numpy.matrix(numpy.dot(L.T,L))
# represent the distance given by LMNN
figure,axis = pyplot.subplots(1,1)
plot_data(x,y,axis)
ellipse = make_covariance_ellipse(M.... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Beyond the main idea
LMNN is one of the so-called linear metric learning methods. What this means is that we can understand LMNN's output in two different ways: on the one hand, as a distance measure, this was explained above; on the other hand, as a linear transformation of the input data. Like any other linear transf... | # project original data using L
lx = numpy.dot(L,x.T)
# represent the data in the projected space
figure,axis = pyplot.subplots(1,1)
plot_data(lx.T,y,axis)
plot_data(x,y,axis,0.3)
ellipse = make_covariance_ellipse(numpy.eye(2))
axis.add_artist(ellipse)
axis.set_title('LMNN\'s linear transform')
pyplot.show() | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
In the figure above, the transparent points represent the original data and are shown to ease the visualization of the LMNN transformation. Note also that the ellipse plotted is the one corresponding to the common Euclidean distance. This is actually an important consideration: if we think of LMNN as a linear transform... | import numpy
import matplotlib.pyplot as pyplot
%matplotlib inline
def sandwich_data():
from numpy.random import normal
# number of distinct classes
num_classes = 6
# number of points per class
num_points = 9
# distance between layers, the points of each class are in a layer
dist = 0.7... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Let the fun begin now! In the following block of code, we create an instance of a kNN classifier, compute the nearest neighbours using the Euclidean distance and, afterwards, using the distance computed by LMNN. The data set in the space result of the linear transformation given by LMNN is also shown. | from shogun import KNN, LMNN, features, MulticlassLabels
def plot_neighborhood_graph(x, nn, axis=pyplot, cols=['r', 'b', 'g', 'm', 'k', 'y']):
for i in range(x.shape[0]):
xs = [x[i,0], x[nn[1,i], 0]]
ys = [x[i,1], x[nn[1,i], 1]]
axis.plot(xs, ys, cols[int(y[i])])
feats = features(x.T)
labels = MulticlassLabels... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Notice how all the lines that go across the different layers in the left hand side figure have disappeared in the figure in the middle. Indeed, LMNN did a pretty good job here. The figure in the right hand side shows the disposition of the points in the transformed space; from which the neighbourhoods in the middle fig... | from shogun import CSVFile, features, MulticlassLabels
ape_features = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'multiclass/fm_ape_gut.dat')))
ape_labels = MulticlassLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'multiclass/label_ape_gut.dat'))) | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
It is of course important to have a good insight of the data we are dealing with. For instance, how many examples and different features do we have? | print('Number of examples = %d, number of features = %d.' % (ape_features.get_num_vectors(), ape_features.get_num_features())) | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
So, 1472 features! Those are quite many features indeed. In other words, the feature vectors at hand lie on a 1472-dimensional space. We cannot visualize in the input feature space how the feature vectors look like. However, in order to gain a little bit more of understanding of the data, we can apply dimension reducti... | def visualize_tdsne(features, labels):
from shogun import TDistributedStochasticNeighborEmbedding
converter = TDistributedStochasticNeighborEmbedding()
converter.put('target_dim', 2)
converter.put('perplexity', 25)
embedding = converter.embed(features)
import matplotlib.pyplot as ... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
In the figure above, the green points represent chimpanzees, the red ones bonobos, and the blue points gorillas. Providing the results in the figure, we can rapidly draw the conclusion that the three classes of apes are somewhat easy to discriminate in the data set since the classes are more or less well separated in t... | from shogun import KNN
from shogun import StratifiedCrossValidationSplitting, CrossValidation
from shogun import CrossValidationResult, MulticlassAccuracy
# set up the classifier
knn = KNN()
knn.put('k', 3)
knn.put('distance', sg.distance('EuclideanDistance'))
# set up 5-fold cross-validation
splitting = StratifiedCr... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Finally, we can say that KNN performs actually pretty well in this data set. The average test classification error is less than between 2%. This error rate is already low and we should not really expect a significant improvement applying LMNN. This ought not be a surprise. Recall that the points in this data set have m... | from shogun import LMNN
import numpy
# to make training faster, use a portion of the features
fm = ape_features.get_real_matrix('feature_matrix')
ape_features_subset = features(fm[:150, :])
# number of targer neighbours in LMNN, here we just use the same value that was used for KNN before
k = 3
lmnn = LMNN(ape_featur... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
So only 64 out of the 150 first features are important according to the result transform! The rest of them have been given a weight exactly equal to zero, even if all of the features were weighted equally with a value of one at the beginnning of the training. In fact, if all the 1472 features were used, only about 158 ... | import matplotlib.pyplot as pyplot
%matplotlib inline
statistics = lmnn.get_statistics()
pyplot.plot(statistics.obj.get())
pyplot.grid(True)
pyplot.xlabel('Number of iterations')
pyplot.ylabel('LMNN objective')
pyplot.show() | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Along approximately the first three hundred iterations, there is not much variation in the objective. In other words, the objective curve is pretty much flat. If we are not careful and use termination criteria that are not demanding enough, training could be stopped at this point. This would be wrong, and might have te... | from shogun import CSVFile, features, MulticlassLabels
wine_features = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'uci/wine/fm_wine.dat')))
wine_labels = MulticlassLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'uci/wine/label_wine.dat')))
assert(wine_features.get_num_vectors() == wine_labels.get_num_labels())
prin... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
First, let us evaluate the performance of kNN in this data set using the same cross-validation setting used in the previous section: | from shogun import KNN, EuclideanDistance
from shogun import StratifiedCrossValidationSplitting, CrossValidation
from shogun import CrossValidationResult, MulticlassAccuracy
import numpy
# kNN classifier
k = 5
knn = KNN()
knn.put('k', k)
knn.put('distance', EuclideanDistance())
splitting = StratifiedCrossValidationSp... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Seconly, we will use LMNN to find a distance measure and use it with kNN: | from shogun import LMNN
# train LMNN
lmnn = LMNN(wine_features, wine_labels, k)
lmnn.put('maxiter', 1500)
lmnn.train()
# evaluate kNN using the distance learnt by LMNN
knn.set_distance(lmnn.get_distance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
lmnn_means = numpy.zeros(3)
lmn... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
The warning is fine in this case, we have made sure that the objective variation was really small after 1500 iterations. In any case, do not hesitate to check it yourself studying the objective plot as it was shown in the previous section.
As the results point out, LMNN really helps here to achieve better classificatio... | print('minima = ' + str(numpy.min(wine_features, axis=1)))
print('maxima = ' + str(numpy.max(wine_features, axis=1))) | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Examine the second and the last dimensions, for instance. The second dimension has values ranging from 0.74 to 5.8, while the values of the last dimension range from 278 to 1680. This will cause that the Euclidean distance works specially wrong in this data set. You can realize of this considering that the total distan... | from shogun import RescaleFeatures
# preprocess features so that all of them vary within [0,1]
preprocessor = RescaleFeatures()
preprocessor.init(wine_features)
wine_features.add_preprocessor(preprocessor)
wine_features.apply_preprocessor()
# sanity check
assert(numpy.min(wine_features) >= 0.0 and numpy.max(wine_feat... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Another different preprocessing that can be applied to the data is called whitening. Whitening, which is explained in an article in wikipedia, transforms the covariance matrix of the data into the identity matrix. | import scipy.linalg as linalg
# shorthand for the feature matrix -- this makes a copy of the feature matrix
data = wine_features.get_real_matrix('feature_matrix')
# remove mean
data = data.T
data-= numpy.mean(data, axis=0)
# compute the square of the covariance matrix and its inverse
M = linalg.sqrtm(numpy.cov(data.T)... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
The covariance matrices before and after the transformation can be compared to see that the covariance really becomes the identity matrix. | import matplotlib.pyplot as pyplot
%matplotlib inline
fig, axarr = pyplot.subplots(1,2)
axarr[0].matshow(numpy.cov(wine_features))
axarr[1].matshow(numpy.cov(wine_white_features))
pyplot.show() | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
Finally, we evaluate again the performance obtained with kNN using the Euclidean distance and the distance found by LMNN using the whitened features. | wine_features = wine_white_features
# perform kNN classification after whitening
knn.set_distance(EuclideanDistance())
result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate())
euclidean_means[2] = result.get_real('mean')
print('kNN accuracy with the Euclidean distance after whitening %.4f.' % r... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
As it can be seen, it did not really help to whiten the features in this data set with respect to only applying feature rescaling; the accuracy was already rather large after rescaling. In any case, it is good to know that this transformation exists, as it can become useful with other data sets, or before applying othe... | assert(euclidean_means.shape[0] == lmnn_means.shape[0])
N = euclidean_means.shape[0]
# the x locations for the groups
ind = 0.5*numpy.arange(N)
# bar width
width = 0.15
figure, axes = pyplot.subplots()
figure.set_size_inches(6, 5)
euclidean_rects = axes.bar(ind, euclidean_means, width, color='y')
lmnn_rects = axes.bar... | doc/ipython-notebooks/metric/LMNN.ipynb | besser82/shogun | bsd-3-clause |
(1b) Pluralize and test
Let's use a map() transformation to add the letter 's' to each string in the base RDD we just created. We'll define a Python function that returns the word with an 's' at the end of the word. Please replace <FILL IN> with your solution. If you have trouble, the next cell has the solutio... | # TODO: Replace <FILL IN> with appropriate code
def makePlural(word):
"""Adds an 's' to `word`.
Note:
This is a simple function that only adds an 's'. No attempt is made to follow proper
pluralization rules.
Args:
word (str): A string.
Returns:
str: A string with 's' ... | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(1d) Pass a lambda function to map
Let's create the same RDD using a lambda function. | # TODO: Replace <FILL IN> with appropriate code
pluralLambdaRDD = wordsRDD.map(lambda a: a + "s")
print pluralLambdaRDD.collect()
# TEST Pass a lambda function to map (1d)
Test.assertEquals(pluralLambdaRDD.collect(), ['cats', 'elephants', 'rats', 'rats', 'cats'],
'incorrect values for pluralLambdaRDD... | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(1e) Length of each word
Now use map() and a lambda function to return the number of characters in each word. We'll collect this result directly into a variable. | # TODO: Replace <FILL IN> with appropriate code
pluralLengths = (pluralRDD
.map(lambda a: len(a))
.collect())
print pluralLengths
# TEST Length of each word (1e)
Test.assertEquals(pluralLengths, [4, 9, 4, 4, 4],
'incorrect values for pluralLengths') | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(1f) Pair RDDs
The next step in writing our word counting program is to create a new type of RDD, called a pair RDD. A pair RDD is an RDD where each element is a pair tuple (k, v) where k is the key and v is the value. In this example, we will create a pair consisting of ('<word>', 1) for each word element in th... | # TODO: Replace <FILL IN> with appropriate code
wordPairs = wordsRDD.map(lambda a: (a,1))
print wordPairs.collect()
# TEST Pair RDDs (1f)
Test.assertEquals(wordPairs.collect(),
[('cat', 1), ('elephant', 1), ('rat', 1), ('rat', 1), ('cat', 1)],
'incorrect value for wordPairs') | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(2b) Use groupByKey() to obtain the counts
Using the groupByKey() transformation creates an RDD containing 3 elements, each of which is a pair of a word and a Python iterator.
Now sum the iterator using a map() transformation. The result should be a pair RDD consisting of (word, count) pairs. | # TODO: Replace <FILL IN> with appropriate code
wordCountsGrouped = wordsGrouped.map(lambda (a,b): (a, sum(b)))
print wordCountsGrouped.collect()
# TEST Use groupByKey() to obtain the counts (2b)
Test.assertEquals(sorted(wordCountsGrouped.collect()),
[('cat', 2), ('elephant', 1), ('rat', 2)],
... | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(2d) All together
The expert version of the code performs the map() to pair RDD, reduceByKey() transformation, and collect in one statement. | # TODO: Replace <FILL IN> with appropriate code
wordCountsCollected = (wordsRDD
.map(lambda a: (a,1))
.reduceByKey(lambda a,b: a+b)
.collect())
print wordCountsCollected
# TEST All together (2d)
Test.assertEquals(sorted(wordCountsCollected), [('cat',... | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
Part 3: Finding unique words and a mean value
(3a) Unique words
Calculate the number of unique words in wordsRDD. You can use other RDDs that you have already created to make this easier. | # TODO: Replace <FILL IN> with appropriate code
uniqueWords = wordsRDD.distinct().count()
print uniqueWords
# TEST Unique words (3a)
Test.assertEquals(uniqueWords, 3, 'incorrect count of uniqueWords') | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(3b) Mean using reduce
Find the mean number of words per unique word in wordCounts.
Use a reduce() action to sum the counts in wordCounts and then divide by the number of unique words. First map() the pair RDD wordCounts, which consists of (key, value) pairs, to an RDD of values. | # TODO: Replace <FILL IN> with appropriate code
from operator import add
totalCount = (wordCounts
.map(lambda (a,b): b)
.reduce(lambda a,b: a+b))
average = totalCount / float(wordCounts.distinct().count())
print totalCount
print round(average, 2)
# TEST Mean using reduce (3b)
Test.assertEqu... | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
(4e) Remove empty elements
The next step is to filter out the empty elements. Remove all entries where the word is ''. | # TODO: Replace <FILL IN> with appropriate code
shakeWordsRDD = shakespeareWordsRDD.filter(lambda a: a != "")
shakeWordCount = shakeWordsRDD.count()
print shakeWordCount
# TEST Remove empty elements (4e)
Test.assertEquals(shakeWordCount, 882996, 'incorrect value for shakeWordCount') | lab1_word_count_student.ipynb | BillyLjm/CS100.1x.__CS190.1x | mit |
Composing Learning Algorithms
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/federated/tutorials/composing_learning_algorithms"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blan... | #@test {"skip": true}
!pip install --quiet --upgrade tensorflow-federated
!pip install --quiet --upgrade nest-asyncio
import nest_asyncio
nest_asyncio.apply()
from typing import Callable
import tensorflow as tf
import tensorflow_federated as tff | docs/tutorials/composing_learning_algorithms.ipynb | tensorflow/federated | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.