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 george package pre-computes a lot of matrices that are re-used in different operations, so before anything else, we'll ask it to compute the GP model for our timeseries: python gp.compute(t, sigma) Note that we've only given it the time array and the uncertainties, so as long as those remain the same, you don't have to re-compute anything. This will save you a lot of time in the long run! Finally, the log likelihood is given by gp.log_likelihood(y). How do the speeds compare? Did you get the same value of the likelihood?
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 log likelihood?
%%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 doing GPs in the time domain, so we're good), then celerite is what it's all about: bash pip install celerite Check out the docs here, as well as several tutorials. There is also a paper that discusses the math behind celerite. The basic idea is that for certain families of kernels, there exist extremely efficient methods of factorizing the covariance matrices. Whereas GP fitting typically scales with the number of datapoints $N$ as $N^3$, celerite is able to do everything in order $N$ (!!!) This is a huge advantage, especially for datasets with tens or hundreds of thousands of data points. Using george or any homebuilt GP model for datasets larger than about 10,000 points is simply intractable, but with celerite you can do it in a breeze. Next we repeat the timing tests, but this time using celerite. Note that the Exponential Squared Kernel is not available in celerite, because it doesn't have the special form needed to make its factorization fast. Instead, we'll use the Matern 3/2 kernel, which is qualitatively similar and can be approximated quite well in terms of the celerite basis functions: python kernel = celerite.terms.Matern32Term(np.log(1), np.log(1)) Note that celerite accepts the log of the amplitude and the log of the timescale. Other than this, we can compute the likelihood using the same syntax as george. How much faster did it run? Is the value of the likelihood different from what you found above? Why?
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 (fictitious) light curve for a star with a transiting planet:
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 the connection and cursor later. Next time we could use a with context to automatically close the connection. with sqlite3.connect('sqlite3.db') as conn: cur = conn.execute('SQL QUERY ...') # e.g.: 'SELECT * FROM table_name;' output = cur.fetchall() # get the results Closing the connection automatically closes the cursor. Other bindings may offer similar context managers. to commit and close changes or rollback changes and raise an exception. Creating tables A relational database or SQL database is a tabular structure consisting of rows of data with columns of fields. The data definition language or DDL used to create the table is the same language used to query it, called SQL or Structured Query Language. Although the basic SQL commands are nearly the same for other relational databases, the data types may be different. SQLite only has 5 datatypes: NULL, INTEGER, REAL, TEXT, BLOB. For boolean, use integer zero for false, and one for true. For dates and times use text and ISO8601, e.g.: "2018-02-21T17:05-0800". By comparison, PostgreSQL has too many to list here including booleans, date, time, arrays, JSON, etc. CREATE The basic SQL command to create a table is CREATE TABLE &lt;table_name&gt; (&lt;field_name&gt; &lt;TYPE&gt; &lt;CONSTRAINTS&gt;, &lt;field_name&gt; &lt;TYPE&gt; &lt;CONSTRAINTS&gt;, &lt;CONSTRAINTS&gt;, ...); Some languages enforce the semicolon, some don't. The syntax is nearly the same for other relational databases. Constraints, Defaults, and Options Constraints are optional and set conditions, limitations, or options for columns and the table. The most common constraints are: PRIMARY KEY, UNIQUE, NOT NULL, DEFAULT, FOREIGN KEY, REFERENCES, etc. The syntax is nearly the same for other relational databases. PRIMARY KEY The most important of these is PRIMARY KEY which is equivalent to UNIQUE NOT NULL. A primary key is a unique references that identifies each record in the table. Although it is not required, every table should have a primary key. Only one primary key is allowed, and it can be constructed from multiple columns, PRIMARY KEY (&lt;field_A&gt;, &lt;field_B), to create a unique together, non-null identifier. In SQLite, if missing then a integer primary key named, rowid, is created by default. Also in SQLite, any integer primary key is automatically incremented, so the AUTOINCREMENT command is usually not needed. In PostgreSQL the SERIAL command is used to create a corresponding sequence for the primary key. Practice The other constraints and options are also important, but we'll discover those as we learn. Let's create some simple databases with fictitious data to practice. Imagine you are testing several different materials with different properties $\alpha$ and $\beta$ under different stresses like different temperatures and light intensity and changing thickness. How would you organize this data? Take a moment to design a schema or structure for your data. The schema consists of the column names and data types and the column and table constraints.
# 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, material_type TEXT NOT NULL )''') conn.commit() # if you don't commit the changes, they won't be written to the file, and won't be visible to other connections # then create an experiments table cur.execute('''CREATE TABLE experiments ( experiment_id INTEGER PRIMARY KEY, temperature REAL DEFAULT 298.15, irradiance REAL DEFAULT 1000.0, uv_filter INTEGER DEFAULT 0, material_id NOT NULL REFERENCES materials ON UPDATE CASCADE ON DELETE CASCADE, thickness REAL DEFAULT 0.005, UNIQUE (temperature, irradiance, uv_filter, material_id) )''') conn.commit() # and finally create a trials table cur.execute('''CREATE TABLE trials ( trial_id INTEGER PRIMARY KEY, experiment_id NOT NULL REFERENCES experiments ON UPDATE CASCADE ON DELETE CASCADE, results BLOB NOT NULL, duration REAL NOT NULL, avg_temperature REAL NOT NULL, std_temperature REAL NOT NULL, avg_irradiance REAL NOT NULL, std_irradiance REAL NOT NULL, init_visible_transmittance REAL NOT NULL, final_visible_transmittance REAL NOT NULL, notes TEXT )''') conn.commit()
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 (material_id) Specifying the referenced column in the table constraint isn't necessary, and if omitted defaults to the primary key of the referenced table. The syntax is nearly the same for other relational databases. You can use the same name for the foreign key and it's related field, but it may make joining tables more difficult because you will need to use the table name to avoid an ambigous column name. E.G.: you can use trials.experiment_id and experiments.experiment_id to differentiate between them. You can also use AS to create a temporary name like trials.experiment_id AS experiment. Or you could just use different names for the foreign key and it's related field like FOREIGN KEY (material) REFERENCES materials (material_id) and then there's no ambiguity. Your call. DELETE and UPDATE What happens if the reference of a foreign key is deleted or updated? That's up to you: in SQLite the default is to do nothing, but typically you want the action to cascade. Add the desired ON DELETE or ON UPDATE action to the constraint. Bonus Questions What is the difference between a column constraint and a table constraint? What other table constraint is in the experiments table? What other constraints or defaults are applied in the tables? What part of the materials table schema is fragile and can be improved? INSERT The basic SQL command to put data into a table is INSERT INTO &lt;table_name&gt; (&lt;field_name&gt;, &lt;field_name&gt;, ...) VALUES (&lt;value&gt;, &lt;value&gt;, ...) Other relational databases use the same SQL syntax. Let's add some pretend data to the database
# 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 a convenient shortcut, but it may not be convenient for all database bindings.
# 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 (?, ?, ?, ?, ?)', mat) # use place holders conn.commit() # you can commit all of the changes at the end of the loop # use the executemany shortcut fake_materials = [ ('SiO2', 'silicon dioxide', 1.617, 18.19, 'crystal'), ('CaF2', 'calcium flouride', 2.0, 21.22, 'crystal') ] cur.executemany('INSERT INTO materials VALUES (?, ?, ?, ?, ?)', fake_materials) conn.commit() print('rowcount = %d' % cur.rowcount) # with executemany, cur.rowcount shows total number of rows
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 (?, ?)', materials_list) [(mat, cur.fetchone()) for mat in materials_list] # use the cursor fetchone() method to get next item
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: cur.execute('INSERT INTO experiments (temperature, irradiance) VALUES (?, ?)', (T, E)) except sqlite3.IntegrityError as exc: print('sqlite3.IntegrityError: %s', exc) # Oops! We forgot to specify the material, there is not default, and it is constrained as NOT NULL! conn.rollback() # undo any changes try: for T in temp: for E in irrad: cur.execute('INSERT INTO experiments (temperature, irradiance, material_id) VALUES (?, ?, "EVA")', (T, E)) except sqlite3.IntegrityError as exc: print(exc) conn.commit() # commit! commit! commit! # this list is hard to read list(cur.execute('SELECT * FROM experiments')) # not only is Pandas much nicer, it also executes queries! pd.read_sql('SELECT * FROM experiments', conn, index_col='experiment_id')
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', conn, index_col='experiment_id')
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.random.randn(size) + 298.15, 'irradiance': np.random.randn(size) + 1000, 'visible_transmittance': np.logspace(np.log10(0.9), np.log10(0.8), size) + np.random.randn(size) / 100 } results = pd.DataFrame(data, index=timestamps) duration = (results.index[-1] - results.index[0]).value # [ns] avg_temperature = results.temperature.mean() # [K] std_temperature = results.temperature.std() # [K] avg_irradiance = results.irradiance.mean() # [W/m^2] std_irradiance = results.irradiance.std() # [W/m^2] init_visible_transmittance = results.visible_transmittance[start_time] final_visible_transmittance = results.visible_transmittance[end_time] values = (1, results.to_csv(), duration, avg_temperature, std_temperature, avg_irradiance, std_irradiance, init_visible_transmittance, final_visible_transmittance, 'this is doctored data') cur.execute('''INSERT INTO trials ( experiment_id, results, duration, avg_temperature, std_temperature, avg_irradiance, std_irradiance, init_visible_transmittance, final_visible_transmittance, notes ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', values) conn.commit() # commit! commit! commit! # check the blob, is it really there? cur.execute('SELECT results FROM trials WHERE trial_id = 1') trial1_results = cur.fetchone() pd.read_csv(io.StringIO(trial1_results[0]), index_col=0) # yay! it works!
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' 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.random.randn(size) + temperature, 'irradiance': np.random.randn(size) + irradiance, 'visible_transmittance': np.logspace(np.log10(0.9), np.log10(0.7), size) + np.random.randn(size) / 100 } results = pd.DataFrame(data, index=timestamps) duration = (results.index[-1] - results.index[0]).value # [ns] avg_temperature = results.temperature.mean() # [K] std_temperature = results.temperature.std() # [K] avg_irradiance = results.irradiance.mean() # [W/m^2] std_irradiance = results.irradiance.std() # [W/m^2] init_visible_transmittance = results.visible_transmittance[start_time] final_visible_transmittance = results.visible_transmittance[end_time] values = (experiment_id, results.to_csv(), duration, avg_temperature, std_temperature, avg_irradiance, std_irradiance, init_visible_transmittance, final_visible_transmittance, 'this is doctored data') cur.execute('''INSERT INTO trials ( experiment_id, results, duration, avg_temperature, std_temperature, avg_irradiance, std_irradiance, init_visible_transmittance, final_visible_transmittance, notes ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', values) conn.commit() # commit! commit! commit! pd.read_sql(''' SELECT trial_id, trials.experiment_id AS experiment, init_visible_transmittance, final_visible_transmittance, experiments.material_id AS material, temperature, irradiance, alpha, beta, material_type FROM trials JOIN experiments ON experiments.experiment_id = experiment JOIN materials ON materials.material_id = material ''', conn, index_col='trial_id') cur.close() conn.close()
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, " ", j) y = Predictor() y.load_data(file="Data/Training/clean_s_filtered.csv") y.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i, random_data=0) y.supervised_training("mlp_adam") y.benchmark(j, "S") del y print("x", i, " ", j) x = Predictor() x.load_data(file="Data/Training/clean_s_filtered.csv") x.process_data(vector_function="sequence", amino_acid="S", imbalance_function=i, random_data=1) x.supervised_training("mlp_adam") x.benchmark(j, "S") del x
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: print("y", i, " ", j) y = Predictor() y.load_data(file="Data/Training/clean_Y_filtered.csv") y.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i, random_data=0) y.supervised_training("bagging") y.benchmark(j, "Y") del y print("x", i, " ", j) x = Predictor() x.load_data(file="Data/Training/clean_Y_filtered.csv") x.process_data(vector_function="sequence", amino_acid="Y", imbalance_function=i, random_data=1) x.supervised_training("bagging") x.benchmark(j, "Y") del x except: print("Benchmark not relevant")
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, " ", j) y = Predictor() y.load_data(file="Data/Training/clean_t_filtered.csv") y.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i, random_data=0) y.supervised_training("mlp_adam") y.benchmark(j, "T") del y print("x", i, " ", j) x = Predictor() x.load_data(file="Data/Training/clean_t_filtered.csv") x.process_data(vector_function="sequence", amino_acid="T", imbalance_function=i, random_data=1) x.supervised_training("mlp_adam") x.benchmark(j, "T") del x
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 independent, variables. The independent variables can be stored in a vector, a 1-dimensional array: $$X^T = (X_{1}, X_{2}, X_{3})$$ As we have multiple records these can be stacked in a 2-dimensional array. Each record becomes one row in the array. Our x variable is already set up in this way. In linear regression we can compute the value of the dependent variable using the following formula: $$f(X) = \beta_{0} + \sum_{j=1}^p X_j\beta_j$$ The $\beta_{0}$ term is the intercept, and represents the value of the dependent variable when the independent variable is zero. Calculating a solution is easier if we don't treat the intercept as special. Instead of having an intercept co-efficient that is handled separately we can instead add a variable to each of our records with a value of one.
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 returned by lstsq?
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) ** 2), residuals
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$$ Matrix arithmetic Within lstsq all the calculations are performed using matrix arithmetic rather than the more familiar element-wise arithmetic numpy arrays generally perform. Numpy does have a matrix type but matrix arithmetic can also be performed on standard arrays using dedicated methods. Source: Wikimedia Commons (User:Bilou) In matrix multiplication the resulting value in any position is the sum of multiplying each value in a row in the first matrix by the corresponding value in a column in the second matrix. The residual sum of squares can be calculated with the following formula: $$RSS(\beta) = (y - X\beta)^T(y-X\beta)$$ The value of our co-efficients can be calculated with: $$\hat\beta = (X^TX)^{-1}X^Ty$$ Unfortunately, the result is not as visually appealing as in languages that use matrix arithmetic by default.
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(numpoints=1, loc=4) plt.show() np.arange(12).reshape((3,4))
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 range.
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_predictions = np.sum(intercept_all_x * our_coeff.T, axis=1) plt.plot(all_x, all_x_predictions, 'r-', label='Predictions') plt.legend(numpoints=1, loc=4) plt.show()
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 linear with respect to its inputs. Those input variables can take any form. One approach we can take to improve the predictions from our model would be to add in the square, cube, etc of our existing variable.
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 is to detect true sources of variation in the data and ignore variation that is just noise. How do we know if we have a good model? A common approach is to break up our data into a training set, a validation set, and a test set. We train models with different parameters on the training set. We evaluate each model on the validation set, and choose the best We then measure the performance of our best model on the test set. What would our best model look like? Because we are using dummy data here we can easily make more.
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( np.dot( x.T, x ) ), x.T ), y ) our_predictions = np.dot(x, our_coeff) our_training_rss = np.sum((y - our_predictions) ** 2) training.append(our_training_rss) val_x = np.random.random((n,1)) val_y = 5 + 6 * val_x ** 2 + np.random.normal(0,0.5, size=(n,1)) val_x = np.hstack((val_x**j for j in np.arange(i))) our_val_pred = np.dot(val_x, our_coeff) our_val_rss = np.sum((val_y - our_val_pred) ** 2) val.append(our_val_rss) #print(i, our_training_rss, our_val_rss) plt.plot(range(1, p), training, 'ko-', label='training') plt.plot(range(1, p), val, 'ro-', label='validation') plt.legend(loc=2) plt.show()
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 the error and changing the coefficients slightly to reduce that error. It does this by calculating a gradient and then descending to a minimum in small steps. Stochastic gradient descent calculates the gradient on a small batch of the data, updates the coefficients, loads the next chunk of the data and repeats the process. We will just look at a basic gradient descent model.
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.zeros((x.shape[1], 1)) costs = [] for i in range(rounds): prediction = np.dot(x, theta) error = prediction - y gradient = np.dot(x.T, error / y.shape[0]) theta -= gradient * alpha costs.append(np.sum(error ** 2)) return (theta, costs) theta, costs = gradient_descent(intercept_x, y, rounds=10000) print(theta, costs[::500]) 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)) x = np.hstack((x**j for j in np.arange(20))) coeff, residuals, rank, sing_vals = np.linalg.lstsq(x,y) print('lstsq', coeff) theta, costs = gradient_descent(x, y, rounds=10000) print(theta, costs[::500]) plt.plot(x[:,1], y, 'ko') plt.plot(x[:,1], np.dot(x, coeff), 'co') plt.plot(x[:,1], np.dot(x, theta), 'ro') plt.show()
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 of spaces to advance. For example, if the total on your first roll is 2, you could advance a token to space 2. If you roll a 3 on the next roll, you could advance the same token to space 5. Suppose you have a token on space 13. How many rolls did it take to get there? Hint: you might want to start by computing the distribution of k given n, where k is the number of the space and n is the number of rolls. Then think about the prior distribution of n. Here's a Pmf that represents one of the 4-sided dice.
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 over.
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 yield(n, total)
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 about, so let's start by assuming that it is uniform, and see where that gets us. If the prior is uniform, the posterior equals the likelihood function, normalized.
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 par l'algorithme. En sortie nous obtenons l'ensemble des paires semblables, avec leur mesure de similarité. On stocke dans un fichier pour l'exploiter ensuite avec un autre script PIG. Pour réduire le nombre de résultats, nous ne retiendrons que les paires de films qui ont une similarité de plus de 0.5 .
%%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 Rating*Rating; out = SUM(tmp_out); GENERATE group as MovieID, SQRT(out) as Norm, ($sqrt_gamma.$0/SQRT(out)>1?1:$sqrt_gamma.$0/SQRT(out)) as Prob_j; } } cData = LOAD '$CONTAINER/imdd/ratings_mean.csv' using PigStorage (',') AS (UserID:int, MovieID:int, Rating:double) ; -- On calcule le gamma users = GROUP cData all ; total= FOREACH users GENERATE MAX($1.UserID) as m, MAX($1.MovieID) as n; sqrt_gamma = FOREACH total GENERATE SQRT(4*LOG(n)/0.7) as a; -- On calcule la norme et le gamma sur la norme Matrix_Norms = computeMatrixNorms(cData,sqrt_gamma); -- On ajoute la colonne Norm et probabilite dans cData C = JOIN cData BY MovieID,Matrix_Norms BY MovieID; D = FOREACH C GENERATE cData::UserID as UserID_f,cData::MovieID as MovieID_f,cData::Rating as Rating_f, Matrix_Norms::Norm as Norm_f,Matrix_Norms::Prob_j as Prob_j_f; Matrix_data = GROUP D BY UserID_f; FF = FOREACH Matrix_data GENERATE group as UID, FLATTEN(D.MovieID_f) as MV1; -- Ajout des informations de MV1 FFF = JOIN FF BY (UID,MV1), D BY (UserID_f,MovieID_f); -- Condition de validite premier IF FFD = FILTER FFF BY RANDOM()<Prob_j_f; -- Ajout de la seconde loop GG = JOIN FFD BY UID, D BY UserID_f; -- Cleaning du tableau GGG = FOREACH GG GENERATE FFD::FF::UID as UserID,FFD::FF::MV1 as MV_1,FFD::D::Rating_f as Rating_1,FFD::D::Norm_f as Norm_1, FFD::D::Prob_j_f as Proba_1,D::MovieID_f as MV_2,D::Rating_f as Rating_2, D::Norm_f as Norm_2,D::Prob_j_f as Proba_2; -- Ajout de la deuxieme boucle -- Condition de validite second IF GGD = FILTER GGG BY RANDOM()<Proba_2; -- Generation des similarites HH = FOREACH GGD{ val = Rating_1*Rating_2/(((sqrt_gamma.$0>Norm_1)?Norm_1:sqrt_gamma.$0)*((sqrt_gamma.$0>Norm_2)?Norm_2:sqrt_gamma.$0)); GENERATE MV_1,MV_2,val as VAL; } DESCRIBE HH; -- Ajout d un filtre supplementaire pour reduire la taille des resultats HHH = FILTER HH BY VAL > 0.5; HHHH = DISTINCT HHH; STORE GGD INTO '$CONTAINER/$PSEUDO/dom/matrix_all.txt' USING PigStorage(','); STORE HHH INTO '$CONTAINER/$PSEUDO/dom/similarities.txt' USING PigStorage(',');
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 in df["name"]: cl.delete_blob(bs, "hdblobstorage", 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 ids des films dont la similarité calculée est maximale.
%%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_limit GENERATE MovieID2; STORE movies INTO '$CONTAINER/imdd/dom/recom.txt' USING PigStorage(',');
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["status"]["jobComplete"],st["status"]["state"])
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)) # calculate d_observation/d_error gradients_graph = tf.gradients(sum_error_squared, observations_variable) session = tf.Session() session.run(tf.initialize_all_variables()) steps = 0
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') plot(observations[0,:,1], label='observations') ylim((-5,5)) grid() legend() plot_gradients(gradients) for i in range(1): # take 1 gradient descent step steps += 1 observations = session.run( observations_variable.assign_sub(gradients * 0.5 * (random.random() - 0.25)) ) plot(observations[0,:,1], label='observations') sigmoid = np.vectorize(lambda(x): 1.0/(1.0+np.exp(-x))) # plot(sigmoid(observations[0,:,1]), label='sigmoid(observations)') legend() grid() hmm_np = hmm.HMMNumpy(np.array([[0.9, 0.1], [0.1, 0.9]]), p0=np.array([0.5, 0.5])) out, _ = hmm_np.viterbi_decode(sigmoid(observations[0,:,:])) print 'gradient steps taken:', steps print 'viterbi error:', sum((truth[0,:,1] - out)**2) plot(truth[0,:,1], label='truth') plot(out, label='out') grid() legend()
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, this new version uses its DataFrame as its basic data object. Embedded Cytoscaep.js Widget You can use Cytoscape.js widget to embed your final result as a part of your notebook. Simpler Code to access Cytoscape cyREST provides language-agnostic RESTful API, but you need to use a lot of template code to access raw API. Here is an example. Both of the following do the same task, which is creating an empty network in Cytoscape. You will notice it is significantly simpler if you use py2cytoscape wrapper API. Raw cyREST
# 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 = { 'data': { 'name': 'I\'m empty!' }, 'elements': { 'nodes':[], 'edges':[] } } res = requests.post(BASE + 'networks?collection=My%20Collection', data=json.dumps(empty_network), headers=HEADERS) new_network_id = res.json()['networkSUID'] print('New network created with raw REST API. Its SUID is ' + str(new_network_id))
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 Cytoscape
# 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.session.delete()
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 multiple locations network_locations = [ 'sample_yeast_network.xgmml', # Local file 'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif', # Static file on a web server 'http://www.ebi.ac.uk/Tools/webservices/psicquic/intact/webservices/current/search/query/brca1?format=xml25' # or a web service ] # This requrns Series networks = cy.network.create_from(network_locations) pd.DataFrame(networks, columns=['CyNetwork'])
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 uses 'source' for source node column, 'target' for target node column, and 'interaction' for interaction yeast1 = cy.network.create_from_dataframe(df_from_sif, name='Yeast network created from pandas DataFrame') # Example 2: from more complicated table df_from_mitab = pd.read_csv('intact_pubid_22094256.txt', sep='\t') df_from_mitab.head() source = df_from_mitab.columns[0] target = df_from_mitab.columns[1] interaction = 'Interaction identifier(s)' title='A Systematic Screen for CDK4/6 Substrates Links FOXM1 Phosphorylation to Senescence Suppression in Cancer Cells.' human1 = cy.network.create_from_dataframe(df_from_mitab, source_col=source, target_col=target, interaction_col=interaction, name=title) # Import edge attributes and node attributes at the same time (TBD) # NetworkX nx_graph = nx.scale_free_graph(100) nx.set_node_attributes(nx_graph, 'Degree', nx.degree(nx_graph)) nx.set_node_attributes(nx_graph, 'Betweenness_Centrality', nx.betweenness_centrality(nx_graph)) scale_free100 = cy.network.create_from_networkx(nx_graph, collection='Generated by NetworkX') # TODO: igraph # TODO: Numpy adj. martix # TODO: GraphX
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_edges)) # As a simple, SIF-like DataFrame yeast1_df = yeast1.to_dataframe() yeast1_df.head()
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 ' + str(len(edges)) + ' edges\n') # Get a row in the node table as pandas Series object node0 = nodes[0] row = yeast1.get_node_value(id=node0) print(row) # Or, pick one cell in the table cell = yeast1.get_node_value(id=node0, column='name') print('\nThis node has name: ' + str(cell))
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 properties. Since pandas is extremely useful to handle table data, default data type for tables is DataFrame. However, you can also use other data types including: Cytoscape.js style JSON CSV TSV CX (TBD)
# 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. "name" is the unique Index scale_free100.get_node_columns()
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_edges = [] new_edges.append((new_nodes['a'], new_nodes['b'], 'type1')) new_edges.append((new_nodes['a'], new_nodes['c'], 'type2')) new_edges.append((new_nodes['b'], new_nodes['c'], 'type3')) new_edge_ids = scale_free100.add_edges(new_edges) new_edge_ids # Delete node scale_free100.delete_node(new_nodes['a']) # Delete edge scale_free100.delete_edge(new_edge_ids.index[0])
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 } res = requests.get(url, params=payload) df = pd.read_csv(res.url, sep='\t') res.close() return df # Get node table from Cytoscape yeast_node_table = yeast1.get_node_table() # From KEGG ID to UniprotKB ID query1 = ' '.join(yeast_node_table['name'].map(lambda gene_id: 'sce:' + gene_id).values) id_map_kegg2uniprot = uniprot_id_mapping_service(query1, from_id='KEGG_ID', to_id='ID') id_map_kegg2uniprot.columns = ['kegg', 'uniprot'] # From UniprotKB to SGD query2 = ' '.join(id_map_kegg2uniprot['uniprot'].values) id_map_uniprot2sgd = uniprot_id_mapping_service(query2, from_id='ID', to_id='SGD_ID') id_map_uniprot2sgd.columns = ['uniprot', 'sgd'] # From UniprotKB to Entrez Gene ID query3 = ' '.join(id_map_kegg2uniprot['uniprot'].values) id_map_uniprot2ncbi = uniprot_id_mapping_service(query3, from_id='ID', to_id='P_ENTREZGENEID') id_map_uniprot2ncbi.columns = ['uniprot', 'entrez'] # Merge them merged = pd.merge(id_map_kegg2uniprot, id_map_uniprot2sgd, on='uniprot') merged = pd.merge(merged, id_map_uniprot2ncbi, on='uniprot') # Add key column by removing prefix merged['name'] = merged['kegg'].map(lambda kegg_id : kegg_id[4:]) merged.head() update_url = BASE + 'networks/' + str(yeast1.get_id()) + '/tables/defaultnode' print(update_url) ut = { 'key': 'name', 'dataKey': 'name', 'data': [ { 'name': 'YBR112C', 'foo': 'aaaaaaaa' } ] } requests.put(update_url, json=ut, headers=HEADERS) # Now update existing node table with the data frame above. yeast1.update_node_table(merged, network_key_col='name', data_key_col='name') # Check the table is actually updated yeast1.get_node_table().head()
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()) # Get all available Visual Properties print(len(cy.style.vps.get_all())) # Get Visual Properties for each data type node_vps = cy.style.vps.get_node_visual_props() edge_vps = cy.style.vps.get_edge_visual_props() network_vps = cy.style.vps.get_network_visual_props() print(pd.Series(edge_vps).head())
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', 'EDGE_LINE_TYPE': 'LONG_DASH', 'EDGE_TRANSPARENCY': 120, # Network defaults 'NETWORK_BACKGROUND_PAINT': 'black' } # Update style1.update_defaults(new_defaults) # Apply the new style cy.style.apply(style1, yeast1)
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='String', vp='EDGE_STROKE_UNSELECTED_PAINT', mappings=kv_pair) # Continuous mapping points = [ { 'value': '1.0', 'lesser':'white', 'equal':'white', 'greater': 'white' }, { 'value': '20.0', 'lesser':'green', 'equal':'green', 'greater': 'green' } ] minimal_style = cy.style.create('Minimal') minimal_style.create_continuous_mapping(column='Degree', col_type='Double', vp='NODE_FILL_COLOR', points=points) # Or, use utility for simple mapping simple_slope = StyleUtil.create_slope(min=1, max=20, values=(10, 60)) minimal_style.create_continuous_mapping(column='Degree', col_type='Double', vp='NODE_SIZE', points=simple_slope) # Apply the new style cy.style.apply(minimal_style, scale_free100)
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_format='cytoscapejs') cyjs.render(view1, style=cyjs_style['style'], background='white')
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) # class 1 data axis.plot(X1[:,0], X1[:,1], 'o', color='red', markersize=12, alpha=alpha) # class 2 data axis.plot(X2[:,0], X2[:,1], 'o', color='blue', markersize=12, alpha=alpha) # set axes limits axis.set_xlim(-1.5,1.5) axis.set_ylim(-1.5,1.5) axis.set_aspect('equal') axis.set_xlabel('x') axis.set_ylabel('y') figure,axis = pyplot.subplots(1,1) plot_data(x,y,axis) axis.set_title('Toy data set') pyplot.show()
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 neighbors) in a data set like this, we would expect quite some errors using the standard Euclidean distance. This is due to the fact that the spread of the data is not similar amongst the feature dimensions. The following piece of code plots an ellipse on top of the data set. The ellipse in this case is in fact a circunference that helps to visualize how the Euclidean distance weights equally both feature dimensions.
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 real part w,v = linalg.eigh(covariance) # normalize the eigenvector corresponding to the largest eigenvalue u = v[0]/linalg.norm(v[0]) # angle in degrees angle = 180.0/numpy.pi*numpy.arctan(u[1]/u[0]) # fill Gaussian ellipse at 2 standard deviation ellipse = patches.Ellipse(mean, 2*w[0]**0.5, 2*w[1]**0.5, 180+angle, color='orange', alpha=0.3) return ellipse # represent the Euclidean distance figure,axis = pyplot.subplots(1,1) plot_data(x,y,axis) ellipse = make_covariance_ellipse(numpy.eye(2)) axis.add_artist(ellipse) axis.set_title('Euclidean distance') pyplot.show()
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. Nonetheless, it would be nicer (and, in fact, much more useful in practice) if this distance could be learnt automatically from the data at hand. Actually, LMNN is based upon this principle: given a number of neighbours k, find the Mahalanobis distance measure which maximizes kNN accuracy (using the given value for k) in a training data set. As we usually do in machine learning, under the assumption that the training data is an accurate enough representation of the underlying process, the distance learnt will not only perform well in the training data, but also have good generalization properties. Now, let us use the LMNN class implemented in Shogun to find the distance and plot its associated ellipse. If everything goes well, we will see that the new ellipse only overlaps with the data points of the green class. First, we need to wrap the data into Shogun's feature and label objects:
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.I) axis.add_artist(ellipse) axis.set_title('LMNN distance') pyplot.show()
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 transformation, LMNN's output can be written as a matrix, that we will call $L$. In other words, if the input data is represented by the matrix $X$, then LMNN can be understood as the data transformation expressed by $X'=L X$. We use the convention that each column is a feature vector; thus, the number of rows of $X$ is equal to the input dimension of the data, and the number of columns is equal to the number of vectors. So far, so good. But, if the output of the same method can be interpreted in two different ways, then there must be a relation between them! And that is precisely the case! As mentioned above, the ellipses that were plotted in the previous section represent a distance measure. This distance measure can be thought of as a matrix $M$, being the distance between two vectors $\vec{x_i}$ and $\vec{x_j}$ equal to $d(\vec{x_i},\vec{x_j})=(\vec{x_i}-\vec{x_j})^T M (\vec{x_i}-\vec{x_j})$. In general, this type of matrices are known as Mahalanobis matrices. In LMNN, the matrix $M$ is precisely the 'square' of the linear transformation $L$, i.e. $M=L^T L$. Note that a direct consequence of this is that $M$ is guaranteed to be positive semi-definite (PSD), and therefore define a valid metric. This distance measure/linear transform duality in LMNN has its own advantages. An important one is that the optimization problem can go back and forth between the $L$ and the $M$ representations, giving raise to a very efficient solution. Let us now visualize LMNN using the linear transform interpretation. In the following figure we have taken our original toy data, transform it using $L$ and plot both the before and after versions of the data together.
# 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 transformation, the distance considered in the projected space is the Euclidean distance, and no any Mahalanobis distance given by M. To sum up, we can think of LMNN as a linear transform of the input space, or as method to obtain a distance measure to be used in the input space. It is an error to apply both the projection and the learnt Mahalanobis distance. Neighbourhood graphs An alternative way to visualize the effect of using the distance found by LMNN together with kNN consists of using neighbourhood graphs. Despite the fancy name, these are actually pretty simple. The idea is just to construct a graph in the Euclidean space, where the points in the data set are the nodes of the graph, and a directed edge from one point to another denotes that the destination node is the 1-nearest neighbour of the origin node. Of course, it is also possible to work with neighbourhood graphs where $k \gt 1$. Here we have taken the simplification of $k = 1$ so that the forthcoming plots are not too cluttered. Let us define a data set for which the Euclidean distance performs considerably bad. In this data set there are several levels or layers in the y-direction. Each layer is populated by points that belong to the same class spread along the x-direction. The layers are close to each other in pairs, whereas the spread along x is larger. Let us define a function to generate such a data set and have a look at it.
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 # memory pre-allocation x = numpy.zeros((num_classes*num_points, 2)) y = numpy.zeros(num_classes*num_points) for i,j in zip(range(num_classes), range(-num_classes//2, num_classes//2 + 1)): for k,l in zip(range(num_points), range(-num_points//2, num_points//2 + 1)): x[i*num_points + k, :] = numpy.array([normal(l, 0.1), normal(dist*j, 0.1)]) y[i*num_points:i*num_points + num_points] = i return x,y def plot_sandwich_data(x, y, axis=pyplot, cols=['r', 'b', 'g', 'm', 'k', 'y']): for idx,val in enumerate(numpy.unique(y)): xi = x[y==val] axis.scatter(xi[:,0], xi[:,1], s=50, facecolors='none', edgecolors=cols[idx]) x, y = sandwich_data() figure, axis = pyplot.subplots(1, 1, figsize=(5,5)) plot_sandwich_data(x, y, axis) axis.set_aspect('equal') axis.set_title('"Sandwich" toy data set') axis.set_xlabel('x') axis.set_ylabel('y') pyplot.show()
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(y) fig, axes = pyplot.subplots(1, 3, figsize=(15, 10)) # use k = 2 instead of 1 because otherwise the method nearest_neighbors just returns the same # points as their own 1-nearest neighbours k = 2 distance = sg.distance('EuclideanDistance') distance.init(feats, feats) knn = KNN(k, distance, labels) plot_sandwich_data(x, y, axes[0]) plot_neighborhood_graph(x, knn.nearest_neighbors(), axes[0]) axes[0].set_title('Euclidean neighbourhood in the input space') lmnn = LMNN(feats, labels, k) # set a large number of iterations. The data set is small so it does not cost a lot, and this way # we ensure a robust solution lmnn.put('maxiter', 3000) lmnn.train() knn.put('distance', lmnn.get_distance()) plot_sandwich_data(x, y, axes[1]) plot_neighborhood_graph(x, knn.nearest_neighbors(), axes[1]) axes[1].set_title('LMNN neighbourhood in the input space') # plot features in the transformed space, with the neighbourhood graph computed using the Euclidean distance L = lmnn.get_real_matrix('linear_transform') xl = numpy.dot(x, L.T) feats = features(xl.T) dist = sg.distance('EuclideanDistance') dist.init(feats, feats) knn.put('distance', dist) plot_sandwich_data(xl, y, axes[2]) plot_neighborhood_graph(xl, knn.nearest_neighbors(), axes[2]) axes[2].set_ylim(-3, 2.5) axes[2].set_title('Euclidean neighbourhood in the transformed space') [axes[i].set_xlabel('x') for i in range(len(axes))] [axes[i].set_ylabel('y') for i in range(len(axes))] [axes[i].set_aspect('equal') for i in range(len(axes))] pyplot.show()
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 figure should be clear. In any case, this toy example is just an illustration to give an idea of the power of LMNN. In the next section we will see how after applying a couple methods for feature normalization (e.g. scaling, whitening) the Euclidean distance is not so sensitive against different feature scales. Real data sets Feature selection in metagenomics Metagenomics is a modern field in charge of the study of the DNA of microorganisms. The data set we have chosen for this section contains information about three different types of apes; in particular, gorillas, chimpanzees, and bonobos. Taking an approach based on metagenomics, the main idea is to study the DNA of the microorganisms (e.g. bacteria) which live inside the body of the apes. Owing to the many chemical reactions produced by these microorganisms, it is not only the DNA of the host itself important when studying, for instance, sickness or health, but also the DNA of the microorganisms inhabitants. First of all, let us load the ape data set. This data set contains features taken from the bacteria inhabitant in the gut of the apes.
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 reduction, embed the feature vectors in a two-dimensional space, and plot the vectors in the embedded space. To this end, we are going to use one of the many methods for dimension reduction included in Shogun. In this case, we are using t-distributed stochastic neighbour embedding (or t-dsne). This method is particularly suited to produce low-dimensional embeddings (two or three dimensions) that are straightforward to visualize.
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 pyplot % matplotlib inline x = embedding.get_real_matrix('feature_matrix') y = labels.get_real_vector('labels') pyplot.scatter(x[0, y==0], x[1, y==0], color='green') pyplot.scatter(x[0, y==1], x[1, y==1], color='red') pyplot.scatter(x[0, y==2], x[1, y==2], color='blue') pyplot.show() visualize_tdsne(ape_features, ape_labels)
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 two dimensions. Note that t-dsne use randomness in the embedding process. Thus, the figure result of the experiment in the previous block of code will be different after different executions. Feel free to play around and observe the results after different runs! After this, it should be clear that the bonobos form most of the times a very compact cluster, whereas the chimpanzee and gorillas clusters are more spread. Also, there tends to be a chimpanzee (a green point) closer to the gorillas' cluster. This is probably a outlier in the data set. Even before applying LMNN to the ape gut data set, let us apply kNN classification and study how it performs using the typical Euclidean distance. Furthermore, since this data set is rather small in terms of number of examples, the kNN error above may vary considerably (I have observed variation of almost 20% a few times) across different runs. To get a robust estimate of how kNN performs in the data set, we will perform cross-validation using Shogun's framework for evaluation. This will give us a reliable result regarding how well kNN performs in this data set.
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 = StratifiedCrossValidationSplitting(ape_labels, 5) # evaluation method evaluator = MulticlassAccuracy() cross_validation = CrossValidation(knn, ape_features, ape_labels, splitting, evaluator) # locking is not supported for kNN, deactivate it to avoid an inoffensive warning cross_validation.put('m_autolock', False) # number of experiments, the more we do, the less variance in the result num_runs = 200 cross_validation.put('num_runs', num_runs) # perform cross-validation and print the result! result = cross_validation.evaluate() result = CrossValidationResult.obtain_from_generic(result) print('kNN mean accuracy in a total of %d runs is %.4f.' % (num_runs, result.get_real('mean')))
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 more than one thousand features and, as we saw before in the dimension reduction experiment, only two dimensions in an embedded space were enough to discern arguably well the chimpanzees, gorillas and bonobos. Note that we have used stratified splitting for cross-validation. Stratified splitting divides the folds used during cross-validation so that the proportion of the classes in the initial data set is approximately maintained for each of the folds. This is particular useful in skewed data sets, where the number of examples among classes varies significantly. Nonetheless, LMNN may still turn out to be very useful in a data set like this one. Making a small modification of the vanilla LMNN algorithm, we can enforce that the linear transform found by LMNN is diagonal. This means that LMNN can be used to weight each of the features and, once the training is performed, read from these weights which features are relevant to apply kNN and which ones are not. This is indeed a form of feature selection. Using Shogun, it is extremely easy to switch to this so-called diagonal mode for LMNN: just call the method set_diagonal(use_diagonal) with use_diagonal set to True. The following experiment takes about five minutes until it is completed (using Shogun Release, i.e. compiled with optimizations enabled). This is mostly due to the high dimension of the data (1492 features) and the fact that, during training, LMNN has to compute many outer products of feature vectors, which is a computation whose time complexity is proportional to the square of the number of features. For the illustration purposes of this notebook, in the following cell we are just going to use a small subset of all the features so that the training finishes faster.
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_features_subset, ape_labels, k) lmnn.put('m_diagonal', True) lmnn.put('maxiter', 1000) init_transform = numpy.eye(ape_features_subset.get_num_features()) lmnn.train(init_transform) diagonal = numpy.diag(lmnn.get_real_matrix('linear_transform')) print('%d out of %d elements are non-zero.' % (numpy.sum(diagonal != 0), diagonal.size))
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 would have received a non-zero weight. Please, feel free to experiment using all the features! It is a fair question to ask how did we know that the maximum number of iterations in this experiment should be around 1200 iterations. Well, the truth is that we know this only because we have run this experiment with this same data beforehand, and we know that after this number of iterations the algorithm has converged. This is not something nice, and the ideal case would be if one could completely forget about this parameter, so that LMNN uses as many iterations as it needs until it converges. Nevertheless, this is not practical at least because of two reasons: If you are dealing with many examples or with very high dimensional feature vectors, you might not want to wait until the algorithm converges and have a look at what LMNN has found before it has completely converged. As with any other algorithm based on gradient descent, the termination criteria can be tricky. Let us illustrate this further:
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 terrible results as the training had not clearly converged yet at that moment. In order to avoid disastrous situations, in Shogun we have implemented LMNN with really demanding criteria for automatic termination of the training process. Albeit, it is possible to tune the termination criteria using the methods set_stepsize_threshold and set_obj_threshold. These methods can be used to modify the lower bound required in the step size and the increment in the objective (relative to its absolute value), respectively, to stop training. Also, it is possible to set a hard upper bound on the number of iterations using set_maxiter as we have done above. In case the internal termination criteria did not fire before the maximum number of iterations was reached, you will receive a warning message, similar to the one shown above. This is not a synonym that the training went wrong; but it is strongly recommended at this event to have a look at the objective plot as we have done in the previous block of code. Multiclass classification In addition to feature selection, LMNN can be of course used for multiclass classification. I like to think about LMNN in multiclass classification as a way to empower kNN. That is, the idea is basically to apply kNN using the distance found by LMNN $-$ in contrast with using one of the other most common distances, such as the Euclidean one. To this end we will use the wine data set from the UCI Machine Learning repository.
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()) print('%d feature vectors with %d features from %d different classes.' % (wine_features.get_num_vectors(), \ wine_features.get_num_features(), wine_labels.get_num_classes()))
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 = StratifiedCrossValidationSplitting(wine_labels, 5) evaluator = MulticlassAccuracy() cross_validation = CrossValidation(knn, wine_features, wine_labels, splitting, evaluator) cross_validation.put('m_autolock', False) num_runs = 200 cross_validation.put('num_runs', num_runs) result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate()) euclidean_means = numpy.zeros(3) euclidean_means[0] = result.get_real('mean') print('kNN accuracy with the Euclidean distance %.4f.' % result.get_real('mean'))
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) lmnn_means[0] = result.get_real('mean') print('kNN accuracy with the distance obtained by LMNN %.4f.' % result.get_real('mean'))
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 classification performance. However, this comparison is not entirely fair since the Euclidean distance is very sensitive to the scaling that different feature dimensions may have, whereas LMNN can adjust to this during training. Let us have a closer look to this fact. Next, we are going to retrieve the feature matrix and see what are the maxima and minima for every dimension.
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 distance between two points will almost certainly just take into account the contributions of the dimensions with largest range. In order to produce a more fair comparison, we will rescale the data so that all the feature dimensions are within the interval [0,1]. Luckily, there is a preprocessor class in Shogun that makes this straightforward.
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_features) <= 1.0) # perform kNN classification after the feature rescaling knn.put('distance', EuclideanDistance()) result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate()) euclidean_means[1] = result.get_real('mean') print('kNN accuracy with the Euclidean distance after feature rescaling %.4f.' % result.get_real('mean')) # train kNN in the new features and classify with kNN lmnn.train() knn.put('distance', lmnn.get_distance()) result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate()) lmnn_means[1] = result.get_real('mean') print('kNN accuracy with the distance obtained by LMNN after feature rescaling %.4f.' % result.get_real('mean'))
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)) # keep only the real part, although the imaginary that pops up in the sqrtm operation should be equal to zero N = linalg.inv(M).real # apply whitening transform white_data = numpy.dot(N, data.T) wine_white_features = features(white_data)
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.' % result.get_real('mean')) # train kNN in the new features and classify with kNN lmnn.train() knn.put('distance', lmnn.get_distance()) result = CrossValidationResult.obtain_from_generic(cross_validation.evaluate()) lmnn_means[2] = result.get_real('mean') print('kNN accuracy with the distance obtained by LMNN after whitening %.4f.' % result.get_real('mean'))
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 other machine learning algorithms. Let us summarize the results obtained in this section with a bar chart grouping the accuracy results by distance (Euclidean or the one found by LMNN), and feature preprocessing:
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(ind+width, lmnn_means, width, color='r') # attach information to chart axes.set_ylabel('Accuracies') axes.set_ylim(top=1.4) axes.set_title('kNN accuracy by distance and feature preprocessing') axes.set_xticks(ind+width) axes.set_xticklabels(('Raw', 'Rescaling', 'Whitening')) axes.legend(( euclidean_rects[0], lmnn_rects[0]), ('Euclidean', 'LMNN'), loc='upper right') def autolabel(rects): # attach text labels to bars for rect in rects: height = rect.get_height() axes.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%.3f' % height, ha='center', va='bottom') autolabel(euclidean_rects) autolabel(lmnn_rects) pyplot.show()
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 &lt;FILL IN&gt; with your solution. If you have trouble, the next cell has the solution. After you have defined makePlural you can run the third cell which contains a test. If you implementation is correct it will print 1 test passed. This is the general form that exercises will take, except that no example solution will be provided. Exercises will include an explanation of what is expected, followed by code cells where one cell will have one or more &lt;FILL IN&gt; sections. The cell that needs to be modified will have # TODO: Replace &lt;FILL IN&gt; with appropriate code on its first line. Once the &lt;FILL IN&gt; sections are updated and the code is run, the test cell can then be run to verify the correctness of your solution. The last code cell before the next markdown section will contain the tests.
# 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' added to it. """ return word + "s" print makePlural('cat') # One way of completing the function def makePlural(word): return word + 's' print makePlural('cat') # Load in the testing code and check to see if your answer is correct # If incorrect it will report back '1 test failed' for each failed test # Make sure to rerun any cell you change before trying the test again from test_helper import Test # TEST Pluralize and test (1b) Test.assertEquals(makePlural('rat'), 'rats', 'incorrect result: makePlural does not add an 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 (1d)')
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 ('&lt;word&gt;', 1) for each word element in the RDD. We can create the pair RDD using the map() transformation with a lambda() function to create a new RDD.
# 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)], 'incorrect value for wordCountsGrouped')
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', 2), ('elephant', 1), ('rat', 2)], 'incorrect value for wordCountsCollected')
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.assertEquals(round(average, 2), 1.67, 'incorrect value of average')
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="_blank" href="https://colab.research.google.com/github/tensorflow/federated/blob/v0.27.0/docs/tutorials/composing_learning_algorithms.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/federated/blob/v0.27.0/docs/tutorials/composing_learning_algorithms.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/federated/docs/tutorials/composing_learning_algorithms.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> Before you start Before you start, please run the following to make sure that your environment is correctly setup. If you don't see a greeting, please refer to the Installation guide for instructions.
#@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