markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
可以用方法ranking_來看輸入的特徵權重關係。而方法estimator_可以取得訓練好的分類機狀態。比較特別的是當我們核函數是以線性來做分類時,estimator_下的方法coef_即為特徵的分類權重矩陣。權重矩陣的大小會因為n_features_to_select與資料的分類類別而改變,譬如本範例是十個數字的分類,並選擇以一個特徵來做分類訓練,就會得到45*1的係數矩陣,其中45是從分類類別所需要的判斷式而來,與巴斯卡三角形的第三層數正比。 (三)畫出每個像素所對應的權重順序 取得每個像素位置對於判斷數字的權重順序後,我們把權重順序依照顏色畫在對應的位置,數值愈大代表該像素是較不重要之特徵。由結果來看,不重要之特徵多半位於影像...
# Plot pixel ranking plt.matshow(ranking, cmap=plt.cm.Blues) plt.colorbar() plt.title("Ranking of pixels with RFE") plt.show()
Feature_Selection/ipython_notebook/ex2_Recursive_feature_elimination.ipynb
dryadb11781/machine-learning-python
bsd-3-clause
(四)原始碼 Python source code: plot_rfe_digits.py
print(__doc__) from sklearn.svm import SVC from sklearn.datasets import load_digits from sklearn.feature_selection import RFE import matplotlib.pyplot as plt # Load the digits dataset digits = load_digits() X = digits.images.reshape((len(digits.images), -1)) y = digits.target # Create the RFE object and rank each pi...
Feature_Selection/ipython_notebook/ex2_Recursive_feature_elimination.ipynb
dryadb11781/machine-learning-python
bsd-3-clause
Learn about the Model Input <br> HydroTrend will now be activated in PyMT. You can find information on the model, the developer, the papers that describe the moel in more detail etc. Importantly you can scroll down a bit to the Parameters list, it shows what parameters the model uses to control the simulations. The li...
# Get basic information about the HydroTrend model help(hydrotrend)
notebooks/hydrotrend.ipynb
csdms/pymt
mit
Exercise 1: Explore the Hydrotrend base-case river simulation For this case study, first we will create a subdirectory in which the basecase (BC) simulation will be implemented. Then we specify for how long we will run a simulation: for 100 years at daily time-step. This means you run Hydrotrend for 36,500 days total....
# Set up Hydrotrend model by indicating the number of years to run config_file, config_folder = hydrotrend.setup("_hydrotrendBC", run_duration=100)
notebooks/hydrotrend.ipynb
csdms/pymt
mit
With the cat command you can print character by character one of the two input files that HydroTrend uses. HYDRO0.HYPS: This first file specifies the River Basin Hysometry - the surface area per elevation zone. The hypsometry captures the geometric characteristics of the river basin, how high is the relief, how much up...
cat _hydrotrendBC/HYDRO0.HYPS cat _hydrotrendBC/HYDRO.IN #In pymt one can always find out what output a model generates by using the .output_var_names method. hydrotrend.output_var_names # Now we initialize the model with the configure file and in the configure folder hydrotrend.initialize(config_file, config_fold...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
## <font color = green> Assignment 1 </font> Calculate mean water discharge Q, mean suspended load Qs, mean sediment concentration Cs, and mean bedload Qb for this 100 year simulation of the river dynamics of the Waiapaoa River. Note all values are reported as daily averages. What are the units?
# your code goes here
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Assignment 2 </font> Identify the highest flood event for this simulation. Is this the 100-year flood? Please list a definition of a 100 year flood, and discuss whether the modeled extreme event fits this definition. Plot the year of Q-data which includes the flood.
# here you can calculate the maximum river discharge. # your code to determine which day and which year encompass the maximum discharge go here # Hint: you will want to determine the ndex of htis day first, look into the numpy.argmax and numpy.argmin # as a sanity check you can see whether the plot y-axis seems to g...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Assignment 3 </font> Calculate the mean annual sediment load for this river system. Then compare the annual load of the Waiapaoha river to the Mississippi River. <br> To compare the mean annual load to other river systems you will need to calculate its sediment yield. Sediment Yield is defined as ...
# your code goes here # you will have to sum all days of the individual years, to get the annual loads, then calculate the mean over the 100 years. # one possible trick is to use the .reshape() method # plot a graph of the 100 years timeseries of the total annual loads # take the mean over the 100 years #your evalua...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
HydroTrend Exercise 2: How does a river system respond to climate change; two simple scenarios for the coming century. Now we will look at changing climatic conditions in a small river basin. We'll change temperature and precipitation regimes and compare discharge and sediment load characteristics to the original basec...
# Set up a new run of the Hydrotrend model # Create a new config file a different folder for input and output files, indicating the number of years to run, and specify the change in mean annual temparture parameter hydrotrendHT = pymt.models.Hydrotrend() config_file, config_folder = hydrotrendHT.setup("_hydrotrendhigh...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Assignment 5 </font> So what is the effect of a warming basin temperature? How much increase or decrease of river discharge do you see after 50 years? <br> How is the mean suspended load affected? <br> How does the mean bedload change? <br> What happens to the peak event; look at the maximum sedim...
# type your answers here
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Assignment 6 </font> What happens to river discharge, suspended load and bedload if the mean annual precipitation would increase by 50% in this specific river basin over the next 50 years? Create a new simulation folder, High Precipitation, HP, and set up a run with a trend in future precipitation.
# Set up a new run of the Hydrotrend model # Create a new config file indicating the number of years to run, and specify the change in mean annual precipitation parameter # initialize the new simulation # your code for the timeloop goes here ## your code that prints out the mean river discharge, the mean sediment l...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Assignment 7 </font> In addition, climate model predictions indicate that perhaps precipitation intensity and variability could increase. How would you possibly model this? Discuss how you would modify your input settings for precipitation.
#type your answer here
notebooks/hydrotrend.ipynb
csdms/pymt
mit
Exercise 3: How do humans affect river sediment loads? Here we will look at the effect of human in a river basin. Humans can accelerate erosion processes, or reduce the sediment loads traveling through a river system. Both concepts can be simulated, first run 3 simulations systematically increasing the anthropogenic fa...
# your explanation goes here, can you list two reasons why this factor would be unsuitable or it would fall short?
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Bonus Assignment 9 </font> Model a scenario of a drinking water supply reservoir to be planned in the coastal area of the basin. The reservoir would have 800 km 2of contributing drainage area and be 3 km long, 200m wide and 100m deep. Set up a simulation with these parameters.
# Set up a new 50 year of the Hydrotrend model # Create a new directory, and a config file indicating the number of years to run, and specify different reservoir parameters # initialize the new simulation # your code for the timeloop and update loop goes here # plot a bar graph comparing Q mean, Qs mean, Qmax, Qs M...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
<font color = green> Bonus Assignment 10 </font> Set up a simulation for a different river basin. This means you would need to change the HYDRO0.HYPS file and change some climatic parameters. There are several hypsometric files packaged with HydroTrend, you can use one of those, but are welcome to do something differ...
# write a short motivation and description of your scenario # make a 2 panel plot using the subplot functionality of matplotlib # One panel would show the hypsometry of the Waiapohoa and the other panel the hypsometry of your selected river basin # Set up a new 50 year of the Hydrotrend model # Create a new direct...
notebooks/hydrotrend.ipynb
csdms/pymt
mit
4. Calculate the coefficient of correlation (r) and generate the scatter plot. Does there seem to be a correlation worthy of investigation?
df.plot(kind='scatter', x='Exposure', y='Mortality') r = df.corr()['Exposure']['Mortality'] r
class6/donow/Lee_Dongjin_6_Donow.ipynb
ledeprogram/algorithms
gpl-3.0
Yes, there seems to be a correlation wothy of investigation. 5. Create a linear regression model based on the available data to predict the mortality rate given a level of exposure
lm = smf.ols(formula="Mortality~Exposure",data=df).fit() intercept, slope = lm.params lm.params
class6/donow/Lee_Dongjin_6_Donow.ipynb
ledeprogram/algorithms
gpl-3.0
6. Plot the linear regression line on the scatter plot of values. Calculate the r^2 (coefficient of determination)
# Method 01 (What we've learned from the class) df.plot(kind='scatter', x='Exposure', y='Mortality') plt.plot(df["Exposure"],slope*df["Exposure"]+intercept,"-",color="red") # Method 02 (Another version) _ so much harder ...than what we have learned def plot_correlation( ds, x, y, ylim=(100,240) ): plt.xlim(0,14) ...
class6/donow/Lee_Dongjin_6_Donow.ipynb
ledeprogram/algorithms
gpl-3.0
7. Predict the mortality rate (Cancer per 100,000 man years) given an index of exposure = 10
def predicting_mortality_rate(exposure): return intercept + float(exposure) * slope predicting_mortality_rate(10)
class6/donow/Lee_Dongjin_6_Donow.ipynb
ledeprogram/algorithms
gpl-3.0
Custom experimental setup with item sampling The EigenRec paper follows a specific experimentation setup, mainly based on the settings, proposed in my another favorite paper Performance of recommender algorithms on top-n recommendation tasks, devoted to the PureSVD model itself. For evaluation purposes, the authors sam...
data_model.test_ratio = 0 # do not split dataset into folds, use entire dataset for sampling data_model.holdout_size = 0.014 # sample this fraction of ratings from data data_model.random_holdout = True # sample ratings randomly (not just 5-star) data_model.warm_start = False # allow test users to be part of the trainin...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Mind the test_ratio parameter setting. Together with the test_fold parameter it controls, which fraction of the dataset to sample from; 0 means the whole dataset and turns off data splitting mechanism used by Polara for cross-validation. The value of test_fold has no effect in that case. Also note that by default Polar...
data_model.test.holdout.head()
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
The second step is to leave only items with rating 5, as it was done in the original paper. The easiest way in our case would be to simply run: python data_model.test.holdout.query('rating==5', inplace=True) However, in general, you shouldn't manually change the data after it was processed by Polara, as it may break so...
data_model.set_test_data( holdout=data_model.test.holdout.query('rating==5'), # select only 5-star ratings warm_start=data_model.warm_start, reindex=False, # avoid reindexing users and items second time ensure_consistency=False # do not try to filter out unseen entities (already...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Note that we reuse the previously sampled holdout dataset (the $\mathcal{P}$ dataset in the authors' notation), which is already reindexed by Polara's built-in data pre-processing procedure. In order not to loose the index mapping between internal and external representation of movies and users (stored in the data_mode...
data_model.test.holdout.head()
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Scaled SVD-based model In the simplest case of the EigenRec model, when only the scaling factor is changed, we can go with a very straightforward approach. Instead of computing similarity matrices and solving an eigendecomposition problem, it is sufficient to apply standard SVD to a scaled rating matrix $\tilde R$: $...
from scipy.sparse import diags from scipy.sparse.linalg import norm as spnorm def sparse_normalize(matrix, scaling, axis): '''Function to scale either rows or columns of the sparse rating matrix''' if scaling == 1: # no scaling (standard SVD case) return matrix norm = spnorm(matrix, axis=axis,...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Sampling random items for evaluation Somewhat more involved modifications are required to generate model predictions, as it's based on an additional sampling of items not previously seen by the test users. Quote from the paper (Section 4.2.1): <div class="alert alert-block alert-info">"For each item in $\mathcal{T}$, ...
data_model.test.holdout.userid.value_counts().max()
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
In order to "flatten" the holdout dataset and to independently generate prediction scores for every holdout item (and 1000 of additionally sampled items) we will customize the get_recommendations method of the SVDModel class. Below is the support function, that helps to achieve the necessary result. It iterates over al...
def sample_scores_flat(useridx, itemidx, seen_data, all_items, user_factors, item_factors, sample_size=1000, random_state=None): '''Function to randomly sample unrated items and generate prediction scores for them.''' scores = [] for user, items in itemidx.groupby(useridx): # iterate over every test user an...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
<div class="alert alert-block alert-warning">Prediction scores are generated similarly to the standard *PureSVD* model by an orthogonal projection of a vector $r$ of user ratings onto the latent feature space, defined by the formula $VV^Tr$. Note that unlike the model computation phase, no scaling is used in the predic...
import numpy as np import pandas as pd from polara import SVDModel class ScaledSVD(SVDModel): '''Class that adds scaling functionality to the PureSVD model''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.col_scaling = 1 # scaling parameted d, initially corres...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
The model is ready and can be used in a standard way:
svd = ScaledSVD(data_model) # create model svd.rank = 50 svd.col_scaling = 0.5 svd.build() # fit model
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Now, when we have our model computed, its time to evaluate it. However, we cannot use the built-in evaluation routine. Normally, the number of test users is equal to the number of rows in recommendations array and that's the logic Polara relies on. In our case the number of test users is lower than the number of rows i...
# if you run the cell for the first time you'll notice a short delay before print output due to calculation of recommendations print('# of test users:', data_model.test.holdout.userid.nunique()) print('# of rows and columns in recommendations array:', svd.recommendations.shape) print('# of ratinhgs in the holdout:', da...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
We will fix this inconsistency in the next section. Worth noting here that Polara implements a unified system of callbacks, which reset the svd.recommendations property whenever either the data_model or the model itself are changed in a way that affects the models' output (try, for example, call svd.recommendations, th...
def evaluate_mrr(model): '''Function to calculate MRR score.''' is_holdout = model.recommendations==0 # holdout items are always in the first column before sorting pos = np.where(is_holdout)[1] + 1.0 # position of holdout items (indexing starts from 0, so adding 1) mrr = np.reciprocal(pos).mean() # mea...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Finally, to compute the MRR score, as it is done in the original paper, simply run:
evaluate_mrr(svd)
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
More functional approach While the previously described approach is fully working and easy, in some cases you may want to use the built-in model.evaluate method, as it provides additional functionality. It is also useful to see how Polara can be customized to serve specific needs. The key ingredient here is the control...
svd._prediction_key = 'xuser' svd._prediction_target = 'xitem'
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Now, we need to specify the corresponding fields in the holdout data. Recall that our goal is to treat every item in the holdout independently of the user or, in other words, to assign every item to a unique "virtual" user ('xuser'). Furthermore, by construction, prediction scores for holdout items are located in the f...
data_model.test.holdout['xuser'] = np.arange(data_model.test.holdout.shape[0]) # number of rated items defines the range data_model.test.holdout['xitem'] = 0
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Let's check that the result is the same (up to a small rounding error due to different calculation schemes):
svd.evaluate('ranking', simple_rates=True) # `simple_rates` is used to enforce calculation of MRR
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
<div class="alert alert-block alert-warning">If you'll do the math you'll see that the whole experiment took under 100 lines of code to program, and the most part of it was pretty standard (i.e., declaring variables and methods).</div> Less lines of code typically means less risks for having bugs or inconsistencies. B...
try: from ipypb import track except ImportError: from tqdm import tqdm_notebook as track %matplotlib inline svd_mrr_flat = {} # will stor results here svd.verbose = False max_rank = 150 scaling_params = np.arange(-20, 21, 2) / 10 # values of d from -2 to 2 with step 0.2 svd_ranks = range(10, max_rank+1, 10) #...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Results Now we have the results of the grid search stored in the svd_mrr_flat dictionary. There's one catch that wasn't clear for me at first: <div class="alert alert-block alert-warning">in order to show the effect of parameter $d$ the authors have fixed the value of rank corresponding to the best result achieved with...
result_flat = pd.Series(svd_mrr_flat) best_d, best_rank = result_flat.idxmax() best_d, best_rank result_flat.xs(best_rank, axis=0, level=1).plot(label='fixed rank', legend=True, title='MRR', figsize=(4.3, 2), ylim=(0, None), xlim=(-2, 2), grid=True);
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Comparing this picture to the bottom left graph of Figure 1 in the original paper leads to a satisfactory conclusion that the curves on the graphs are very close. Of course, there are slight differences; however, there are many factors that may affect it, like data sampling and unrated items randomization. It would be ...
result_flat.sort_values(ascending=False).head()
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
A bit of exploration The difference between the best result achieved with the EigenRec approach and the standard PureSVD result (that corresponds to the point with scaling parameter equal to 1) is quite large. However, such a comparison is a bit unfair as the restriction on having a fixed value of rank is artificial. W...
result_flat.groupby(level=0).max().plot(label='optimal rank', legend=True) result_flat.xs(best_rank, axis=0, level=1).plot(label='fixed rank', legend=True, title='MRR', figsize=(4.3, 2), ylim=(0, None), xlim=(-2, 2), grid=True);
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Now the difference is less pronounced. Anyway, the EigenRec approach still performs better. Moreover, the difference vary significantly from dataset to dataset and in some cases that difference can be much more noticeable. Another degree of freedom here, which may increase the top score, is the maximum value of rank us...
ax = result_flat.groupby(level=0).idxmax().str[1].plot(label='optimal rank value', ls=":", legend=True, secondary_y=True, c='g') result_flat.groupby(level=0).max().plot(label='optimal rank experiment', legend=True) result_flat.xs(best_rank, axis=0, level=1).plot(la...
examples/Reproducing_EIGENREC_results.ipynb
Evfro/polara
mit
Data preparation We will use some of Ben's Sjorgrens data for this. We will generate a random sample of 1 million reads from the full data set. Prepare data with Snakemake bash snakemake -s aligners.snakefile It appears that kallisto needs at least 51 bases of the reference to successfully align most of the reads. Mu...
names = ['QNAME', 'FLAG', 'RNAME', 'POS', 'MAPQ', 'CIGAR', 'RNEXT', 'PNEXT', 'TLEN', 'SEQ', 'QUAL'] bowtie_alns = pd.read_csv('alns/bowtie-51mer.aln', sep='\t', header=None, usecols=list(range(11)), names=names) bowtie2_alns = pd.read_csv('alns/bowtie2-51mer.aln', sep='\t', header=None, usecols=list(range(11)), names=...
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Bowtie2 vs kallisto
bt2_k_joined = pd.merge(bowtie2_alns, kallisto_alns, how='inner', on='QNAME', suffixes=['_bt2', '_k'])
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
How many reads do bowtie2 and kallisto agree on?
(bt2_k_joined.RNAME_bt2 == bt2_k_joined.RNAME_k).sum() For the minority of reads they disagree on, what do they look like?
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
For the minority of reads they disagree on, what do they look like
bt2_k_joined[bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k].RNAME_k
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Mostly lower sensitivity of kallisto due to indels in the read. Specifically, out of
(bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k).sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
discordant reads, the number where kallisto failed to map is
(bt2_k_joined[bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k].RNAME_k == '*').sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
or as a fraction
(bt2_k_joined[bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k].RNAME_k == '*').sum() / (bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k).sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Are there any cases where bowtie2 fails to align
(bt2_k_joined[bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k].RNAME_bt2 == '*').sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Which means there are no cases where bowtie and kallisto align to different peptides.
((bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k) & (bt2_k_joined.RNAME_bt2 != '*') & (bt2_k_joined.RNAME_k != '*')).sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
What do examples look like of kallisto aligning and bowtie2 not?
bt2_k_joined[(bt2_k_joined.RNAME_bt2 != bt2_k_joined.RNAME_k) & (bt2_k_joined.RNAME_bt2 == '*')]
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Looks like there is a perfect match to a prefix and the latter part of the read doesn't match ``` read AAATCCACCATTGTGAAGCAGATGAAGATCATTCATGGTTACTCAGAGCA ref AAATCCACCATTGTGAAGCAGATGAAGATCATTCATAAAAATGGTTACTCA read GGTCCTCACGCCGCCCGCGTTCGCGGGTTGGCATTACAATCCGCTTTCCA ref GGTCCTCACGCCGCCCGCGTTCGCGGGTTGGCATTCCTCCCACACCAG...
bt_k_joined = pd.merge(bowtie_alns, kallisto_alns, how='inner', on='QNAME', suffixes=['_bt', '_k'])
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
How many reads do bowtie and kallisto agree on?
(bt_k_joined.RNAME_bt == bt_k_joined.RNAME_k).sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
For the minority of reads they disagree on, what do they look like
bt_k_joined[bt_k_joined.RNAME_bt != bt_k_joined.RNAME_k][['RNAME_bt', 'RNAME_k']]
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Looks like many disagreeents, but probably still few disagreements on a positive mapping.
(bt_k_joined.RNAME_bt != bt_k_joined.RNAME_k).sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
discordant reads, the number where kallisto failed to map is
(bt_k_joined[bt_k_joined.RNAME_bt != bt_k_joined.RNAME_k].RNAME_k == '*').sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
and the number where bowtie failed is
(bt_k_joined[bt_k_joined.RNAME_bt != bt_k_joined.RNAME_k].RNAME_bt == '*').sum()
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
which means there are no disagreements on mapping. kallisto appears to be somewhat higher sensitivity. Quantitation
bowtie_counts = pd.read_csv('counts/bowtie-51mer.tsv', sep='\t', header=0, names=['id', 'input', 'output']) bowtie2_counts = pd.read_csv('counts/bowtie2-51mer.tsv', sep='\t', header=0, names=['id', 'input', 'output']) kallisto_counts = pd.read_csv('counts/kallisto-51mer.tsv', sep='\t', header=0) fig, ax = plt.subplots...
notebooks/aligners/Aligners.ipynb
laserson/phip-stat
apache-2.0
Check significance In an e-mail received 19/07/2016 at 17:20, Don pointed out a couple of TOC plots on my trends map where he was surprised that the estimated trend was deemed insignificant: Little Woodford (site code X15:1C1-093) Partridge (station code X15:ME-9999) Checking this will provide a useful test of my tre...
# Read RESA2 export, calculate annual medians and plot # Input file in_xlsx = (r'C:\Data\James_Work\Staff\Heleen_d_W\ICP_Waters\TOC_Trends_Analysis_2015' r'\Data\TOC_Little_Woodford_Partridge.xlsx') df = pd.read_excel(in_xlsx, sheetname='DATA') # Pivot df = df.pivot(index='Date', columns='Station name', va...
check_trend_signif.ipynb
JamesSample/icpw
mit
These plots and summary statistics are identical to the ones given on my web map (with the exception that, for plotting, the web map linearly interpolates over data gaps, so the break in the line for Little Woodford is not presented). This is a good start. The next step is to estimate the Theil-Sen slope. It would als...
# Theil-Sen regression # Set up plots fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(16, 8)) # Loop over sites for idx, site in enumerate(['LITTLE - WOODFORD', 'PARTRIDGE POND']): # Get data df2 = df[site].reset_index() # Drop NaNs df2.dropna(how='any', inplace='True') # Get quantiles ...
check_trend_signif.ipynb
JamesSample/icpw
mit
Next, a function that extracts the net rating for a team.
def team_net_ratings(the_team_name): """ team name is one of ["76ers", "Bucks", "Bulls", "Cavaliers", "Celtics", "Clippers", "Grizzlies", "Hawks", "Heat", "Hornets", "Jazz", "Kings", "Knicks", "Lakers", "Magic", "Mavericks", "Nets", "Nuggets", "Pacers", "Pelicans", "Pistons", "Raptors",...
basic-stats/nba-games-net-rating-boxplots/NbaTeamGameNetRatingsPlots.ipynb
krosaen/ml-study
mit
The Pistons With this, we can make a histogram of the net ratings for a team. I like the Pistons, so let's check them out:
import matplotlib.mlab as mlab plt.hist(team_net_ratings('Pistons'), bins=15) plt.title("Pistons Net Rating for 2015/2016 Games") plt.xlabel("Net Rating") plt.ylabel("Num Games") plt.show()
basic-stats/nba-games-net-rating-boxplots/NbaTeamGameNetRatingsPlots.ipynb
krosaen/ml-study
mit
As experienced as a fan this year, we are a bit bi-modal, sometimes playing great, even beating some of the leagu's best teams, other times getting blown out (that -40 net rating was most recently against The Wizards). Best and worst teams Now let's compare this to the best and worst teams in the league
plt.hist(team_net_ratings("Warriors"), bins=15, color='b', label='Warriors') plt.hist(team_net_ratings("76ers"), bins=15, color='r', alpha=0.5, label='76ers') plt.title("Net Rating for 2015/2016 Games") plt.xlabel("Net Rating") plt.ylabel("Num Games") plt.legend() plt.show()
basic-stats/nba-games-net-rating-boxplots/NbaTeamGameNetRatingsPlots.ipynb
krosaen/ml-study
mit
Yep, the warriors usually win, and the 76ers usually lose. Still striking to see how many games the warriors win by a safe margin. Box Plots Box plots are a nice way to visually compare multiple team's distributions giving a quick snapshot of the median, range and interquartile range. Let's compare the top 9 seeds in t...
def box_plot_teams(team_names): reversed_names = list(reversed(team_names)) data = [team_net_ratings(team_name) for team_name in reversed_names] plt.figure() plt.xlabel('Game Net Ratings') plt.boxplot(data, labels=reversed_names, vert=False) plt.show() box_plot_teams(['Cavaliers', 'Raptors'...
basic-stats/nba-games-net-rating-boxplots/NbaTeamGameNetRatingsPlots.ipynb
krosaen/ml-study
mit
We can see that The Pistons have the largest spread, but have a median slightly better than The Bulls (they are in fact neck and neck) with potentially more upside. The 3rd quartile net rating of close to 10 is what makes us Pistons fans feel like we could have a shot against most teams in The Eastern Conference. Anoth...
def mean_std(team_name): nrs = team_net_ratings(team_name) return (team_name, np.mean(nrs), np.std(nrs)) [mean_std(team_name) for team_name in ['Cavaliers', 'Raptors', 'Celtics', 'Heat', 'Hawks', 'Hornets', 'Pacers', 'Bulls', 'Pistons']]
basic-stats/nba-games-net-rating-boxplots/NbaTeamGameNetRatingsPlots.ipynb
krosaen/ml-study
mit
Let's have a look at the dataset we just created using our trusty friend, Matplotlib:
import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
I'm sure this is getting easier every time. We use scatter to create a scatter plot of all $x$ values (X[:, 0]) and $y$ values (X[:, 1]), which will result in the following output:
plt.figure(figsize=(10, 6)) plt.scatter(X[:, 0], X[:, 1], c=y, s=50);
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
In agreement with our specifications, we see two different point clusters. They hardly overlap, so it should be relatively easy to classify them. What do you think—could a linear classifier do the job? Yes, it could. Recall that a linear classifier would try to draw a straight line through the figure, trying to put all...
import numpy as np from sklearn import model_selection as ms X_train, X_test, y_train, y_test = ms.train_test_split( X.astype(np.float32), y, test_size=0.1 )
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Classifying the data with a normal Bayes classifier We will then use the same procedure as in earlier chapters to train a normal Bayes classifier. Wait, why not a naive Bayes classifier? Well, it turns out OpenCV doesn't really provide a true naive Bayes classifier... Instead, it comes with a Bayesian classifier that d...
import cv2 model_norm = cv2.ml.NormalBayesClassifier_create()
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Then, training is done via the train method:
model_norm.train(X_train, cv2.ml.ROW_SAMPLE, y_train)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Once the classifier has been trained successfully, it will return True. We go through the motions of predicting and scoring the classifier, just like we have done a million times before:
_, y_pred = model_norm.predict(X_test) from sklearn import metrics metrics.accuracy_score(y_test, y_pred)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Even better—we can reuse the plotting function from the last chapter to inspect the decision boundary! If you recall, the idea was to create a mesh grid that would encompass all data points and then classify every point on the grid. The mesh grid is created via the NumPy function of the same name:
def plot_decision_boundary(model, X_test, y_test): # create a mesh to plot in h = 0.02 # step size in mesh x_min, x_max = X_test[:, 0].min() - 1, X_test[:, 0].max() + 1 y_min, y_max = X_test[:, 1].min() - 1, X_test[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), ...
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
So far, so good. The interesting part is that a Bayesian classifier also returns the probability with which each data point has been classified:
ret, y_pred, y_proba = model_norm.predictProb(X_test)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
The function returns a Boolean flag (True for success, False for failure), the predicted target labels (y_pred), and the conditional probabilities (y_proba). Here, y_proba is an $N \times 2$ matrix that indicates, for every one of the $N$ data points, the probability with which it was classified as either class 0 or cl...
y_proba.round(2)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Classifying the data with a naive Bayes classifier We can compare the result to a true naïve Bayes classifier by asking scikit-learn for help:
from sklearn import naive_bayes model_naive = naive_bayes.GaussianNB()
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
As usual, training the classifier is done via the fit method:
model_naive.fit(X_train, y_train)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Scoring the classifier is built in:
model_naive.score(X_test, y_test)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Again a perfect score! However, in contrast to OpenCV, this classifier's predict_proba method returns true probability values, because all values are between 0 and 1, and because all rows add up to 1:
yprob = model_naive.predict_proba(X_test) yprob.round(2)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
You might have noticed something else: This classifier has absolutely no doubt about the target label of each and every data point. It's all or nothing. The decision boundary returned by the naive Bayes classifier looks slightly different, but can be considered identical to the previous command for the purpose of this ...
plt.figure(figsize=(10, 6)) plot_decision_boundary(model_naive, X, y)
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
Visualizing conditional probabilities Similarly, we can also visualize probabilities. For this, we slightly modify the plot function from the previous example. We start out by creating a mesh grid between (x_min, x_max) and (y_min, y_max):
def plot_proba(model, X_test, y_test): # create a mesh to plot in h = 0.02 # step size in mesh x_min, x_max = X_test[:, 0].min() - 1, X_test[:, 0].max() + 1 y_min, y_max = X_test[:, 1].min() - 1, X_test[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.ara...
notebooks/07.01-Implementing-Our-First-Bayesian-Classifier.ipynb
mbeyeler/opencv-machine-learning
mit
To get started, make sure all of the folloing import statements work without error. You should get a message telling you there are 59 layers in the network and 7548 channels.
from __future__ import print_function from io import BytesIO import math, time, copy, json, os import glob from os import listdir from os.path import isfile, join from random import random from io import BytesIO from enum import Enum from functools import partial import PIL.Image from IPython.display import clear_outpu...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Let's inspect the network now. The following will give us the name of all the layers in the network, as well as the number of channels they contain. We can use this as a lookup table when selecting channels.
for l, layer in enumerate(layers): layer = layer.split("/")[1] num_channels = T(layer).shape[3] print(layer, num_channels)
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
The basic idea is to take any image as input, then iteratively optimize its pixels so as to maximally activate a particular channel (feature extractor) in a trained convolutional network. We reproduce tensorflow's recipe here to read the code in detail. In render_naive, we take img0 as input, then for iter_n steps, we ...
def render_naive(t_obj, img0, iter_n=20, step=1.0): t_score = tf.reduce_mean(t_obj) # defining the optimization objective t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation! img = img0.copy() for i in range(iter_n): g, score = sess.run([t_grad, t_score], {...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now let's try running it. First, we initialize a 200x200 block of colored noise. We then select the layer mixed4d_5x5_bottleneck_pre_relu and the 20th channel in that layer as the objective, and run it through render_naive for 40 iterations. You can try to optimize at different layers or different channels to get a fee...
img0 = np.random.uniform(size=(200, 200, 3)) + 100.0 layer = 'mixed4d_3x3_bottleneck_pre_relu' channel = 140 img1 = render_naive(T(layer)[:,:,:,channel], img0, 40, 1.0) display_image(img1)
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
The above isn't so interesting yet. One improvement is to use repeated upsampling to effectively detect features at multiple scales (what we call "octaves") of the image. What we do is we start with a smaller image and calculate the gradients for that, going through the procedure like before. Then we upsample it by a p...
def render_multiscale(t_obj, img0, iter_n=10, step=1.0, octave_n=3, octave_scale=1.4): t_score = tf.reduce_mean(t_obj) # defining the optimization objective t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation! img = img0.copy() for octave in range(octave_n): ...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Let's try this on noise first. Note the new variables octave_n and octave_scale which control the parameters of the scaling. Thanks to tensorflow's patch to do the process on overlapping subrectangles, we don't have to worry about running out of memory. However, making the overall size large will mean the process takes...
h, w = 200, 200 octave_n = 3 octave_scale = 1.4 iter_n = 50 img0 = np.random.uniform(size=(h, w, 3)) + 100.0 layer = 'mixed4c_5x5_bottleneck_pre_relu' channel = 20 img1 = render_multiscale(T(layer)[:,:,:,channel], img0, iter_n, 1.0, octave_n, octave_scale) display_image(img1)
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now load a real image and use that as the starting point. We'll use the kitty image in the assets folder. Here is the original. <img src="../assets/kitty.jpg" alt="kitty" style="width: 280px;"/>
h, w = 320, 480 octave_n = 3 octave_scale = 1.4 iter_n = 60 img0 = load_image('../assets/kitty.jpg', h, w) layer = 'mixed4d_5x5_bottleneck_pre_relu' channel = 21 img1 = render_multiscale(T(layer)[:,:,:,channel], img0, iter_n, 1.0, octave_n, octave_scale) display_image(img1)
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now we introduce Laplacian normalization. The problem is that although we are finding features at multiple scales, it seems to have a lot of unnatural high-frequency noise. We apply a Laplacian pyramid decomposition to the image as a regularization technique and calculate the pixel gradient at each scale, as before.
def render_lapnorm(t_obj, img0, iter_n=10, step=1.0, oct_n=3, oct_s=1.4, lap_n=4): t_score = tf.reduce_mean(t_obj) # defining the optimization objective t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation! # build the laplacian normalization graph lap_norm_func = t...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
With Laplacian normalization and multiple octaves, we have the core technique finished and are level with the Tensorflow example. Try running the example below and modifying some of the numbers to see how it affects the result. Remember you can use the layer lookup table at the top of this notebook to recall the differ...
h, w = 300, 400 octave_n = 3 octave_scale = 1.4 iter_n = 20 img0 = np.random.uniform(size=(h, w, 3)) + 100.0 layer = 'mixed5b_pool_reduce_pre_relu' channel = 99 img1 = render_lapnorm(T(layer)[:,:,:,channel], img0, iter_n, 1.0, octave_n, octave_scale) display_image(img1)
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now we are going to modify the render_lapnorm function in three ways. 1) Instead of passing just a single channel or layer to be optimized (the objective, t_obj), we can pass several in an array, letting us optimize several channels simultaneously (it must be an array even if it contains just one element). 2) We now a...
def lapnorm_multi(t_obj, img0, mask, iter_n=10, step=1.0, oct_n=3, oct_s=1.4, lap_n=4, clear=True): mask_sizes = get_mask_sizes(mask.shape[0:2], oct_n, oct_s) img0 = resize(img0, np.int32(mask_sizes[0])) t_score = [tf.reduce_mean(t) for t in t_obj] # defining the optimization objective t_grad = [tf.gra...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Try first on noise, as before. This time, we pass in two objectives from different layers and we create a mask where the top half only lets in the first channel, and the bottom half only lets in the second.
h, w = 300, 400 octave_n = 3 octave_scale = 1.4 iter_n = 15 img0 = np.random.uniform(size=(h, w, 3)) + 100.0 objectives = [T('mixed3a_3x3_pre_relu')[:,:,:,79], T('mixed5a_1x1_pre_relu')[:,:,:,200], T('mixed4b_5x5_bottleneck_pre_relu')[:,:,:,22]] # mask mask = np.zeros((h, w, 3)) mask[0:1...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now the same thing, but we optimize over the kitty instead and pick new channels.
h, w = 400, 400 octave_n = 3 octave_scale = 1.4 iter_n = 30 img0 = load_image('../assets/kitty.jpg', h, w) objectives = [T('mixed4d_3x3_bottleneck_pre_relu')[:,:,:,99], T('mixed5a_5x5_bottleneck_pre_relu')[:,:,:,40]] # mask mask = np.zeros((h, w, 2)) mask[:,:200,0] = 1.0 mask[:,200:,1] = 1.0 img1 = l...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Let's make a more complicated mask. Here we use numpy's linspace function to linearly interpolate the mask between 0 and 1, going from left to right, in the first channel's mask, and the opposite for the second channel. Thus on the far left of the image, we let in only the second channel, on the far right only the firs...
h, w = 256, 1024 img0 = np.random.uniform(size=(h, w, 3)) + 100.0 octave_n = 3 octave_scale = 1.4 objectives = [T('mixed4c_3x3_pre_relu')[:,:,:,50], T('mixed4d_5x5_bottleneck_pre_relu')[:,:,:,29]] mask = np.zeros((h, w, 2)) mask[:,:,0] = np.linspace(0,1,w) mask[:,:,1] = np.linspace(1,0,w) img1 = la...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
One can think up many clever ways to make masks. Maybe they are arranged as overlapping concentric circles, or along diagonal lines, or even using Perlin noise to get smooth organic-looking variation. Here is one example making a circular mask.
h, w = 500, 500 cy, cx = 0.5, 0.5 # circle masks pts = np.array([[[i/(h-1.0),j/(w-1.0)] for j in range(w)] for i in range(h)]) ctr = np.array([[[cy, cx] for j in range(w)] for i in range(h)]) pts -= ctr dist = (pts[:,:,0]**2 + pts[:,:,1]**2)**0.5 dist = dist / np.max(dist) mask = np.ones((h, w, 2)) mask[:, :, 0] = ...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now we show how to use an existing image as a set of masks, using k-means clustering to segment it into several sections which become masks.
import sklearn.cluster k = 3 h, w = 320, 480 img0 = load_image('../assets/kitty.jpg', h, w) imgp = np.array(list(img0)).reshape((h*w, 3)) clusters, assign, _ = sklearn.cluster.k_means(imgp, k) assign = assign.reshape((h, w)) mask = np.zeros((h, w, k)) for i in range(k): mask[:,:,i] = np.multiply(np.ones((h, w)),...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Now, we move on to generating video. The most straightforward way to do this is using feedback; generate one image in the conventional way, and then use it as the input to the next generation, rather than starting with noise again. By itself, this would simply repeat or intensify the features found in the first image, ...
h, w = 200, 200 # start with random noise img = np.random.uniform(size=(h, w, 3)) + 100.0 octave_n = 3 octave_scale = 1.4 objectives = [T('mixed4d_5x5_bottleneck_pre_relu')[:,:,:,11]] mask = np.ones((h, w, 1)) # repeat the generation loop 20 times. notice the feedback -- we make img and then use it the initial input...
examples/dreaming/neural-synth.ipynb
ml4a/ml4a-guides
gpl-2.0
Patches The fill attribute of the Lines mark allows us to fill a path in different ways, while the fill_colors attribute lets us control the color of the fill
sc_x = LinearScale() sc_y = LinearScale() patch = Lines(x=[[0, 2, 1.2, np.nan, np.nan, np.nan, np.nan], [0.5, 2.5, 1.7, np.nan, np.nan, np.nan, np.nan], [4,5,6, 6, 5, 4, 3]], y=[[0, 0, 1 , np.nan, np.nan, np.nan, np.nan], [0.5, 0.5, -0.5, np.nan, np.nan, np.nan, np.nan], [1, 1.1, 1.2, 2.3, 2.2, 2.7, 1....
examples/Marks/Object Model/Lines.ipynb
SylvainCorlay/bqplot
apache-2.0
Observation - from the report contents page, I can navigate via the Back button to https://publications.parliament.uk/pa/cm201516/cmselect/cmwomeq/584/58401.htm but then it's not clear where I am at all? It would probably make sense to be able to get back to the inquiry page for the inquiry that resulted in the report.
import pandas as pd
notebooks/Committee Reports.ipynb
psychemedia/parlihacks
mit
Report Contents Page Link Scraper
import requests import requests_cache requests_cache.install_cache('parli_comm_cache') from bs4 import BeautifulSoup #https://www.dataquest.io/blog/web-scraping-tutorial-python/ page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') #What does a ToC item look like? soup.select('p[class*="ToC"]')[...
notebooks/Committee Reports.ipynb
psychemedia/parlihacks
mit
Report - Page Scraper For each HTML Page in the report, extract references to oral evidence session questions and written evidence.
pagesoup=BeautifulSoup(r.content, 'html.parser') print(str(pagesoup.select('div[id="shellcontent"]')[0])[:2000]) import re def evidenceRef(pagesoup): qs=[] ws=[] #Grab list of questions for p in pagesoup.select('div[class="_idFootnote"]'): #Find oral question numbers q=re.search(r'^.*\...
notebooks/Committee Reports.ipynb
psychemedia/parlihacks
mit
Report - Oral Session Page Scraper Is this reliably cribbed by link text Witnesses?
#url='https://publications.parliament.uk/pa/cm201516/cmselect/cmwomeq/584/58414.htm' if url_witnesses is not None: r=requests.get('{}/{}'.format(stub[0],url_witnesses)) pagesoup=BeautifulSoup(r.content, 'html.parser') l1=[t.text.split('\t')[0] for t in pagesoup.select('h2[class="WitnessHeading"]')] ...
notebooks/Committee Reports.ipynb
psychemedia/parlihacks
mit
Report - Written Evidence Scraper Is this reliably cribbed by link text Published written evidence?
#url='https://publications.parliament.uk/pa/cm201516/cmselect/cmwomeq/584/58415.htm' all_written=[] if url_written is not None: r=requests.get('{}/{}'.format(stub[0],url_written)) pagesoup=BeautifulSoup(r.content, 'html.parser') for p in pagesoup.select('p[class="EvidenceList1"]'): #print(p) ...
notebooks/Committee Reports.ipynb
psychemedia/parlihacks
mit