Skip to content

Instantly share code, notes, and snippets.

@aydun1
Last active July 17, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aydun1/932f526867f7f8139b8e8eae7c76e866 to your computer and use it in GitHub Desktop.
Save aydun1/932f526867f7f8139b8e8eae7c76e866 to your computer and use it in GitHub Desktop.
Reproducibility of CRISPR-Cas9 Methods for generation of conditional mouse alleles: a multi-center evaluation
The MIT License
Copyright 2019 Aidan O'Brien
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
import numpy as np
import pandas as pd
import re
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import StratifiedKFold
from sklearn.utils import compute_class_weight
## This should be an Excel file with the following columns:
## guide_5prime, guide_3prime, donor_5prime, donor_3prime, correctly_targeted
input_file = 'data/gbio/combined.xlsx'
## The name of the column with the label
label = 'correctly_targeted'
# Number of trees to build
trees = 2000
## Some constants. These shouldn't be changed
nucleotides = ['A', 'T', 'C', 'G']
dinucleotides = [i + j for i in nucleotides for j in nucleotides]
allnucleotides = nucleotides + dinucleotides
## Function that takes a nucleotide sequence and returns counts of nucleotides
def tokenize_sequence_global(seq, name):
data = {n: int(sum(1 for i in range(len(seq)) if seq.startswith(n, i)) / (len(seq) - len(n) + 1) * 100) for n in allnucleotides}
s = pd.Series(data)
s = s.reindex(allnucleotides, axis=1)
s.index = ['{}_{}'.format(name, x) for x in s.index]
return s
## Read the Excel file
df = pd.read_excel(input_file)
## Tokenise the samples
guide_3prime = df.apply(lambda _: tokenize_sequence_global(_['guide_3prime'][:20], 'guide_3prime'), axis=1)
guide_5prime = df.apply(lambda _: tokenize_sequence_global(_['guide_5prime'][:20], 'guide_5prime'), axis=1)
donor_3prime = df.apply(lambda _: tokenize_sequence_global(_['donor_3prime'][:20], 'donor_3prime'), axis=1)
donor_5prime = df.apply(lambda _: tokenize_sequence_global(_['donor_5prime'][:20], 'donor_5prime'), axis=1)
donor_3prime_length = df.apply(lambda _: pd.Series({'donor_3prime_length': len(_['donor_3prime'])}), axis=1)
donor_5prime_length = df.apply(lambda _: pd.Series({'donor_5prime_length': len(_['donor_5prime'])}), axis=1)
## Define the feature matrix (X) and label array (y)
X = pd.concat([guide_3prime, guide_5prime, donor_3prime, donor_5prime, donor_3prime_length, donor_5prime_length], axis=1)
y = df['correctly_targeted'] > 0
## Used for the imbalanced classes
class_weights = dict(zip(np.unique(y), compute_class_weight('balanced', np.unique(y), y)))
## Define the Random Forest model
rf = RandomForestClassifier(
n_estimators=trees,
oob_score=True,
max_features="sqrt",
class_weight = class_weights,
n_jobs=2
)
## Train the Random Forest model
rf.fit(X, y)
## Print the OOB Error
print('OOB error: {}'.format(1 - rf.oob_score_))
## Print the top 10 features, ranked by feature importance
print('Top 10 features:')
for i in sorted([f for f in zip(list(X), rf.feature_importances_)], key=lambda t: t[1], reverse=True)[:10]:
print('{}, {}'.format(i[0], i[1]))
## Print OOB scores for each cross-validation fold
print('Cross validated OOB errors')
for i, fold in enumerate(StratifiedKFold(5).split(X, y)):
train_X = X.iloc[fold[0], :]
train_y = y.iloc[fold[0]]
test_X = X.iloc[fold[1], :]
test_y = y.iloc[fold[1]]
rf.fit(train_X, train_y)
pred_y = rf.predict(test_X)
print('Fold {}:'.format(i + 1))
print('Error: {}'.format(1 - rf.oob_score_))
print(confusion_matrix(test_y, pred_y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment