markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
3. (3 pts) Generate a series of four 3D scatter plots at selected time points to visually convey what is going on. Arrange the plots in a single row from left to right. Make sure you indicate which time points you are showing.
import matplotlib.pyplot as plt from mpl_toolkits import mplot3d lim = 70 plt.figure(figsize=(12,3)) for (i,t) in enumerate([0, 100, 1000, 1999]): ax = plt.subplot(1, 4, i+1, projection='3d') x = positions[:,0,t] y = positions[:,1,t] z = positions[:,2,t] ax.scatter(x, y, z) plt.xlim([-lim, lim]...
_____no_output_____
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021
4. (3 pts) Draw the path of a single particle (your choice) across all time steps in a 3D plot.
ax = plt.subplot(1, 1, 1, projection='3d') i = 10 # particle index x = positions[i,0,:] y = positions[i,1,:] z = positions[i,2,:] plt.plot(x, y, z) plt.xlabel("x") plt.ylabel("y") ax.set_zlabel("z") plt.title(f"Particle {i}");
_____no_output_____
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021
5. (3 pts) Find the minimum, maximum, mean and variance for the jump distances of all particles throughout the entire simulation. Jump distance is the euclidean distance moved on each time step $\sqrt(dx^2+dy^2+dz^2)$. *Hint: numpy makes this very simple.*
jumpsXYZForAllParticlesAndAllTimeSteps = positions[:,:,1:] - positions[:,:,:-1] jumpDistancesForAllParticlesAndAllTimeSteps = np.sqrt(np.sum(jumpsXYZForAllParticlesAndAllTimeSteps**2, axis=1)) print(f"min = {jumpDistancesForAllParticlesAndAllTimeSteps.min()}") print(f"max = {jumpDistancesForAllParticlesAndAllTimeSteps...
min = 0.0052364433932233926 max = 1.7230154410954457 mean = 0.9602742572616196 var = 0.07749699927626445
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021
6. (3 pts) Repeat the simulation, but this time confine the particles to a unit cell of dimension 10x10x10. Make it so that if a particle leaves one edge of the cell, it enters on the opposite edge (this is the sort of thing most molecular dynamics simulations do). Show plots as in 3 to visualize the simulation (note t...
for t in range(numTimeSteps-1): # 2 * [0 to 1] - 1 --> [-1 to 1] jumpsForAllParticles = 2 * np.random.random((numParticles, 3)) - 1 positions[:,:,t+1] = positions[:,:,t] + jumpsForAllParticles # check for out-of-bounds and warp to opposite bound for i in range(numParticles): for j in range(3...
_____no_output_____
Unlicense
homework/key-random_walks.ipynb
nishadalal120/NEU-365P-385L-Spring-2021
- 使用ngram进行恶意域名识别- 参考论文:https://www.researchgate.net/publication/330843380_Malicious_Domain_Names_Detection_Algorithm_Based_on_N_-Gram
import numpy as np import pandas as pd import tldextract import matplotlib.pyplot as plt import os import re import time from scipy import sparse %matplotlib inline
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
加载数据 - 加载正常域名
df_benign_domain = pd.read_csv('top-1m.csv', index_col=0, header=None).reset_index(drop=True) df_benign_domain.columns = ['domain'] df_benign_domain['label'] = 0
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
- 加载恶意域名
df_malicious_domain = pd.read_csv('malicious-domain.csv', engine='python', header=None) df_malicious_domain = df_malicious_domain[[1]] df_malicious_domain.columns = ['domain'] df_malicious_domain = df_malicious_domain[df_malicious_domain['domain'] != '-'] df_malicious_domain['label'] = 1 df_domain = pd.concat([df_benig...
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
提取ngram特征
from sklearn.feature_extraction.text import CountVectorizer domain_list = df_domain[df_domain['label'] == 0]['domain'].values.tolist() benign_text_str = '.'.join(domain_list) benign_text = re.split(r'[.-]', benign_text_str) benign_text = list(filter(lambda x: len(x) >= 3, benign_text)) def get_ngram_weight_dict(benign_...
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
计算域名的信誉值
def get_reputation_value(ngram_weights_dict, domain): if len(domain) < 3: return 1000 domains = re.split(r'[.-]', domain) reputation = 0 domain_len = 0 for domain in domains: domain_len += len(domain) for window_size in range(3, 8): for i in range(len(domain) - wi...
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
保存模型文件
import joblib joblib.dump(ngram_weights_dict, 'ngram_weights_dict.m', compress=4)
_____no_output_____
MIT
malicious_domain_detect.ipynb
aierwiki/ngram-detection
Another attempt at MC Simulation on AHP/ANP The ideas are the following:1. There is a class MCAnp that has a sim() method that will simulate any Prioritizer2. MCAnp also has a sim_fill() function that does fills in the data needed for a single simulation Import needed libs
import pandas as pd import sys import os sys.path.insert(0, os.path.abspath("../")) import numpy as np from scipy.stats import triang from copy import deepcopy from pyanp.priority import pri_eigen from pyanp.pairwise import Pairwise from pyanp.ahptree import AHPTree, AHPTreeNode from pyanp.direct import Direct
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
MCAnp class
def ascale_mscale(val:(float,int))->float: if val is None: return 0 elif val < 0: val = -val val += 1 val = 1.0/val return val else: return val+1 def mscale_ascale(val:(float,int))->float: if val == 0: return None elif val >= 1: re...
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
Checking that the deep copy is actually a deep copyFor some reason deepcopy was not copying the matrix, I had to overwrite__deepcopy__ in Pairwise
pwobj.matrix('u1') rpwobj = pwobj.__deepcopy__() a=rpwobj b=pwobj a.df display(a.df.loc['u1', 'Matrix']) display(b.df.loc['u1', 'Matrix']) display(a.matrix('u1') is b.matrix('u1')) display(a.matrix('u1') == b.matrix('u1'))
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
Now let's try to simulate
[mc.sim_pw(pwobj, rpwobj) for i in range(20)] pwobj.matrix('u1')
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
Try to simulate a direct data
dd = Direct(alt_names=['a1', 'a2', 'a3']) dd.data[0]=0.5 dd.data[1]=0.3 dd.data[2]=0.2 rdd=mc.sim_direct_fill(dd) rdd.data
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
Simulate an ahptree
alts=['alt '+str(i) for i in range(3)] tree = AHPTree(alt_names=alts) kids = ['crit '+str(i) for i in range(4)] for kid in kids: tree.add_child(kid) node = tree.get_node(kid) direct = node.alt_prioritizer s = 0 for alt in alts: direct[alt] = np.random.uniform() s += direct[alt] ...
_____no_output_____
MIT
scrap/MCAnpResearch.ipynb
georg-cantor/pyanp
Laboratorio 5 Datos: _European Union lesbian, gay, bisexual and transgender survey (2012)_Link a los datos [aquí](https://www.kaggle.com/ruslankl/european-union-lgbt-survey-2012). ContextoLa FRA (Agencia de Derechos Fundamentales) realizó una encuesta en línea para identificar cómo las personas lesbianas, gays, bisex...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline daily_life_raw = pd.read_csv(os.path.join("..", "data", "LGBT_Survey_DailyLife.csv")) daily_life_raw.head() daily_life_raw.info() daily_life_raw.describe(include="all").T questions = ( daily_life_raw.loc[: , ["quest...
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Preprocesamiento de datos ¿Te fijaste que la columna `percentage` no es numérica? Eso es por los registros con notes `[1]`, por lo que los eliminaremos.
daily_life_raw.notes.unique() daily_life = ( daily_life_raw.query("notes != ' [1] '") .astype({"percentage": "int"}) .drop(columns=["question_label", "notes"]) .rename(columns={"CountryCode": "country"}) ) daily_life.head()
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Ejercicio 1(1 pto)¿A qué tipo de dato (nominal, ordinal, discreto, continuo) corresponde cada columna del DataFrame `daily_life`?Recomendación, mira los valores únicos de cada columna.
daily_life.dtypes # FREE STYLE #
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
__Respuesta:__* `country`: * `subset`: * `question_code`:* `answer`: * `percentage`: Ejercicio 2 (1 pto)Crea un nuevo dataframe `df1` tal que solo posea registros de Bélgica, la pregunta con código `b1_b` y que hayan respondido _Very widespread_.Ahora, crea un gráfico de barras vertical con la función `bar` de `matpl...
print(f"Question b1_b:\n\n{questions['b1_b']}") df1 = # FIX ME # df1 x = # FIX ME # y = # FIX ME # fig = plt.figure(# FIX ME #) plt# FIX ME # plt.show()
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Ejercicio 3(1 pto)Respecto a la pregunta con código `g5`, ¿Cuál es el porcentaje promedio por cada valor de la respuesta (notar que la respuestas a las preguntas son numéricas)?
print(f"Question g5:\n\n{questions['g5']}")
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Crea un DataFrame llamado `df2` tal que:1. Solo sean registros con la pregunta con código `g5`2. Cambia el tipo de la columna `answer` a `int`.3. Agrupa por país y respuesta y calcula el promedio a la columna porcentaje (usa `agg`).4. Resetea los índices.
df2 = ( # FIX ME # ) df2
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Crea un DataFrame llamado `df2_mean` tal que:1. Agrupa `df2` por respuesta y calcula el promedio del porcentaje.2. Resetea los índices.
df2_mean = df2.# FIX ME # df2_mean.head()
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Ahora, grafica lo siguiente:1. Una figura con dos columnas, tamaño de figura 15 x 12 y que compartan eje x y eje y. Usar `plt.subplots`.2. Para el primer _Axe_ (`ax1`), haz un _scatter plot_ tal que el eje x sea los valores de respuestas de `df2`, y el eye y corresponda a los porcentajes de `df2`. Recuerda que en este ...
x = # FIX ME # y = # FIX ME # x_mean = # FIX ME #s y_mean = # FIX ME # fig, (ax1, ax2) = plt.subplots(# FIX ME #) ax1.# FIX ME # ax1.grid(alpha=0.3) ax2.# FIX ME # ax2.grid(alpha=0.3) fig.show()
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Ejercicio 4(1 pto) Respecto a la misma pregunta `g5`, cómo se distribuyen los porcentajes en promedio para cada país - grupo?Utilizaremos el mapa de calor presentado en la clase, para ello es necesario procesar un poco los datos para conformar los elementos que se necesitan.Crea un DataFrame llamado `df3` tal que:1. S...
## Code from: # https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py import numpy as np import matplotlib import matplotlib.pyplot as plt def heatmap(data, row_labels, col_labels, ax=None, cbar_k...
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Finalmente, los ingredientes para el heat map son:
countries = df3.index.tolist() subsets = df3.columns.tolist() answers = df3.values
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
El mapa de calor debe ser de la siguiente manera:* Tamaño figura: 15 x 20* cmap = "YlGn"* cbarlabel = "Porcentaje promedio (%)"* Precición en las anotaciones: Flotante con dos decimales.
fig, ax = plt.subplots(# FIX ME #) im, cbar = heatmap(# FIX ME #") texts = annotate_heatmap(# FIX ME #) fig.tight_layout() plt.show()
_____no_output_____
BSD-3-Clause
labs/lab05.ipynb
aoguedao/mat281_2020S2
Talktorial 1 Compound data acquisition (ChEMBL) Developed in the CADD seminars 2017 and 2018, AG Volkamer, Charité/FU Berlin Paula Junge and Svetlana Leng Aim of this talktorialWe learn how to extract data from ChEMBL:* Find ligands which were tested on a certain target* Filter by available bioactivity data* Calculat...
from chembl_webresource_client.new_client import new_client import pandas as pd import math from rdkit.Chem import PandasTools
/home/andrea/anaconda2/envs/cadd-py36/lib/python3.6/site-packages/grequests.py:21: MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6. It may also silently lead to incorrect behaviour on Python 3.7. Please monkey-patch earlier. See http...
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Create resource objects for API access.
targets = new_client.target compounds = new_client.molecule bioactivities = new_client.activity
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Target data* Get UniProt-ID (http://www.uniprot.org/uniprot/P00533) of the target of interest (EGFR kinase) from UniProt website (https://www.uniprot.org/)* Use UniProt-ID to get target information* Select a different UniProt-ID if you are interested into another target
uniprot_id = 'P00533' # Get target information from ChEMBL but restrict to specified values only target_P00533 = targets.get(target_components__accession=uniprot_id) \ .only('target_chembl_id', 'organism', 'pref_name', 'target_type') print(type(target_P00533)) pd.DataFrame.from_records(target_P00...
<class 'chembl_webresource_client.query_set.QuerySet'>
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
After checking the entries, we select the first entry as our target of interest`CHEMBL203`: It is a single protein and represents the human Epidermal growth factor receptor (EGFR, also named erbB1)
target = target_P00533[0] target
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Save selected ChEMBL-ID.
chembl_id = target['target_chembl_id'] chembl_id
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Bioactivity dataNow, we want to query bioactivity data for the target of interest. Download and filter bioactivities for the target In this step, we download and filter the bioactivity data and only consider* human proteins* bioactivity type IC50* exact measurements (relation '=') * binding data (assay type 'B')
bioact = bioactivities.filter(target_chembl_id = chembl_id) \ .filter(type = 'IC50') \ .filter(relation = '=') \ .filter(assay_type = 'B') \ .only('activity_id','assay_chembl_id', 'assay_description', 'assay_type', \ ...
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
If you experience difficulties to query the ChEMBL database, we provide here a file containing the results for the query in the previous cell (11 April 2019). We do this using the Python package pickle which serializes Python objects so they can be saved to a file, and loaded in a program again later on.(Learn more abo...
#import pickle #bioact = pickle.load(open("../data/T1/EGFR_compounds_from_chembl_query_20190411.p", "rb"))
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Clean and convert bioactivity dataThe data is stored as a list of dictionaries
bioact[0]
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Convert to pandas dataframe (this might take some minutes).
bioact_df = pd.DataFrame.from_records(bioact) bioact_df.head(10) bioact_df.shape
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Delete entries with missing values.
bioact_df = bioact_df.dropna(axis=0, how = 'any') bioact_df.shape
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Delete duplicates:Sometimes the same molecule (`molecule_chembl_id`) has been tested more than once, in this case, we only keep the first one.
bioact_df = bioact_df.drop_duplicates('molecule_chembl_id', keep = 'first') bioact_df.shape
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
We would like to only keep bioactivity data measured in molar units. The following print statements will help us to see what units are contained and to control what is kept after dropping some rows.
print(bioact_df.units.unique()) bioact_df = bioact_df.drop(bioact_df.index[~bioact_df.units.str.contains('M')]) print(bioact_df.units.unique()) bioact_df.shape
['uM' 'nM' 'M' "10'1 ug/ml" 'ug ml-1' "10'-1microM" "10'1 uM" "10'-1 ug/ml" "10'-2 ug/ml" "10'2 uM" '/uM' "10'-6g/ml" 'mM' 'umol/L' 'nmol/L'] ['uM' 'nM' 'M' "10'-1microM" "10'1 uM" "10'2 uM" '/uM' 'mM']
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Since we deleted some rows, but we want to iterate over the index later, we reset index to be continuous.
bioact_df = bioact_df.reset_index(drop=True) bioact_df.head()
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
To allow further comparison of the IC50 values, we convert all units to nM. First, we write a helper function, which can be applied to the whole dataframe in the next step.
def convert_to_NM(unit, bioactivity): # c=0 # for i, unit in enumerate(bioact_df.units): if unit != "nM": if unit == "pM": value = float(bioactivity)/1000 elif unit == "10'-11M": value = float(bioactivity)/100 elif unit == "10'-10M": value = fl...
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Compound dataWe have a data frame containing all molecules tested (with the respective measure) against EGFR. Now, we want to get the molecules that are stored behind the respective ChEMBL IDs. Get list of compoundsLet's have a look at the compounds from ChEMBL we have defined bioactivity data for. First, we retriev...
cmpd_id_list = list(bioact_df['molecule_chembl_id']) compound_list = compounds.filter(molecule_chembl_id__in = cmpd_id_list) \ .only('molecule_chembl_id','molecule_structures')
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Then, we convert the list to a pandas dataframe and delete duplicates (again, the pandas from_records function might take some time).
compound_df = pd.DataFrame.from_records(compound_list) compound_df = compound_df.drop_duplicates('molecule_chembl_id', keep = 'first') print(compound_df.shape) print(bioact_df.shape) compound_df.head()
(4780, 2) (4780, 11)
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
So far, we have multiple different molecular structure representations. We only want to keep the canonical SMILES.
for i, cmpd in compound_df.iterrows(): if compound_df.loc[i]['molecule_structures'] != None: compound_df.loc[i]['molecule_structures'] = cmpd['molecule_structures']['canonical_smiles'] print (compound_df.shape)
(4780, 2)
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Prepare output data Merge values of interest in one dataframe on ChEMBL-IDs:* ChEMBL-IDs* SMILES* units* IC50
output_df = pd.merge(bioact_df[['molecule_chembl_id','units','value']], compound_df, on='molecule_chembl_id') print(output_df.shape) output_df.head()
(4780, 4)
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
For distinct column names, we rename IC50 and SMILES columns.
output_df = output_df.rename(columns= {'molecule_structures':'smiles', 'value':'IC50'}) output_df.shape
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
If we do not have a SMILES representation of a compound, we can not further use it in the following talktorials. Therefore, we delete compounds without SMILES column.
output_df = output_df[~output_df['smiles'].isnull()] print(output_df.shape) output_df.head()
(4771, 4)
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
In the next cell, you see that the low IC50 values are difficult to read. Therefore, we prefer to convert the IC50 values to pIC50.
output_df = output_df.reset_index(drop=True) ic50 = output_df.IC50.astype(float) print(len(ic50)) print(ic50.head(10)) # Convert IC50 to pIC50 and add pIC50 column: pIC50 = pd.Series() i = 0 while i < len(output_df.IC50): value = 9 - math.log10(ic50[i]) # pIC50=-log10(IC50 mol/l) --> for nM: -log10(IC50*10**-9)= ...
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Collected bioactivity data for EGFR Let's have a look at our collected data set. Draw moleculesIn the next steps, we add a molecule column to our datafame and look at the structures of the molecules with the highest pIC50 values.
PandasTools.AddMoleculeColumnToFrame(output_df, smilesCol='smiles')
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Sort molecules by pIC50.
output_df.sort_values(by="pIC50", ascending=False, inplace=True) output_df.reset_index(drop=True, inplace=True)
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Show the most active molecules = molecules with the highest pIC50 values.
output_df.drop("smiles", axis=1).head()
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Write output fileTo use the data for the following talktorials, we save the data as csv file. Note that it is advisable to drop the molecule column (only contains an image of the molecules) when saving the data.
output_df.drop("ROMol", axis=1).to_csv("../data/T1/EGFR_compounds.csv")
_____no_output_____
CC-BY-4.0
talktorials/1_ChEMBL/T1_ChEMBL.ipynb
speleo3/TeachOpenCADD
Making ML Applications with Gradio[Gradio](https://www.gradio.app/) is a python library that provides web interfaces for your models. This library is very high-level with it being the easiest to learn for beginners. Here we use a dataset called [EMNIST](https://pytorch.org/vision/stable/datasets.htmlemnist) which is ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Importing PyTorch import torch import torch.nn as nn # Importing torchvision for dataset import torchvision import torchvision.transforms as transforms # Installing gradio using PIP !pip install gradio
Collecting gradio [?25l Downloading https://files.pythonhosted.org/packages/e4/c6/19d6941437fb56db775b00c0181af81e539c42369bc79c664001d2272ccb/gradio-2.0.5-py3-none-any.whl (1.6MB)  |████████████████████████████████| 1.6MB 5.2MB/s [?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dis...
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Downloading and Preparing EMNIST Dataset**Note:** Even though the images in the EMNIST dataset are 28x28 images just like the regular MNIST dataset, there are necessary transforms needed for EMNIST dataset. If not transformed, the images are rotated 90° counter-clockwise and are flipped vertically. To undo these two i...
# Getting Dataset !mkdir EMNIST root = '/content/EMNIST' # Creating Transforms transforms = transforms.Compose([ # Rotating image 90 degrees counter-clockwise transforms.RandomRotation((-90,-90)), # Flipping images horizontally ...
Downloading and extracting zip archive Downloading https://www.itl.nist.gov/iaui/vip/cs_links/EMNIST/gzip.zip to /content/EMNIST/EMNIST/raw/emnist.zip
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Building the Model
class Neural_Network(nn.Module): # Constructor def __init__(self, num_classes): super(Neural_Network, self).__init__() # Defining Fully-Connected Layers self.fc1 = nn.Linear(28*28, 392) # 28*28 since each image is 28*28 self.fc2 = nn.Linear(392, 196) self.fc3 = nn.Linear...
Neural_Network( (fc1): Linear(in_features=784, out_features=392, bias=True) (fc2): Linear(in_features=392, out_features=196, bias=True) (fc3): Linear(in_features=196, out_features=98, bias=True) (fc4): Linear(in_features=98, out_features=62, bias=True) (relu): ReLU() )
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Defining Loss Function and Optimizer
criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
_____no_output_____
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Moving model to GPUIf you have not changed the runtime type to a GPU, please do so now. This helps with the speed of training.
# Use GPU if available device = "cuda" if torch.cuda.is_available() else "cpu" # Moving model to use GPU model.to(device)
_____no_output_____
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Training the Model
# Function that returns a torch tensor with predictions to compare with labels def get_preds_from_logits(logits): # Using softmax to get an array that sums to 1, and then getting the index with the highest value return torch.nn.functional.softmax(logits, dim=1).argmax(dim=1) epochs = 10 train_losses = [] train_acc...
_____no_output_____
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Evaluating the modelHere we will display the test loss and accuracy and examples of images that were misclassified.
test_loss = 0.0 test_counts = 0 # Setting model to evaluation mode, no parameters will change model.eval() for images, labels in test_dataloader: # Moving to GPU if available images, labels = images.to(device), labels.to(device) # Calculate Output output = model(images) # Calculate Loss los...
_____no_output_____
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
How to use GradioThere are three parts of using Gradio1. Define a function that takes input and returns your model's output2. Define what type of input the interface will use3. Define what type of output the interface will giveThe function `recognize_image` takes a 28x28 image that is not yet normalized and returns a ...
import gradio import gradio as gr # Function that returns a torch tensor with predictions to compare with labels def get_probs_from_logits(logits): # Using softmax to get probabilities from the logits return torch.nn.functional.softmax(logits, dim=1) # Function that takes the img drawn in the Gradio interface, th...
Colab notebook detected. To show errors in colab notebook, set `debug=True` in `launch()` This share link will expire in 24 hours. If you need a permanent link, visit: https://gradio.app/introducing-hosted (NEW!) Running on External URL: https://27407.gradio.app Interface loading below...
MIT
machine_learning/lesson 4 - ML Apps/Gradio/EMNIST_Gradio_Tutorial.ipynb
BreakoutMentors/Data-Science-and-Machine-Learning
Baixando a base de dados do Kaggle
# baixando a lib do kaggle !pip install --upgrade kaggle !pip install plotly # para visualizar dados faltantes !pip install missingno # requisitando upload do token de autentificação do Kaggle # OBS: o arquivo kaggle.json precisa ser baixado da sua conta pessoal do Kaggle. from google.colab import files uploaded = fi...
Downloading covid-world-vaccination-progress.zip to /content 0% 0.00/172k [00:00<?, ?B/s] 100% 172k/172k [00:00<00:00, 20.4MB/s]
MIT
src/projeto_1_ciencia_de_dados.ipynb
Cogitus/covid-vacine-progression-analysis
Código da análise exploratória em si
import pandas as pd import matplotlib.pyplot as plt import missingno as msno import plotly.graph_objects as go import matplotlib.ticker as ticker def gera_lista_vacinas(dataset): ''' Gera uma lista com todas as vacinas do dataset input: DataFrame dos dados output: lista de todas as vacinas ''' t...
_____no_output_____
MIT
src/projeto_1_ciencia_de_dados.ipynb
Cogitus/covid-vacine-progression-analysis
Código da criação dos gráficos e mapas
groupby_country = dataset.groupby(['pais']) listof_dataframe_countries = [] for idx, group in enumerate(groupby_country): listof_dataframe_countries.append(group) total_vac_top_countries = pd.DataFrame() # total_vacinacoes pessoas_vacinadas pessoas_tot_vacinadas for i in range(len(listof_dataframe_countries)): ...
_____no_output_____
MIT
src/projeto_1_ciencia_de_dados.ipynb
Cogitus/covid-vacine-progression-analysis
Backprop Core Example: Text SummarisationText summarisation takes a chunk of text, and extracts the key information.
# Set your API key to do inference on Backprop's platform # Leave as None to run locally api_key = None import backprop summarisation = backprop.Summarisation(api_key=api_key) # Change this up. input_text = """ Britain began its third COVID-19 lockdown on Tuesday with the government calling for one last major national...
Britain begins its third COVID-19 lockdown. Finance minister Rishi Sunak announces a package of business grants. The government is pinning its hopes on vaccines.
Apache-2.0
examples/Summarisation.ipynb
lucky7323/backprop
Jacobian calculation
x = pdt.Var('x') y = pdt.Var('y') gm = pdt.Par('gm') a = pdt.Par('a') b = pdt.Par('b') t = pdt.Var('t') xdot = pdt.Fun(y, [y], 'xdot') ydot = pdt.Fun(-a*gm*gm - b*gm*gm*x -gm*gm*x*x*x -gm*x*x*y + gm*gm*x*x - gm*x*y, [x, y], 'ydot') F = pdt.Fun([xdot(y), ydot(x, y)], [x,y], 'F') jac = pdt.Fun(pdt.Diff(F, [x, y]), [t, x,...
[[0,1],[(((-b*gm*gm)-gm*gm*(x*x+x*2*x))-gm*(x*y+x*y)+gm*gm*2*x)-gm*y,(-gm*x*x)-gm*x]]
MIT
pydstools_implementation.ipynb
gnouveau/birdsynth
Simple model
icdict = {'x': 0, 'y': 0} pardict = { 'gm': 2 # g is γ in Boari 2015 } vardict = { 'x': xdot(y), 'y': ydot(x,y), } args = pdt.args() args.name = 'birdsynth' args.fnspecs = [jac, xdot, ydot] args.ics = icdict args.pars = pardict args.inputs = inputs args.tdata = [0, 1] args.varspecs = vardict ds...
_____no_output_____
MIT
pydstools_implementation.ipynb
gnouveau/birdsynth
05 超参数
import numpy as np from sklearn import datasets digits = datasets.load_digits() X = digits.data y = digits.target from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=666) from sklearn.neighbors import KNeighborsClassifier knn_clf =...
_____no_output_____
Apache-2.0
04-kNN/05-Hyper-Parameters/05-Hyper-Parameters.ipynb
mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms
寻找最好的k
best_score = 0.0 best_k = -1 for k in range(1, 11): knn_clf = KNeighborsClassifier(n_neighbors=k) knn_clf.fit(X_train, y_train) score = knn_clf.score(X_test, y_test) if score > best_score: best_k = k best_score = score print("best_k =", best_k) print("best_score =", best_score)
best_k = 4 best_score = 0.991666666667
Apache-2.0
04-kNN/05-Hyper-Parameters/05-Hyper-Parameters.ipynb
mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms
考虑距离?不考虑距离?
best_score = 0.0 best_k = -1 best_method = "" for method in ["uniform", "distance"]: for k in range(1, 11): knn_clf = KNeighborsClassifier(n_neighbors=k, weights=method) knn_clf.fit(X_train, y_train) score = knn_clf.score(X_test, y_test) if score > best_score: best_k = k ...
_____no_output_____
Apache-2.0
04-kNN/05-Hyper-Parameters/05-Hyper-Parameters.ipynb
mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms
搜索明可夫斯基距离相应的p
best_score = 0.0 best_k = -1 best_p = -1 for k in range(1, 11): for p in range(1, 6): knn_clf = KNeighborsClassifier(n_neighbors=k, weights="distance", p=p) knn_clf.fit(X_train, y_train) score = knn_clf.score(X_test, y_test) if score > best_score: best_k = k ...
best_k = 3 best_p = 2 best_score = 0.988888888889
Apache-2.0
04-kNN/05-Hyper-Parameters/05-Hyper-Parameters.ipynb
mtianyan/Mtianyan-Play-with-Machine-Learning-Algorithms
Bayesian Hierarchical ModelingThis jupyter notebook accompanies the Bayesian Hierarchical Modeling lecture(s) delivered by Stephen Feeney as part of David Hogg's [Computational Data Analysis class](http://dwh.gg/FlatironCDA). As part of the lecture(s) you will be asked to complete a number of tasks, some of which will...
from __future__ import print_function # make sure everything we need is installed if running on Google Colab def is_colab(): try: cfg = get_ipython().config if cfg['IPKernelApp']['kernel_class'] == 'google.colab._kernel.Kernel': return True else: return False exc...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
... and immediately move to... Task 2In which I ask you to write a Python function to generate a simulated Cepheid sample using the period-luminosity relation $m_{ij} = \mu_i + M^* + s\,\log p_{ij} + \epsilon(\sigma_{\rm int})$. For simplicity, assume Gaussian priors on everything, Gaussian intrinsic scatter and Gaussi...
# setup n_gal = 2 n_star = 200 n_samples = 50000 # PL relation parameters abs_bar = -26.0 # mean of standard absolute magnitude prior abs_sig = 4.0 # std dev of standard absolute magnitude prior s_bar = -1.0 # mean of slope prior s_sig = 1.0 # std dev of slope prior mu_bar = 30.0 # mean of distanc...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Let's check that the simulation generates something sane. A simple test that the magnitude measurements errors are correctly generated.
# simulate abs_true, s_true, mu_true, lp_true, m_true, mu_hat, m_hat = \ simulate(n_gal, n_star, abs_bar, abs_sig, s_bar, s_sig, mu_bar, mu_sig, mu_hat_sig, m_sig_int, m_hat_sig) # plot difference between true and observed apparent magnitudes. this should be the # noise, which is Gaussian distributed with mean ze...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
And another test that the intrinsic scatter is added as expected.
# plot difference between true apparent magnitudes and expected apparent # magnitude given a perfect (i.e., intrinsic-scatter-free) period-luminosity # relation. this should be the intrinsic scatter, which is Gaussian- # distributed with mean zero and std dev m_sig_int eps = np.zeros((n_gal, n_star)) for i in range(n...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Generalized Least Squares DemoCoding up the [GLS estimator](https://en.wikipedia.org/wiki/Generalized_least_squares) is a little involved, so I've done it for you below. Note that, rather unhelpfully, I've done so in a different order than in the notes. When I get a chance I will re-write. For now, you can simply eval...
def gls_fit(n_gal, n_star, mu_hat, mu_hat_sig, m_hat, m_sig_int, m_hat_sig, \ lp_true, priors=None): # setup # n_obs is one anchor constraint and one magnitude per Cepheid. # n_par is one mu per Cepheid host and 2 CPL params. if priors # are used, we add on n_gal + 2 observations: one prio...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
In order to plot the outputs of the GLS fit we could draw a large number of samples from the resulting multivariate Gaussian posterior and pass them to something like [`corner`](https://corner.readthedocs.io/en/latest/); however, as we have analytic results we might as well use those directly. I've coded up something t...
# this is a hacky function designed to transform the analytic GLS outputs # into a corner.py style triangle plot, containing 1D and 2D marginalized # posteriors import scipy.stats as sps import matplotlib.patches as mpp def schmorner(par_mean, par_cov, par_true, par_label): # setup par_std = np.sqrt(np.dia...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Task 3BBelow I've written the majority of a Gibbs sampler to infer the hyper-parameters of the Cepheid PL relation from our simulated sample. One component is missing: drawing from the conditional distribution of the standard absolute magnitude, $M^*$. Please fill it in, using the results of whiteboard/paper Task 3A.
def gibbs_sample(n_samples, n_gal, n_star, abs_bar, abs_sig, \ s_bar, s_sig, mu_bar, mu_sig, mu_hat_sig, \ m_sig_int, m_hat_sig, mu_hat, lp_true, m_hat): # storage abs_samples = np.zeros(n_samples) s_samples = np.zeros(n_samples) mu_samples = np.zeros((n_gal, n_sam...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Now let's sample, setting aside the first half of the samples as warmup.
all_samples = gibbs_sample(n_samples, n_gal, n_star, abs_bar, abs_sig, \ s_bar, s_sig, mu_bar, mu_sig, mu_hat_sig, \ m_sig_int, m_hat_sig, mu_hat, lp_true, m_hat) n_warmup = int(n_samples / 2) g_samples = [samples[n_warmup:] for samples in all_samples]
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Let's make sure that the absolute magnitude is being inferred as expected. First, generate a trace plot of the absolute magnitude samples (the first entry in `g_samples`), overlaying the ground truth. Then print out the mean and standard deviation of the marginalized absolute magnitude posterior. Recall that marginaliz...
mp.plot(g_samples[0]) mp.axhline(abs_true) mp.xlabel('sample') mp.ylabel(r'$M^*$') print('Truth {:6.2f}; inferred {:6.2f} +/- {:4.2f}'.format(abs_true, np.mean(g_samples[0]), np.std(g_samples[0])))
Truth -30.95; inferred -30.97 +/- 0.02
MIT
bhms.ipynb
sfeeney/bhm_lecture
Now let's generate some marginalized parameter posteriors (by simply discarding all samples of the latent parameters) using DFM's [`corner`](https://corner.readthedocs.io/en/latest/) package. Note the near identical nature of this plot to the `schmorner` plot we generated above.
import corner samples = np.stack((g_samples[0], g_samples[1])) fig = corner.corner(samples.T, labels=[r"$M^*$", r"$s$"], show_titles=True, truths=[abs_true, s_true])
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Task 4The final task is to write a [Stan model](https://pystan.readthedocs.io/en/latest/getting_started.html) to infer the parameters of the period-luminosity relation. I've coded up the other two blocks required (`data` and `parameters`), so all that is required is for you to write the joint posterior (factorized int...
import sys import pystan as ps import pickle stan_code = """ data { int<lower=0> n_gal; int<lower=0> n_star; real mu_hat; real mu_hat_sig; real m_hat[n_gal, n_star]; real m_hat_sig; real m_sig_int; real lp_true[n_gal, n_star]; real abs_bar; real abs_sig; real s_bar; real...
INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_ab41b39e55c2f57c74acf30e86ea4ea5 NOW.
MIT
bhms.ipynb
sfeeney/bhm_lecture
Now let's sample...
stan_data = {'n_gal': n_gal, 'n_star': n_star, 'mu_hat': mu_hat, 'mu_hat_sig': mu_hat_sig, \ 'm_hat': m_hat, 'm_hat_sig': m_hat_sig, 'm_sig_int': m_sig_int, 'lp_true': lp_true, \ 'abs_bar': abs_bar, 'abs_sig': abs_sig, 's_bar': s_bar, 's_sig': s_sig, \ 'mu_bar': mu_bar, 'mu_sig': ...
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
... print out Stan's posterior summary (note this is for _all_ parameters)...
samples = fit.extract(permuted=True) print(fit)
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
... and plot the marginalized posterior of the PL parameters, as with the Gibbs sampler.
c_samples = np.stack((samples['abs_true'], samples['s_true'])) fig = corner.corner(c_samples.T, labels=[r"$M^*$", r"$s$"], show_titles=True, truths=[abs_true, s_true])
_____no_output_____
MIT
bhms.ipynb
sfeeney/bhm_lecture
Detecting Loops in Linked ListsIn this notebook, you'll implement a function that detects if a loop exists in a linked list. The way we'll do this is by having two pointers, called "runners", moving through the list at different rates. Typically we have a "slow" runner which moves at one node per step and a "fast" run...
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, init_list=None): self.head = None if init_list: for value in init_list: self.append(value) def append(self, value): ...
_____no_output_____
MIT
2/1-3/linked_lists/Detecting Loops.ipynb
ZacksAmber/Udacity-Data-Structure-Algorithms
Write the function definition here**Exercise:** Given a linked list, implement a function `iscircular` that returns `True` if a loop exists in the list and `False` otherwise.
def iscircular(linked_list): """ Determine whether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular, return False otherwise """ # TODO: Write function to check if linked list is circ...
_____no_output_____
MIT
2/1-3/linked_lists/Detecting Loops.ipynb
ZacksAmber/Udacity-Data-Structure-Algorithms
Let's test your function
iscircular(list_with_loop) # Test Cases # Create another circular linked list small_loop = LinkedList([0]) small_loop.head.next = small_loop.head print ("Pass" if iscircular(list_with_loop) else "Fail") # Pass print ("Pass" if iscircular(LinkedList([-4, 7, 2, 5, -1])) else "Fail") # Fail print ("Pa...
Pass Fail Fail Pass Fail
MIT
2/1-3/linked_lists/Detecting Loops.ipynb
ZacksAmber/Udacity-Data-Structure-Algorithms
Normalize> Data normalization methods.
#hide from nbdev.showdoc import * #export def simple_normalize(data, method='minmax', target_column='RATING'): zscore = lambda x: (x - x.mean()) / x.std() minmax = lambda x: (x - x.min()) / (x.max() - x.min()) if method=='minmax': norm = data.groupby('USERID')[target_column].transform(minmax) elif method=...
Author: Sparsh A. Last updated: 2021-12-18 08:35:26 Compiler : GCC 7.5.0 OS : Linux Release : 5.4.104+ Machine : x86_64 Processor : x86_64 CPU cores : 2 Architecture: 64bit IPython: 5.5.0
Apache-2.0
nbs/utils/utils.normalize.ipynb
sparsh-ai/recohut
Copyright 2020 The Google AI Language Team AuthorsLicensed under the Apache License, Version 2.0 (the "License");
# Copyright 2019 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
_____no_output_____
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Running a Tapas fine-tuned checkpoint---This notebook shows how to load and make predictions with TAPAS model, which was introduced in the paper: [TAPAS: Weakly Supervised Table Parsing via Pre-training](https://arxiv.org/abs/2004.02349) Clone and install the repository First, let's install the code.
! pip install tapas-table-parsing
Collecting tapas-table-parsing Downloading tapas_table_parsing-0.0.1.dev0-py3-none-any.whl (195 kB) [?25l  |█▊ | 10 kB 22.3 MB/s eta 0:00:01  |███▍ | 20 kB 28.7 MB/s eta 0:00:01  |█████ | 30 kB 16.4 MB/s eta 0:00:0...
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Fetch models fom Google Storage Next we can get pretrained checkpoint from Google Storage. For the sake of speed, this is base sized model trained on [SQA](https://www.microsoft.com/en-us/download/details.aspx?id=54253). Note that best results in the paper were obtained with a large model, with 24 layers instead of 12...
! gsutil cp gs://tapas_models/2020_04_21/tapas_sqa_base.zip . && unzip tapas_sqa_base.zip
Copying gs://tapas_models/2020_04_21/tapas_sqa_base.zip... | [1 files][ 1.0 GiB/ 1.0 GiB] 51.4 MiB/s Operation completed over 1 objects/1.0 GiB. Archive: tapas_sqa_base.zip replace tapas_sqa_base/model.ckpt.data-00000-of-00001? [y]es, [n]o, [...
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Imports
import tensorflow.compat.v1 as tf import os import shutil import csv import pandas as pd import IPython tf.get_logger().setLevel('ERROR') from tapas.utils import tf_example_utils from tapas.protos import interaction_pb2 from tapas.utils import number_annotation_utils from tapas.scripts import prediction_utils
_____no_output_____
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Load checkpoint for prediction Here's the prediction code, which will create and `interaction_pb2.Interaction` protobuf object, which is the datastructure we use to store examples, and then call the prediction script.
os.makedirs('results/sqa/tf_examples', exist_ok=True) os.makedirs('results/sqa/model', exist_ok=True) with open('results/sqa/model/checkpoint', 'w') as f: f.write('model_checkpoint_path: "model.ckpt-0"') for suffix in ['.data-00000-of-00001', '.index', '.meta']: shutil.copyfile(f'tapas_sqa_base/model.ckpt{suffix}',...
_____no_output_____
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Predict
# Example nu-1000-0 result = predict(""" Doctor_ID|Doctor_Name|Department|opd_day|Morning_time|Evening_time 1|ABCD|Nephrology|Monday|9|5 2|ABC|Opthomology|Tuesday|9|6 3|DEF|Nephrology|Wednesday|9|6 4|GHI|Gynaecology|Thursday|9|6 5|JKL|Orthopeadics|Friday|9|6 6|MNO|Cardiology|Saturday|9|6 7|PQR|Dentistry|Sunday|9|5 8|ST...
_____no_output_____
Apache-2.0
notebooks/sqa_predictions.ipynb
aniket371/tapas
Tutorial Part 6: Going Deeper On Molecular FeaturizationsOne of the most important steps of doing machine learning on molecular data is transforming this data into a form amenable to the application of learning algorithms. This process is broadly called "featurization" and involves tutrning a molecule into a vector or...
!wget -c https://repo.anaconda.com/archive/Anaconda3-2019.10-Linux-x86_64.sh !chmod +x Anaconda3-2019.10-Linux-x86_64.sh !bash ./Anaconda3-2019.10-Linux-x86_64.sh -b -f -p /usr/local !conda install -y -c deepchem -c rdkit -c conda-forge -c omnia deepchem-gpu=2.3.0 import sys sys.path.append('/usr/local/lib/python3.7/si...
--2020-03-07 01:06:34-- https://repo.anaconda.com/archive/Anaconda3-2019.10-Linux-x86_64.sh Resolving repo.anaconda.com (repo.anaconda.com)... 104.16.130.3, 104.16.131.3, 2606:4700::6810:8303, ... Connecting to repo.anaconda.com (repo.anaconda.com)|104.16.130.3|:443... connected. HTTP request sent, awaiting response.....
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem
Let's start with some basic imports
from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from rdkit import Chem from deepchem.feat import ConvMolFeaturizer, WeaveFeaturizer, CircularFingerprint from deepchem.feat import AdjacencyFingerprint, RDKitDescriptors from deepchem.feat ...
/usr/local/lib/python3.6/dist-packages/sklearn/externals/joblib/__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickle...
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem
We use `propane`( $CH_3 CH_2 CH_3 $ ) as a running example throughout this tutorial. Many of the featurization methods use conformers or the molecules. A conformer can be generated using the `ConformerGenerator` class in `deepchem.utils.conformers`. RDKitDescriptors `RDKitDescriptors` featurizes a molecule by computi...
example_smile = "CCC" example_mol = Chem.MolFromSmiles(example_smile)
_____no_output_____
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem
Let's check the allowed list of descriptors. As you will see shortly, there's a wide range of chemical properties that RDKit computes for us.
for descriptor in RDKitDescriptors.allowedDescriptors: print(descriptor) rdkit_desc = RDKitDescriptors() features = rdkit_desc._featurize(example_mol) print('The number of descriptors present are: ', len(features))
The number of descriptors present are: 111
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem
BPSymmetryFunction `Behler-Parinello Symmetry function` or `BPSymmetryFunction` featurizes a molecule by computing the atomic number and coordinates for each atom in the molecule. The features can be used as input for symmetry functions, like `RadialSymmetry`, `DistanceMatrix` and `DistanceCutoff` . More details on th...
example_smile = "CCC" example_mol = Chem.MolFromSmiles(example_smile) engine = conformers.ConformerGenerator(max_conformers=1) example_mol = engine.generate_conformers(example_mol)
_____no_output_____
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem
Let's now take a look at the actual featurized matrix that comes out.
bp_sym = BPSymmetryFunctionInput(max_atoms=20) features = bp_sym._featurize(mol=example_mol) features
_____no_output_____
MIT
examples/tutorials/06_Going_Deeper_on_Molecular_Featurizations.ipynb
patrickphatnguyen/deepchem