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 |
|---|---|---|---|---|---|
12. Use Baye's rule to convert from P(W1|T) to P(T|W1). Write a function Ptw to reflect this. Hints:* Call your other functions.* You may need to write a function for P(W1) and you may need a new counter for `data['first_word']` | def Pw(W1=''):
words = Counter(data['first_word'])
return words[W1] / len(data['first_word'])
def Ptw(T='',W1=''):
return (Pwt(W1=W1,T=T)*P(T=T))/Pw(W1=W1) | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
13 What is P(T='movie'|W1='the')? What about P(T='person'|W1='the')? What about P(T='drug'|W1='the')? What about P(T='place'|W1='the') What about P(T='company'|W1='the') | Ptw(T='movie',W1='the')
Ptw(T='person',W1='the')
Ptw(T='drug',W1='the')
Ptw(T='place',W1='the')
Ptw(T='company',W1='the') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
14 Given this, if the word 'the' is found in a name, what is the most likely type? | Pwt('the', 'movie') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
15. Is Ptw(T='movie'|W1='the') the same as Pwt(W1='the'|T='movie') the same? Why or why not? | Ptw(T='movie',W1='the')
Pwt(W1='the', T='movie') | _____no_output_____ | AFL-3.0 | A2/A2-probability-information-theory.ipynb | Colmine/NLP_Stuff |
_Lambda School Data Science - Model Validation_ Feature SelectionObjectives:* Feature importance* Feature selection Yesterday we saw that... Less isn't always more (but sometimes it is) More isn't always better (but sometimes it is) Saavas,... | # import
import numpy as np
# Create the dataset
# from https://blog.datadive.net/selecting-good-features-part-iv-stability-selection-rfe-and-everything-side-by-side/
np.random.seed(42)
size = 1500 # I increased the size from what's given in the link
Xs = np.random.uniform(0, 1, (size, 14))
# Changed variable name ... | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
We want to be able to look at classification problems too, so let's bin the Y values to create a categorical feature from the Y values. It should have *roughly* similar relationships to the X features as Y does. | # First, let's take a look at what Y looks like
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(friedmanY); | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
That's pretty normal, let's make two binary categories--one balanced, one unbalanced, to see the difference.* balanced binary variable will be split evenly in half* unbalanced binary variable will indicate whether $Y <5$. | friedman['Y_bal'] = friedman['Y'].apply(lambda y: 1 if (y < friedman.Y.median()) else 0)
friedman['Y_un'] = friedman['Y'].apply(lambda y: 1 if (y < 5) else 0)
print(friedman.Y_bal.value_counts(), '\n\n', friedman.Y_un.value_counts())
friedman.head()
# Finally, let's put it all into our usual X and y's
# (I already hav... | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Alright! Let's get to it! Remember, with each part, we are increasing complexity of the analysis and thereby increasing the computational costs and runtime. So even before univariate selection--which compares each feature to the output feature one by one--there is a [VarianceThreshold](https://scikit-learn.org/stable/... | import sklearn.feature_selection as fe
MIR = fe.SelectKBest(fe.mutual_info_regression, k='all').fit(X, y)
MIR_scores = pd.Series(data=MIR.scores_, name='MI_Reg_Scores', index=names)
MIR_scores | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_bal (balanced binary output)options* SelectKBest* SelectPercentilethese options will cut out features with error rates above a certain tolerance level, define in parameter -`alpha`* SelectFpr (false positive rate--false positives predicted/total negatives in dataset)* SelectFdr (false discovery rate--false positives... | MIC_b = fe.SelectFpr(fe.mutual_info_classif).fit(X, y_bal)
MIC_b_scores = pd.Series(data=MIC_b.scores_,
name='MIC_Bal_Scores', index=names)
MIC_b_scores | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_un (unbalanced binary output) | MIC_u = fe.SelectFpr(fe.mutual_info_classif).fit(X, y_un)
MIC_u_scores = pd.Series(data=MIC_u.scores_,
name='MIC_Unbal_Scores', index=names)
MIC_u_scores | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Part 2: linear models and regularization* L1 Regularization (Lasso for regression) is best for goal 1: "produces sparse solutions and as such is very useful selecting a strong subset of features for improving model performance" (forces coefficients to zero, telling you which you could remove--but doesn't handle multic... | from sklearn.ensemble import RandomForestRegressor as RFR
# Fitting a random forest regression
rfr = RFR().fit(X, y)
# Creating scores from feature_importances_ ranking (some randomness here)
rfr_scores = pd.Series(data=rfr.feature_importances_, name='RFR', index=names)
rfr_scores | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
"10 in version 0.20 to 100 in 0.22.", FutureWarning)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_bal | from sklearn.ensemble import RandomForestClassifier as RFC
# Fitting a Random Forest Classifier
rfc_b = RFC().fit(X, y_bal)
# Creating scores from feature_importances_ ranking (some randomness here)
rfc_b_scores = pd.Series(data=rfc_b.feature_importances_, name='RFC_bal',
index=names)
rfc... | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
"10 in version 0.20 to 100 in 0.22.", FutureWarning)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_un | # Fitting a Random Forest Classifier
rfc_u = RFC().fit(X, y_un)
# Creating scores from feature_importances_ ranking (some randomness here)
rfc_u_scores = pd.Series(data=rfc_u.feature_importances_,
name='RFC_unbal', index=names)
rfc_u_scores | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/ensemble/forest.py:246: FutureWarning: The default value of n_estimators will change from 10 in version 0.20 to 100 in 0.22.
"10 in version 0.20 to 100 in 0.22.", FutureWarning)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
SelectFromModel is a meta-transformer that can be used along with any estimator that has a `coef_` or `feature_importances_` attribute after fitting. The features are considered unimportant and removed, if the corresponding `coef_` or `feature_importances_` values are below the provided `threshold` parameter. Apart fr... | # Random forest regression transformation of X (elimination of least important
# features)
rfr_transform = fe.SelectFromModel(rfr, prefit=True)
X_rfr = rfr_transform.transform(X)
# Random forest classifier transformation of X_bal (elimination of least important
# features)
rfc_b_transform = fe.SelectFromModel(rfc_b,... | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Part 4: stability selection, RFE, and everything side by side* These methods take longer since they are *wrapper methods* and build multiple ML models before giving results. "They both build on top of other (model based) selection methods such as regression or SVM, building models on different subsets of data and extr... | !pip install git+https://github.com/scikit-learn-contrib/stability-selection.git | Collecting git+https://github.com/scikit-learn-contrib/stability-selection.git
Cloning https://github.com/scikit-learn-contrib/stability-selection.git to /tmp/pip-req-build-axvzrzpv
Requirement already satisfied: nose>=1.1.2 in /home/seek/anaconda3/lib/python3.7/site-packages (from stability-selection==0.0.1) (1.3.7)... | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Okay, I tried this package... it seems to have some problems... hopefully a good implementation of stability selection for Lasso and Logistic Regression will be created soon! In the meantime, scikit's RandomLasso and RandomLogisticRegression have not been removed, so you can fiddle some! Just alter the commented out co... | '''from stability_selection import (RandomizedLogisticRegression,
RandomizedLasso, StabilitySelection,
plot_stability_path)
# Stability selection using randomized lasso method
rl = RandomizedLasso(max_iter=2000)
rl_selector = StabilitySelection(base_est... | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_split.py:2053: FutureWarning: You should specify a value for 'cv' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22.
warnings.warn(CV_WARNING, FutureWarning)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_bal | # stability selection using randomized logistic regression
'''rlr_b = RandomizedLogisticRegression()
rlr_b_selector = StabilitySelection(base_estimator=rlr_b, lambda_name='C',
n_jobs=2)
rlr_b_selector.fit(X, y_bal);'''
from sklearn.ensemble import ExtraTreesClassifier as ETC
# Stabilit... | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_split.py:2053: FutureWarning: You should specify a value for 'cv' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22.
warnings.warn(CV_WARNING, FutureWarning)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Y_un | # stability selection uisng randomized logistic regression
'''rlr_u = RandomizedLogisticRegression(max_iter=2000)
rlr_u_selector = StabilitySelection(base_estimator=rlr_u, lambda_name='C')
rlr_u_selector.fit(X, y_un);'''
# Stability selection using randomized decision trees
etc_u = ETC(n_estimators=50).fit(X, y_un)
#... | /home/seek/anaconda3/lib/python3.7/site-packages/sklearn/preprocessing/data.py:334: DataConversionWarning: Data with input dtype int64, float64 were all converted to float64 by MinMaxScaler.
return self.partial_fit(X, y)
| MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
What do you notice from the diagram below? | sns.heatmap(scaled_comparisons); | _____no_output_____ | MIT | module3-model-interpretation/LS_DS_243_BONUS_Feature_Selection.ipynb | standroidbeta/DS-Unit-2-Sprint-4-Practicing-Understanding |
Scraping Amazon Reviews using Scrapy in Python Part 2> Are you looking for a method of scraping Amazon reviews and do not know where to begin with? In that case, you may find this blog very useful in scraping Amazon reviews.- toc: true - badges: true- comments: true- author: Zeyu Guan- categories: [spaCy, Python, Mach... | import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from wordcloud import WordCloud
from wordcloud import STOPWORDS
import re
import plotly.graph_objects as go
import seaborn as sns | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
Data CleaningFollowing the previous blog, the raw data we scraped from Amazon look like below. Even thought that looks relatively clean, but there are still some inperfections such as star1 and star2 need to be combined, date need to be split... | def remove_punctuation(text):
final = "".join(u for u in text if u not in ("?", ".", ";", ":", "!",'"'))
return final | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Split the Dataframe**Now, we split 80% of the dataset for training and 20% for testing. Meanwhile, each dataset should contain only two variables, one is to indicate positive or negative and another one is the reviews. | df['random_number'] = np.random.randn(len(index))
train = df[df['random_number'] <= 0.8]
test = df[df['random_number'] > 0.8] | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Create a bag of words**Here I would like to introduce a new package.[Scikit-learn](https://scikit-learn.org/stable/install.html) is an open source machine learning library that supports supervised and unsupervised learning. It also provides various tools for model fitting, data preprocessing, model selection, model... | train_matrix = vectorizer.fit_transform(train['title'])
test_matrix = vectorizer.transform(test['title']) | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Import Logistic Regression** | from sklearn.linear_model import LogisticRegression
lr = LogisticRegression() | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Split target and independent variables** | X_train = train_matrix
X_test = test_matrix
y_train = train['sentiment']
y_test = test['sentiment'] | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Fit model on data** | lr.fit(X_train,y_train) | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
- **Make predictionsa** | predictions = lr.predict(X_test) | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
The output will be either 1 or -1. As we assumed before, 1 presents the model predict the review is a positive review and vice versa. TestingNow, we can test the accuracy of our model! | from sklearn.metrics import confusion_matrix, classification_report
new = np.asarray(y_test)
confusion_matrix(predictions,y_test)
print(classification_report(predictions,y_test)) | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
The accuracy is as high as 89%! Sentiment Analysis (Method 2)In this process, you will learn how to build your own sentiment analysis classifier using Python and understand the basics of NLP (natural language processing). First, let's try to ... | #Find all negative review
neg = df[df["sentiment"] == -1].review
#Reset the index
neg.index = range(len(neg.index))
## Write each DataFrame to separate txt
for i in range(len(neg)):
data = neg[i]
with open(str(i) + ".txt","w") as file:
file.write(data + "\n") | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
Next, we sort the order of the official data and remove all the content. In other words, we only keep the file name. | import os
import pandas as pd
#Get file names
file_names = os.listdir('/Users/zeyu/nltk_data/corpora/movie_reviews/neg')
#Convert pandas
neg_df = pd.DataFrame (file_names, columns = ['file_name'])
#split to sort
neg_df[['number','id']] = neg_df.file_name.apply(
lambda x: pd.Series(str(x).split("_")))
#change the... | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
Next, we insert the content of amazon review to the official files with their original file names. | #Get file names
file_names = os.listdir('/Users/zeyu/Desktop/DS/neg')
#Convert pandas
pos_df = pd.DataFrame (file_names, columns = ['file_name'])
pos_names = pos_df['file_name']
for index, file_name in enumerate(pos_names):
try:
t = open(f'/Users/zeyu/Desktop/DS/neg/{file_name}', 'r')
# t.write... | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
Eventually, we can just run these few lines to predict the sentiments of Amazon product review. | import nltk
from nltk.corpus import movie_reviews
import random
documents = [(list(movie_reviews.words(fileid)), category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
#All words, not unique.
random.shuffle(documents)
#Change to lower... | _____no_output_____ | Apache-2.0 | _notebooks/2022-04-07-scraping2.ipynb | christopherGuan/sample-ds-blog |
Install and monitor the FLIR camera serviceInstall | ! sudo cp flir-server.service /etc/systemd/system/flir-server.service | _____no_output_____ | Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
Start the service | ! sudo systemctl start flir-server.service | _____no_output_____ | Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
Stop the service | ! sudo systemctl stop flir-server.service | [0;1;31mWarning:[0m The unit file, source configuration file or drop-ins of flir-server.service changed on disk. Run 'systemctl daemon-reload' to reload units.
| Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
Enable it so that it starts on boot | ! sudo systemctl enable flir-server.service # enable at boot | _____no_output_____ | Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
Disable it so that it does not start on boot | ! sudo systemctl enable flir-server.service # enable at boot | _____no_output_____ | Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
To show status of the service | ! sudo systemctl status flir-server.service
| [0;1;32m●[0m flir-server.service - FLIR-camera server service[m
Loaded: loaded (/etc/systemd/system/flir-server.service; enabled; vendor pres[m
Active: [0;1;32mactive (running)[0m since Tue 2020-03-24 07:53:04 NZDT; 20min ago[m
Main PID: 765 (python)[m
Tasks: 17 (limit: 4915)[m
CGroup: /system.sl... | Apache-2.0 | run/monitor-flir-service.ipynb | johnnewto/FLIR-pubsub |
Analysis of motifs using Motif Miner (RINGS tool that employs alpha frequent subtree mining) | csv_files = ["ABA_14361_100ug_v5.0_DATA.csv",
"ConA_13799-10ug_V5.0_DATA.csv",
'PNA_14030_10ug_v5.0_DATA.csv',
"RCAI_10ug_14110_v5.0_DATA.csv",
"PHA-E-10ug_13853_V5.0_DATA.csv",
"PHA-L-10ug_13856_V5.0_DATA.csv",
"LCA_10ug_13934_v5.0_DATA.csv"... | Lectin & GLYMMR(mean) & GLYMMR(best) & Glycan Miner Tool & MotifFinder & CCARL \\ \hline
\textit{Agaricus bisporus} agglutinin (ABA) & 0.607 (0.151) & 0.776 (0.088) & 0.888 (0.067) & 0.905 & 0.934 (0.034) \\
Concanavalin A (Con A) & 0.760 (0.083) & 0.875 (0.048) & 0.951 (0.042) & 0.937 & 0.971 (0.031) \\
Peanut agglut... | MIT | motif_miner_comparison/motif_miner_performance.ipynb | andrewguy/CCARL |
Descripción del TP IntroducciónEn este práctico se pide desarrollar un programa que calcule parámetros de interés para un circuito RLC serie. Tomando como datos de entrada:* εmax* la frecuencia de la fuente en Hz* los valores de R, L y C: El programa debe determinar: * Imax * la diferencia de potencial de cada comp... | #hola, soy un comentario
import numpy #importamos la librería de funciones matemáticas
from matplotlib import pyplot #importamos la librería de gráficos cartesianos | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Trabajar con variablesPara instanciar o asignarle valor a una variable usamos el signo "="Las variables persisten en todo el notebook, se pueden usar en cualquier bloque de código una vez que son instanciadas | a=7 #creamos la variable "a" y le asignamos el valor 7
#se puede destinar un bloque de código para | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
En el bloque de abajo usamos la variable "a" de arriba | a+5 #realizamos una operación con la variable "a", debajo aparece el resultado de la operación | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Ingresar datos usando formulariosLos formularios permiten capturar datos de usuario para usarlos posteriormente en la ejecución de código. * Para insertar un formulario se debe presionar el botón más acciones de celda (**⋮**) a la derecha de la celda de código. *No se debe usar `Insertar→Agregar campo de formulario` p... | #@title Ejemplos de formulario
valor_formulario_numerico = 5 #@param {type:"number"}
valor_formulario_slider = 16 #@param {type:"slider", min:0, max:100, step:1}
| _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Funciones matemáticas* Las funciones aritméticas se encuentran incluidas en Python mediante [operadores](https://www.aprendeprogramando.es/cursos-online/python/operadores-aritmeticos/operadores-aritmeticos)* Funciones adicionales como las trigonométricas se invocan desde la librería numpy. Una vez importada, la podemos... | #Ejemplos de uso de funciones matemáticas
#La función print muestra en pantalla un mensaje suministrado por el programador,
#el contenido de una variable o alguna operación más compleja con variables
print(f'Valor del formulario numerico: {valor_formulario_numerico}')
print(f'Valor del formulario numerico al cuadrado:... | Valor del formulario numerico: 5
Valor del formulario numerico al cuadrado: 25
Raiz cuadrada del formulario numerico al cuadrado: 2.23606797749979
Seno del formulario slider al cuadrado: -0.2879033166650653
| MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Generando gráficas | pi=numpy.pi #Obtenemos el valor de π desde numpy y lo guardamos en la variable pi
t = [i for i in numpy.arange(0,2*pi,pi/1000)] #generamos un vector de 2000 elementos,
#con valores entre 0 y 2π en pasos de π/1000
corriente=numpy.sin(t); #calculamos el seno de los valores de "t"
tension=numpy.sin(t+numpy.ones(len(t))*pi... | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Mostrar vectoresPara mostrar vectores usamos la funcíon quiver: `(origen, coordenadas X de las puntas, coordenadas Y de las flechas, color=colores de las flechas)` | V = numpy.array([[1,1],[-2,2],[4,-7]])
origin = [0,0,0], [0,0,0] # origin point
pyplot.grid()
pyplot.quiver([0,0,0], [0,0,0], V[:,0], V[:,1], color=['r','b','g'], scale=23)
pyplot.show() | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
Mostrar fórmulasPara mostrar fórmulas podemos acudir a pyplot `(se podría usar otra librería u otra función si se quisiera)` Las fórmulas introducidas de esta forma se escriben en LaTex> Un buen editor de fórmulas de LaTex: https://www.latex4technics.com/ Para generar la fórmula usamos pyplot.text* `pyplot.text(pos X... | #add text
pyplot.text(1, 1,r'$\alpha > \beta > %i$'% valor_formulario_slider,fontsize=40)
pyplot.axis('off')
pyplot.show() #or savefig | _____no_output_____ | MIT | Consignas TP_RLC.ipynb | EmanuelDri/CalculadoraRLC |
import math
def f(x):
return(math.exp(x)) #Trigo function
a = -1
b = 1
n = 10
h = (b-a)/n #Width of Trapezoid
S = h * (f(a)+f(b)) #Value of summation
for i in range(1,n):
S += f(a+i*h)
Integral = S*h
print('Integral = %0.4f' %Integral) | Integral = 2.1731
| Apache-2.0 | Problem_3.ipynb | Nickamaes/Numerical-Methods-58011 | |
CODE HAS BEEN RUN UNTILL HERE.........v analysis of mistakes | analysis_runs.loc[analysis_runs.success == 0].sort_values('terminated_at_step')
#plt.hist(analysis_runs.loc[analysis_runs.success == 0].terminated_at_step, bins=8)
len(analysis_runs.loc[analysis_runs.success == 0])
analysis_runs['instance_size'] = analysis_runs.apply(lambda row: str(row.original_length).replace('37',... | _____no_output_____ | MIT | train_algo_relocation/analysis/get_solved_new_instances-24h-relocation-14151617-expensive_relocation-185k.ipynb | hsinyic/tusp-archive |
ERROR: type should be string, got " https://github.com/PMBio/scLVM/blob/master/tutorials/tcell_demo.ipynb Variational Autoencoder Model (VAE) with latent subspaces based on:https://arxiv.org/pdf/1812.06190.pdf" | #Step 1: import dependencies
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from keras import regularizers
import time
from __future__ import division
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributio... | _____no_output_____ | MIT | VAE_cell_cycle.ipynb | dauparas/tensorflow_examples |
- [Evcxr](https://github.com/google/evcxr): An evaluation context for Rust. | println!("Hello Rust!"); | Hello Rust!
| MIT | code-snippet/rust/notebook/example-evcxr.ipynb | zhoujiagen/ml_hacks |
Predicting Boston Housing Prices Using XGBoost in SageMaker (Hyperparameter Tuning)_Deep Learning Nanodegree Program | Deployment_---As an introduction to using SageMaker's Low Level API for hyperparameter tuning, we will look again at the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/data/boston/bostonDe... | # Make sure that we use SageMaker 1.x
!pip install sagemaker==1.72.0 | Collecting sagemaker==1.72.0
Downloading sagemaker-1.72.0.tar.gz (297 kB)
[K |████████████████████████████████| 297 kB 16.6 MB/s eta 0:00:01
[?25hRequirement already satisfied: boto3>=1.14.12 in /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages (from sagemaker==1.72.0) (1.17.55)
Requirement ... | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 0: Setting up the notebookWe begin by setting up all of the necessary bits required to run our notebook. To start that means loading all of the Python modules we will need. | %matplotlib inline
import os
import time
from time import gmtime, strftime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
import sklearn.model_selection | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
In addition to the modules above, we need to import the various bits of SageMaker that we will be using. | import sagemaker
from sagemaker import get_execution_role
from sagemaker.amazon.amazon_estimator import get_image_uri
# This is an object that represents the SageMaker session that we are currently operating in. This
# object contains some useful information that we will need to access later such as our region.
sessio... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 1: Downloading the dataFortunately, this dataset can be retrieved using sklearn and so this step is relatively straightforward. | boston = load_boston() | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 2: Preparing and splitting the dataGiven that this is clean tabular data, we don't need to do any processing. However, we do need to split the rows in the dataset up into train, test and validation sets. | # First we package up the input data and the target variable (the median value) as pandas dataframes. This
# will make saving the data to a file a little easier later on.
X_bos_pd = pd.DataFrame(boston.data, columns=boston.feature_names)
Y_bos_pd = pd.DataFrame(boston.target)
# We split the dataset into 2/3 training ... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 3: Uploading the data files to S3When a training job is constructed using SageMaker, a container is executed which performs the training operation. This container is given access to data that is stored in S3. This means that we need to upload the data we want to use for training to S3. In addition, when we perfor... | # This is our local data directory. We need to make sure that it exists.
data_dir = '../data/boston'
if not os.path.exists(data_dir):
os.makedirs(data_dir)
# We use pandas to save our test, train and validation data to csv files. Note that we make sure not to include header
# information or an index as this is requ... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Upload to S3Since we are currently running inside of a SageMaker session, we can use the object which represents this session to upload our data to the 'default' S3 bucket. Note that it is good practice to provide a custom prefix (essentially an S3 folder) to make sure that you don't accidentally interfere with data u... | prefix = 'boston-xgboost-tuning-LL'
test_location = session.upload_data(os.path.join(data_dir, 'test.csv'), key_prefix=prefix)
val_location = session.upload_data(os.path.join(data_dir, 'validation.csv'), key_prefix=prefix)
train_location = session.upload_data(os.path.join(data_dir, 'train.csv'), key_prefix=prefix) | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 4: Train and construct the XGBoost modelNow that we have the training and validation data uploaded to S3, we can construct our XGBoost model and train it. Unlike in the previous notebooks, instead of training a single model, we will use SageMakers hyperparameter tuning functionality to train multiple models and u... | # We will need to know the name of the container that we want to use for training. SageMaker provides
# a nice utility method to construct this for us.
container = get_image_uri(session.boto_region_name, 'xgboost')
# We now specify the parameters we wish to use for our training job
training_params = {}
# We need to s... | 'get_image_uri' method will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
There is a more up to date SageMaker XGBoost image. To use the newer image, please set 'repo_version'='1.0-1'. For example:
get_image_uri(region, 'xgboost', '1.0-1').
| MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Set up the tuning jobNow that the *base* training job has been set up, we can describe the tuning job that we would like SageMaker to perform. In particular, like in the high level notebook, we will specify which hyperparameters we wish SageMaker to change and what range of values they may take on.In addition, we spec... | # We need to construct a dictionary which specifies the tuning job we want SageMaker to perform
tuning_job_config = {
# First we specify which hyperparameters we want SageMaker to be able to vary,
# and we specify the type and range of the hyperparameters.
"ParameterRanges": {
"CategoricalParameterRange... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Execute the tuning jobNow that we've built the data structures that describe the tuning job we want SageMaker to execute, it is time to actually start the job. | # First we need to choose a name for the job. This is useful for if we want to recall information about our
# tuning job at a later date. Note that SageMaker requires a tuning job name and that the name needs to
# be unique, which we accomplish by appending the current timestamp.
tuning_job_name = "tuning-job" + strfti... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
The tuning job has now been created by SageMaker and is currently running. Since we need the output of the tuning job, we may wish to wait until it has finished. We can do so by asking SageMaker to output the logs generated by the tuning job and continue doing so until the job terminates. | session.wait_for_tuning_job(tuning_job_name) | ................................................................................................................................................................................................................................................................................................................................... | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Build the modelNow that the tuning job has finished, SageMaker has fit a number of models, the results of which are stored in a data structure which we can access using the name of the tuning job. | tuning_job_info = session.sagemaker_client.describe_hyper_parameter_tuning_job(HyperParameterTuningJobName=tuning_job_name) | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Among the pieces of information included in the `tuning_job_info` object is the name of the training job which performed best out of all of the models that SageMaker fit to our data. Using this training job name we can get access to the resulting model artifacts, from which we can construct a model. | # We begin by asking SageMaker to describe for us the results of the best training job. The data
# structure returned contains a lot more information than we currently need, try checking it out
# yourself in more detail.
best_training_job_name = tuning_job_info['BestTrainingJob']['TrainingJobName']
training_job_info = ... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Step 5: Testing the modelNow that we have fit our model to the training data, using the validation data to avoid overfitting, we can test our model. To do this we will make use of SageMaker's Batch Transform functionality. In other words, we need to set up and execute a batch transform job, similar to the way that we ... | # Just like in each of the previous steps, we need to make sure to name our job and the name should be unique.
transform_job_name = 'boston-xgboost-batch-transform-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# Now we construct the data structure which will describe the batch transform job.
transform_request = \
{
... | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Execute the batch transform jobNow that we have created the request data structure, it is time to as SageMaker to set up and run our batch transform job. Just like in the previous steps, SageMaker performs these tasks in the background so that if we want to wait for the transform job to terminate (and ensure the job i... | transform_response = session.sagemaker_client.create_transform_job(**transform_request)
transform_desc = session.wait_for_transform_job(transform_job_name) | ............................................................!
| MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Analyze the resultsNow that the transform job has completed, the results are stored on S3 as we requested. Since we'd like to do a bit of analysis in the notebook we can use some notebook magic to copy the resulting output from S3 and save it locally. | transform_output = "s3://{}/{}/batch-bransform/".format(session.default_bucket(),prefix)
!aws s3 cp --recursive $transform_output $data_dir | download: s3://sagemaker-us-east-1-888201120197/boston-xgboost-tuning-LL/batch-bransform/test.csv.out to ../data/boston/test.csv.out
| MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
To see how well our model works we can create a simple scatter plot between the predicted and actual values. If the model was completely accurate the resulting scatter plot would look like the line $x=y$. As we can see, our model seems to have done okay but there is room for improvement. | Y_pred = pd.read_csv(os.path.join(data_dir, 'test.csv.out'), header=None)
plt.scatter(Y_test, Y_pred)
plt.xlabel("Median Price")
plt.ylabel("Predicted Price")
plt.title("Median Price vs Predicted Price") | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Optional: Clean upThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a ... | # First we will remove all of the files contained in the data_dir directory
!rm $data_dir/*
# And then we delete the directory itself
!rmdir $data_dir | _____no_output_____ | MIT | 6_sagemaker-deployment/Tutorials/Boston Housing - XGBoost (Hyperparameter Tuning) - Low Level.ipynb | JasmineMou/udacity_DL |
Question 1: | Create a function that takes a list of non-negative integers and strings and return a new list
without the strings.
Examples
filter_list([1, 2, "a", "b"]) ➞ [1, 2]
filter_list([1, "a", "b", 0, 15]) ➞ [1, 0, 15]
filter_list([1, 2, "aasf", "1", "123", 123]) ➞ [1, 2, 123] | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
def filter_list(lst): return list(filter(lambda x: type(x) == int,lst))print(filter_list([1, 2, "a", "b"]))print(filter_list([1, "a", "b", 0, 15]))print(filter_list([1, 2, "aasf", "1", "123", 123])) | Question 2: | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
The "Reverser" takes a string as input and returns that string in reverse order, with theopposite case.Examplesreverse("Hello World") ➞ "DLROw OLLEh"reverse("ReVeRsE") ➞ "eSrEvEr"reverse("Radar") ➞ "RADAr" | Answer : | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
def reverse(string): return string[::-1].swapcase()print(reverse("Hello World"))print(reverse("ReVeRsE"))print(reverse("Radar")) | Question 3: | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
You can assign variables from lists like this:lst = [1, 2, 3, 4, 5, 6]first = lst[0]middle = lst[1:-1]last = lst[-1]print(first) ➞ outputs 1print(middle) ➞ outputs [2, 3, 4, 5]print(last) ➞ outputs 6With Python 3, you can assign variables from lists in a much more succinct way. Createvariables first, middle and last fr... | Answer : | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
def unpack_list(lst): first = lst[0] middle = lst[1:-1] last = lst[-1] return first,middle,lastlst = [1, 2, 3, 4, 5, 6]first,middle,last = unpack_list(lst)print(first)print(middle)print(last) | Question 4: | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
Write a function that calculates the factorial of a number recursively. Examplesfactorial(5) ➞ 120factorial(3) ➞ 6factorial(1) ➞ 1factorial(0) ➞ 1 | def factorial(num):
if num<0:
return f"{num} is negative number."
if num == 0 or num == 1:
return 1
else:
return num*factorial(num-1)
print(factorial(5))
print(factorial(3))
print(factorial(1))
print(factorial(0)) | 120
6
1
1
| MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
Question 5: | Write a function that moves all elements of one type to the end of the list.
Examples
move_to_end([1, 3, 2, 4, 4, 1], 1) ➞ [3, 2, 4, 4, 1, 1]
# Move all the 1s to the end of the array.
move_to_end([7, 8, 9, 1, 2, 3, 4], 9) ➞ [7, 8, 1, 2, 3, 4, 9]
move_to_end(["a", "a", "a", "b"], "a") ➞ ["b", "a", "a", "a"] | _____no_output_____ | MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
Answer : | def move_to_end(lst,x):
lst.remove(x)
lst.append(x)
return lst
print(move_to_end([1, 3, 2, 4, 4, 1], 1))
print(move_to_end([7, 8, 9, 1, 2, 3, 4], 9))
print(move_to_end(["a", "a", "a", "b"], "a")) | [3, 2, 4, 4, 1, 1]
[7, 8, 1, 2, 3, 4, 9]
['a', 'a', 'b', 'a']
| MIT | Python Programming Basic Assignment/Assignment_18.ipynb | kpsanjeet/Python-Programming-Basic-Assignment |
Get Training Data | # get training data
train_df = pd.read_csv(os.path.join(ROOT_DIR,DATA_DIR,FEATURE_SET,'train.csv.gz'))
X_train = train_df.drop(ID_VAR + [TARGET_VAR],axis=1)
y_train = train_df.loc[:,TARGET_VAR]
X_train.shape
y_train.shape
y_train[:10] | _____no_output_____ | MIT | eda/hyper-parameter_tuning/random_forest-Level0.ipynb | jimthompson5802/model-stacking-framework |
Setup pipeline for hyper-parameter tuning | # set up pipeline
pipe = Pipeline([('this_model',ThisModel(n_jobs=-1))]) | _____no_output_____ | MIT | eda/hyper-parameter_tuning/random_forest-Level0.ipynb | jimthompson5802/model-stacking-framework |
this_scorer = make_scorer(lambda y, y_hat: np.sqrt(mean_squared_error(y,y_hat)),greater_is_better=False) | def kag_rmsle(y,y_hat):
return np.sqrt(mean_squared_error(y,y_hat))
this_scorer = make_scorer(kag_rmsle, greater_is_better=False)
grid_search = RandomizedSearchCV(pipe,
param_distributions=PARAM_GRID,
scoring=this_scorer,cv=5,
... | _____no_output_____ | MIT | eda/hyper-parameter_tuning/random_forest-Level0.ipynb | jimthompson5802/model-stacking-framework |
We can see in the next two cells that the parallelized code took off 16 minutes of computation time here. I haven't run on anything larger, so I dont know how it scales yet. There is another example past this as well. | cProfile.runctx('get_phenotype_graph_optimized(database, paramslist)', globals(), {'database':database,'paramslist':paramslist})
cProfile.runctx('get_phenotype_graph_parallel(database, paramslist, num_processes)', globals(), {'database':database,'paramslist':paramslist, 'num_processes':8})
database = Database("/home/el... | _____no_output_____ | MIT | notebooks/Profiling_parallel_code.ipynb | Eandreas1857/dsgrn_acdc |
This one is smaller than the first example, but I feel shows promising results in speeding up computation time. | cProfile.runctx('get_phenotype_graph_optimized(database, paramslist)', globals(), {'database':database,'paramslist':paramslist})
cProfile.runctx('get_phenotype_graph_parallel(database, paramslist, num_processes)', globals(), {'database':database,'paramslist':paramslist, 'num_processes':8}) | 1871 function calls in 0.325 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
15 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:1009(_handle_fromlist)
15 0.000 0.000 0.000 0.000 <frozen importlib._bootstr... | MIT | notebooks/Profiling_parallel_code.ipynb | Eandreas1857/dsgrn_acdc |
Cell Painting morphological (CP) and L1000 gene expression (GE) profiles for the following datasets: - **CDRP**-BBBC047-Bray-CP-GE (Cell line: U2OS) : * $\bf{CP}$ There are 30,430 unique compounds for CP dataset, median number of replicates --> 4 * $\bf{GE}$ There are 21,782 unique compounds for GE dataset, me... | %matplotlib notebook
%load_ext autoreload
%autoreload 2
import numpy as np
import scipy.spatial
import pandas as pd
import sklearn.decomposition
import matplotlib.pyplot as plt
import seaborn as sns
import os
from cmapPy.pandasGEXpress.parse import parse
from utils.replicateCorrs import replicateCorrs
from utils.saveAs... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
Input / ouput files: - **CDRPBIO**-BBBC047-Bray-CP-GE (Cell line: U2OS) : * $\bf{CP}$ * Input: * Output: * $\bf{GE}$ * Input: .mat files that are generated using https://github.com/broadinstitute/2014_wawer_pnas * Output: - **LUAD**-BBBC041-Caicedo-CP-GE (Cell line: A54... | fileName='RepCorrDF'
### dirs on gpu cluster
# rawProf_dir='/storage/data/marziehhaghighi/Rosetta/raw-profiles/'
# procProf_dir='/home/marziehhaghighi/workspace_rosetta/workspace/'
### dirs on ec2
rawProf_dir='/home/ubuntu/bucket/projects/2018_04_20_Rosetta/workspace/raw-profiles/'
# procProf_dir='./'
procProf_dir='/h... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CDRP-BBBC047-Bray GE - L1000 - CDRP | os.listdir(rawProf_dir+'/l1000_CDRP/')
cdrp_dataDir=rawProf_dir+'/l1000_CDRP/'
cpd_info = pd.read_csv(cdrp_dataDir+"/compounds.txt", sep="\t", dtype=str)
cpd_info.columns
from scipy.io import loadmat
x = loadmat(cdrp_dataDir+'cdrp.all.prof.mat')
k1=x['metaWell']['pert_id'][0][0]
k2=x['metaGen']['AFFX_PROBE_ID'][0][0]
... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CP - CDRP | profileType=['_augmented','_normalized']
bioactiveFlag="";# either "-bioactive" or ""
plates=os.listdir(rawProf_dir+'/CDRP'+bioactiveFlag+'/')
for pt in profileType[1:2]:
repLevelCDRP0=[]
for p in plates:
# repLevelCDRP0.append(pd.read_csv(rawProf_dir+'/CDRP/'+p+'/'+p+pt+'.csv'))
repLevelCDRP0... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CDRP-bio-BBBC036-Bray GE - L1000 - CDRPBIO | bioactiveFlag="-bioactive";# either "-bioactive" or ""
plates=os.listdir(rawProf_dir+'/CDRP'+bioactiveFlag+'/')
# plates
cdrp_l1k_rep2_bioactive=cdrp_l1k_rep2[cdrp_l1k_rep2["pert_sample_dose"].isin(repLevelCDRP2.Metadata_Sample_Dose.unique().tolist())]
cdrp_l1k_rep.det_plate | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CP - CDRPBIO | profileType=['_augmented','_normalized','_normalized_variable_selected']
bioactiveFlag="-bioactive";# either "-bioactive" or ""
plates=os.listdir(rawProf_dir+'/CDRP'+bioactiveFlag+'/')
for pt in profileType:
repLevelCDRP0=[]
for p in plates:
# repLevelCDRP0.append(pd.read_csv(rawProf_dir+'/CDRP/'+p+'/... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
LUAD-BBBC041-Caicedo GE - L1000 - LUAD | os.listdir(rawProf_dir+'/l1000_LUAD/input/')
os.listdir(rawProf_dir+'/l1000_LUAD/output/')
luad_dataDir=rawProf_dir+'/l1000_LUAD/'
luad_info1 = pd.read_csv(luad_dataDir+"/input/TA.OE014_A549_96H.map", sep="\t", dtype=str)
luad_info2 = pd.read_csv(luad_dataDir+"/input/TA.OE015_A549_96H.map", sep="\t", dtype=str)
luad_in... | here3
| BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CP - LUAD | profileType=['_augmented','_normalized','_normalized_variable_selected']
plates=os.listdir('/storage/luad/profiles_cp/LUAD-BBBC043-Caicedo/')
for pt in profileType[1:2]:
repLevelLuad0=[]
for p in plates:
repLevelLuad0.append(pd.read_csv('/storage/luad/profiles_cp/LUAD-BBBC043-Caicedo/'+p+'/'+p+pt+'.csv'... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
TA-ORF-BBBC037-Rohban GE - L1000 | taorf_datadir=rawProf_dir+'/l1000_TA_ORF/'
gene_info = pd.read_csv(taorf_datadir+"TA.OE005_U2OS_72H.map.txt", sep="\t", dtype=str)
# gene_info.columns
# TA.OE005_U2OS_72H_INF_n729x22268.gctx
# TA.OE005_U2OS_72H_QNORM_n729x978.gctx
# TA.OE005_U2OS_72H_ZSPCINF_n729x22268.gctx
# TA.OE005_U2OS_72H_ZSPCQNORM_n729x978.gctx
t... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
Check Replicate Correlation | # df1=taorf_l1k_df2[taorf_l1k_df2['pert_id']!='CMAP-000']
df1_scaled = standardize_per_catX(taorf_l1k_df2,'det_plate',l1k_features.tolist());
df1_scaled2=df1_scaled[df1_scaled['pert_id']!='DMSO']
x=replicateCorrs(df1_scaled2,'pert_id',l1k_features,1) | here3
| BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
CP - TAORF | profileType=['_augmented','_normalized','_normalized_variable_selected']
plates=os.listdir(rawProf_dir+'TA-ORF-BBBC037-Rohban/')
for pt in profileType[0:1]:
repLevelTA0=[]
for p in plates:
repLevelTA0.append(pd.read_csv(rawProf_dir+'TA-ORF-BBBC037-Rohban/'+p+'/'+p+pt+'.csv'))
repLevelTA = pd.concat(... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
LINCS-Pilot1 GE - L1000 - LINCS | os.listdir(rawProf_dir+'/l1000_LINCS/2016_04_01_a549_48hr_batch1_L1000/')
os.listdir(rawProf_dir+'/l1000_LINCS/metadata/')
data_meta_match_ls=[['level_3','level_3_q2norm_n27837x978.gctx','col_meta_level_3_REP.A_A549_only_n27837.txt'],
['level_4W','level_4W_zspc_n27837x978.gctx','col_meta_level_3_REP.... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
raw data | # set(repLevelLuad2)-set(Y1.columns)
# Y1[['Allele', 'Category', 'Clone ID', 'Gene Symbol']].head()
# repLevelLuad2[repLevelLuad2['PublicID']=='BRDN0000553807'][['Col','InsertLength','NCBIGeneID','Name','OtherDescriptions','PublicID','Row','Symbol','Transcript','Vector','pert_type','x_mutation_status']].head() | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
Check Replicate Correlation CP - LINCS | # Ran the following on:
# https://ec2-54-242-99-61.compute-1.amazonaws.com:5006/notebooks/workspace_nucleolar/2020_07_20_Nucleolar_Calico/1-NucleolarSizeMetrics.ipynb
# Metadata
def recode_dose(x, doses, return_level=False):
closest_index = np.argmin([np.abs(dose - x) for dose in doses])
if np.isnan(x):
... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
Read saved data | repLevelLINCS2.groupby(['Metadata_pert_id']).size()
repLevelLINCS2.groupby(['Metadata_pert_id_dose']).size().describe()
repLevelLINCS2.Metadata_Plate.unique().shape
repLevelLINCS2['Metadata_pert_id_dose'].unique().shape
# csv_pddf['Metadata_mmoles_per_liter'].round(0).unique()
# np.sort(csv_pddf['Metadata_mmoles_per_li... | _____no_output_____ | BSD-3-Clause | 0-preprocess_datasets.ipynb | carpenterlab/2021_Haghighi_submitted |
IntroductionVisualization of statistics that support the claims of Black Lives Matter movement, data from 2015 and 2016.Data source: https://www.theguardian.com/us-news/ng-interactive/2015/jun/01/about-the-countedIdea from BuzzFeed article: https://www.buzzfeednews.com/article/peteraldhous/race-and-police-shootings I... | import pandas as pd
import numpy as np
from bokeh.io import output_notebook, show, export_png
from bokeh.plotting import figure, output_file
from bokeh.models import HoverTool, ColumnDataSource,NumeralTickFormatter
from bokeh.palettes import Spectral4, PuBu4
from bokeh.transform import dodge
from bokeh.layouts import ... | _____no_output_____ | MIT | thecounted_visual.ipynb | KikiCS/thecounted |
Source for ethnicities percentage in 2015: https://www.statista.com/statistics/270272/percentage-of-us-population-by-ethnicities/Source for population total: https://en.wikipedia.org/wiki/Demography_of_the_United_StatesVital_statistics_from_1935 | ethndic={"White": 61.72,
"Latino": 17.66,
"Black": 12.38,
"Others": (5.28+2.05+0.73+0.17)
}
#print(type(ethndic))
print(ethndic)
population=(321442000 + 323100000)/2 # average between 2015 and 2016 data
# estimates by ethnicity
ethnestim={"White": round((population*ethndic["White"]/10... | {'White': 61.72, 'Latino': 17.66, 'Black': 12.38, 'Others': 8.23}
{'White': 198905661, 'Latino': 56913059, 'Black': 39897150, 'Others': 26522903}
| MIT | thecounted_visual.ipynb | KikiCS/thecounted |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.