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 |
|---|---|---|---|---|---|
Our Chainer script writes various artifacts, such as plots, to a directory `output_data_dir`, the contents of which which SageMaker uploads to S3. Now we download and extract these artifacts. | from s3_util import retrieve_output_from_s3
chainer_training_job = chainer_estimator.latest_training_job.name
desc = sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=chainer_training_job
)
output_data = desc["ModelArtifacts"]["S3ModelArtifacts"].replace("model.tar.gz", "output.tar.gz")
r... | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
These plots show the accuracy and loss over epochs: | from IPython.display import Image
from IPython.display import display
accuracy_graph = Image(filename="output/single_machine_cifar/accuracy.png", width=800, height=800)
loss_graph = Image(filename="output/single_machine_cifar/loss.png", width=800, height=800)
display(accuracy_graph, loss_graph) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
Deploying the Trained ModelAfter training, we use the Chainer estimator object to create and deploy a hosted prediction endpoint. We can use a CPU-based instance for inference (in this case an `ml.m4.xlarge`), even though we trained on GPU instances.The predictor object returned by `deploy` lets us call the new endpoi... | predictor = chainer_estimator.deploy(initial_instance_count=1, instance_type="ml.m4.xlarge") | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
CIFAR10 sample imagesWe'll use these CIFAR10 sample images to test the service: Predicting using SageMaker EndpointWe batch the images together into a single NumPy array to obtain multiple inferences with a single prediction request. | from skimage import io
import numpy as np
def read_image(filename):
img = io.imread(filename)
img = np.array(img).transpose(2, 0, 1)
img = np.expand_dims(img, axis=0)
img = img.astype(np.float32)
img *= 1.0 / 255.0
img = img.reshape(3, 32, 32)
return img
def read_images(filenames):
r... | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
The predictor runs inference on our input data and returns a list of predictions whose argmax gives the predicted label of the input data. | response = predictor.predict(image_data)
for i, prediction in enumerate(response):
print("image {}: prediction: {}".format(i, prediction.argmax(axis=0))) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
CleanupAfter you have finished with this example, remember to delete the prediction endpoint to release the instance(s) associated with it. | chainer_estimator.delete_endpoint() | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/chainer_cifar10/chainer_single_machine_cifar10.ipynb | can-sun/amazon-sagemaker-examples |
USM Numérica Tema del Notebook Objetivos1. Conocer el funcionamiento de la librerìa sklearn de Machine Learning2. Aplicar la librerìa sklearn para solucionar problemas de Machine Learning Sobre el autor Sebastián Flores ICM UTFSM sebastian.flores@usm.cl Sobre la presentación Contenido creada en ipython notebook (jup... | from sklearn import __version__ as vsn
print(vsn) | 0.24.1
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
0.1 InstruccionesLas instrucciones de instalación y uso de un ipython notebook se encuentran en el siguiente [link](link).Después de descargar y abrir el presente notebook, recuerden:* Desarrollar los problemas de manera secuencial.* Guardar constantemente con *`Ctr-S`* para evitar sorpresas.* Reemplazar en las celdas... | """
IPython Notebook v4.0 para python 3.0
Librerías adicionales: numpy, scipy, matplotlib. (EDITAR EN FUNCION DEL NOTEBOOK!!!)
Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT.
(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.
"""
# Configuración para recargar módulos y librerías dinámi... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
1.- Sobre la librería sklearn Historia- Nace en 2007, como un Google Summer Project de David Cournapeau. - Retomado por Matthieu Brucher para su proyecto de tesis.- Desde 2010 con soporte por parte de INRIA.- Actualmente +35 colaboradores. 1.- Sobre la librería sklearn InstalaciónEn python, con un poco de suerte:```p... | from sklearn import HelpfulMethods
from sklearn import AlgorithmIWantToUse
# split data into train and test datasets
# train model with train dataset
# compute error on test dataset
# Optional: Train model with all available data
# Use model for some prediction
| _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Wine DatasetLos datos del [Wine Dataset](https://archive.ics.uci.edu/ml/datasets/Wine) son un conjunto de datos clásicos para verificar los algoritmos de clustering. Los datos corresponden a 3 cultivos diferentes de vinos de la misma región de Italia, y que han sido identificados con las etiq... | %%bash
head data/wine_data.csv | class,alcohol,malic_acid,ash,alcalinity_of_ash,magnesium,total_phenols,flavanoids,nonflavanoid_phenols,proanthocyanins,color_intensity,hue,OD280-OD315_of_diluted_wines,proline
1,14.23,1.71,2.43,15.6,127,2.8,3.06,.28,2.29,5.64,1.04,3.92,1065
1,13.2,1.78,2.14,11.2,100,2.65,2.76,.26,1.28,4.38,1.05,3.4,1050
1,13.16,2.3... | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Lectura de datos | import pandas as pd
data = pd.read_csv("data/wine_data.csv")
data | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Exploración de datos | data.columns
data["class"].value_counts()
data.describe(include="all") | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Exploración gráfica de datos | from matplotlib import pyplot as plt
data.hist(figsize=(12,20))
plt.show()
from matplotlib import pyplot as plt
#pd.scatter_matrix(data, figsize=(12,12), range_padding=0.2)
#plt.show() | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Separación de los datosNecesitamos separar los datos en los predictores (features) y las etiquetas (labels) | X = data.drop("class", axis=1)
true_labels = data["class"] -1 # labels deben ser 0, 1, 2, ..., n-1 | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Custering Magnitudes de los datos | print(X.mean())
print(X.std()) | alcohol 0.811827
malic_acid 1.117146
ash 0.274344
alcalinity_of_ash 3.339564
magnesium 14.282484
total_phenols 0.625851
flavanoids 0.998859
nonflavanoid_phenol... | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Algoritmo de ClusteringPara Clustering usaremos el algoritmo KMeans. Apliquemos un algoritmo de clustering directamente | from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
# Parameters
n_clusters = 3
# Running the algorithm
kmeans = KMeans(n_clusters)
kmeans.fit(X)
pred_labels = kmeans.labels_
cm = confusion_matrix(true_labels, pred_labels)
print(cm) | [[ 0 46 13]
[50 1 20]
[19 0 29]]
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Normalizacion de datosResulta conveniente escalar los datos, para que el algoritmo de clustering funcione mejor | from sklearn import preprocessing
X_scaled = preprocessing.scale(X)
print(X_scaled.mean())
print(X_scaled.std()) | 1.0
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Algoritmo de ClusteringAhora podemos aplicar un algoritmo de clustering | from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
# Parameters
n_clusters = 3
# Running the algorithm
kmeans = KMeans(n_clusters)
kmeans.fit(X_scaled)
pred_labels = kmeans.labels_
cm = confusion_matrix(true_labels, pred_labels)
print(cm) | [[ 0 59 0]
[ 3 3 65]
[48 0 0]]
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn Regla del codoEn todos los casos hemos utilizado que el número de clusters es igual a 3. En caso que no conociéramos este dato, deberíamos graficar la suma de las distancias a los clusters para cada punto, en función del número de clusters. | from sklearn.cluster import KMeans
clusters = range(2,20)
total_distance = []
for n_clusters in clusters:
kmeans = KMeans(n_clusters)
kmeans.fit(X_scaled)
pred_labels = kmeans.labels_
centroids = kmeans.cluster_centers_
# Get the distances
distance_for_n = 0
for k in range(n_clusters):
... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearnGraficando lo anterior, obtenemos | from matplotlib import pyplot as plt
fig = plt.figure(figsize=(16,8))
plt.plot(clusters, total_distance, 'rs')
plt.xlim(min(clusters)-1, max(clusters)+1)
plt.ylim(0, max(total_distance)*1.1)
plt.show() | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
4- Clustering con sklearn¿Qué tan dificil es usar otro algoritmo de clustering? Nada dificil. Algoritmos disponibles:* K-Means* Mini-batch K-means* Affinity propagation* Mean-shift* Spectral clustering* Ward hierarchical clustering* Agglomerative clustering* DBSCAN* Gaussian mixtures* BirchLista con detalles: [http://... | from sklearn.cluster import KMeans
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing
# Normalization of data
X_scaled = preprocessing.scale(X)
# Running the algorithm
kmeans = KMeans(n_clusters=3)
kmeans.fit(X_scaled)
pred_labels = kmeans.labels_
# Evaluating the output
cm = confusion_ma... | [[49 10 0]
[ 3 58 10]
[ 2 0 46]]
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Reconocimiento de dígitosLos datos se encuentran en 2 archivos, `data/optdigits.train` y `data/optdigits.test`. Como su nombre lo indica, el set `data/optdigits.train` contiene los ejemplos que deben ser usados para entrenar el modelo, mientras que el set `data/optdigits.test` se utilizará para obtene... | import numpy as np
XY_tv = np.loadtxt("data/optdigits.train", delimiter=",", dtype=np.int8)
print(XY_tv)
X_tv = XY_tv[:,:64]
Y_tv = XY_tv[:, 64]
print(X_tv.shape)
print(Y_tv.shape)
print(X_tv[0,:])
print(X_tv[0,:].reshape(8,8))
print(Y_tv[0]) | [[ 0 1 6 ... 0 0 0]
[ 0 0 10 ... 0 0 0]
[ 0 0 8 ... 0 0 7]
...
[ 0 0 3 ... 0 0 6]
[ 0 0 6 ... 5 0 6]
[ 0 0 2 ... 0 0 7]]
(3823, 64)
(3823,)
[ 0 1 6 15 12 1 0 0 0 7 16 6 6 10 0 0 0 8 16 2 0 11 2 0
0 5 16 3 0 5 7 0 0 7 13 3 0 8 7 0 0 4 12 0 1 13 5 0... | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Visualizando los datosPara visualizar los datos utilizaremos el método imshow de pyplot. Resulta necesario convertir el arreglo desde las dimensiones (1,64) a (8,8) para que la imagen sea cuadrada y pueda distinguirse el dígito. Superpondremos además el label correspondiente al dígito, mediante el mé... | from matplotlib import pyplot as plt
# Well plot the first nx*ny examples
nx, ny = 5, 5
fig, ax = plt.subplots(nx, ny, figsize=(12,12))
for i in range(nx):
for j in range(ny):
index = j+ny*i
data = X_tv[index,:].reshape(8,8)
label = Y_tv[index]
ax[i][j].imshow(data, interpolation='... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Entrenamiento trivialPara clasificar utilizaremos el algoritmo K Nearest Neighbours.Entrenaremos el modelo con 1 vecino y verificaremos el error de predicción en el set de entrenamiento. | from sklearn.neighbors import KNeighborsClassifier
k = 1
kNN = KNeighborsClassifier(n_neighbors=k)
kNN.fit(X_tv, Y_tv)
Y_pred = kNN.predict(X_tv)
n_errors = sum(Y_pred!=Y_tv)
print("Hay %d errores de un total de %d ejemplos de entrenamiento" %(n_errors, len(Y_tv))) | Hay 0 errores de un total de 3823 ejemplos de entrenamiento
| MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
¡La mejor predicción del punto es el mismo punto! Pero esto generalizaría catastróficamente.Es importantísimo **entrenar** en un set de datos y luego probar como generaliza/funciona en un set **completamente nuevo**. 5- Clasificación Seleccionando el número adecuado de vecinosBuscando el valor de k más apropiadoA part... | from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
template = "k={0:,d}: {1:.1f} +- {2:.1f} errores de clasificación de un total de {3:,d} puntos"
# Fitting the model
mean_error_for_k = []
std_error_for_k = []
k_range = range(1,8)
for k in k_range:
errors_k = []... | k=1: 1.6 +- 0.3 errores de clasificación de un total de 956 puntos
k=2: 2.3 +- 0.5 errores de clasificación de un total de 956 puntos
k=3: 1.6 +- 0.3 errores de clasificación de un total de 956 puntos
k=4: 2.0 +- 0.4 errores de clasificación de un total de 956 puntos
k=5: 1.7 +- 0.2 errores de clasificación de un total... | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- ClasificaciónPodemos visualizar los datos anteriores utilizando el siguiente código, que requiere que `sd_error_for k` y `mean_error_for_k` hayan sido apropiadamente definidos. | mean = np.array(mean_error_for_k)
std = np.array(std_error_for_k)
plt.figure(figsize=(12,8))
plt.plot(k_range, mean - std, "k:")
plt.plot(k_range, mean , "r.-")
plt.plot(k_range, mean + std, "k:")
plt.xlabel("Numero de vecinos k")
plt.ylabel("Error de clasificacion")
plt.show() | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Entrenando todo el modeloA partir de lo anterior, se fija el número de vecinos $k=3$ y se procede a entrenar el modelo con todos los datos. | from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import numpy as np
k = 3
kNN = KNeighborsClassifier(n_neighbors=k)
kNN.fit(X_tv, Y_tv) | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Predicción en testing datasetAhora que el modelo kNN ha sido completamente entrenado, calcularemos el error de predicción en un set de datos completamente nuevo: el set de testing. | # Cargando el archivo data/optdigits.tes
XY_test = np.loadtxt("data/optdigits.test", delimiter=",")
X_test = XY_test[:,:64]
Y_test = XY_test[:, 64]
# Predicción de etiquetas
Y_pred = kNN.predict(X_test) | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- ClasificaciónPuesto que tenemos las etiquetas verdaderas en el set de entrenamiento, podemos visualizar que números han sido correctamente etiquetados. | from matplotlib import pyplot as plt
# Mostrar los datos correctos
mask = (Y_pred==Y_test)
X_aux = X_test[mask]
Y_aux_true = Y_test[mask]
Y_aux_pred = Y_pred[mask]
# We'll plot the first 100 examples, randomly choosen
nx, ny = 5, 5
fig, ax = plt.subplots(nx, ny, figsize=(12,12))
for i in range(nx):
for j in range... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Visualización de etiquetas incorrectasMás interesante que el gráfico anterior, resulta considerar los casos donde los dígitos han sido incorrectamente etiquetados. | from matplotlib import pyplot as plt
# Mostrar los datos correctos
mask = (Y_pred!=Y_test)
X_aux = X_test[mask]
Y_aux_true = Y_test[mask]
Y_aux_pred = Y_pred[mask]
# We'll plot the first 100 examples, randomly choosen
nx, ny = 5, 5
fig, ax = plt.subplots(nx, ny, figsize=(12,12))
for i in range(nx):
for j in range... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Análisis del errorDespués de la exploración visual de los resultados, queremos obtener el error de predicción real del modelo.¿Existen dígitos más fáciles o difíciles de clasificar? | # Error global
mask = (Y_pred!=Y_test)
error_prediccion = 100.*sum(mask) / len(mask)
print("Error de predicción total de {0:.1f} %".format(error_prediccion))
for digito in range(0,10):
mask_digito = Y_test==digito
Y_test_digito = Y_test[mask_digito]
Y_pred_digito = Y_pred[mask_digito]
mask = Y_test_di... | Error de predicción total de 2.2 %
Error de predicción para digito 0 de 0.0 %
Error de predicción para digito 1 de 1.1 %
Error de predicción para digito 2 de 2.3 %
Error de predicción para digito 3 de 1.1 %
Error de predicción para digito 4 de 1.7 %
Error de predicción para digito 5 de 1.6 %
Error de predicción para di... | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
5- Clasificación Análisis del error (cont. de)El siguiente código muestra el error de clasificación, permitiendo verificar que números son confundibles | from sklearn.metrics import confusion_matrix as cm
cm = cm(Y_test, Y_pred)
print(cm)
# As in http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.jet):
plt.figure(figsize=(10,10))
plt.imshow(cm, interpolation=... | _____no_output_____ | MIT | meetup.ipynb | sebastiandres/talk_2016_04_python_meetup_sklearn |
Table of Contents1 Download and Clean Data2 Making Recommendations2.1 BERT2.2 Doc2vec2.3 LDA2.4 TFIDF **rec_books**Downloads an English Wikipedia dump and parses it for all available books. All available models are then ran to compare recommendation effi... | # pip install wikirec -U | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
The following gensim update might be necessary in Google Colab as the default version is very low. | # pip install gensim -U | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
In Colab you'll also need to download nltk's names data. | # import nltk
# nltk.download("names")
import os
import json
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="darkgrid")
sns.set(rc={"figure.figsize": (15, 5)})
from wikirec import data_utils, model, utils
from IPython.core.display import display, HTML
display(HTML("<style>.contai... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
Download and Clean Data | files = data_utils.download_wiki(
language="en", target_dir="./enwiki_dump", file_limit=-1, dump_id=False
)
len(files)
topic = "books"
data_utils.parse_to_ndjson(
topics=topic,
output_path="./enwiki_books.ndjson",
input_dir="./enwiki_dump",
partitions_dir="./enwiki_book_partitions",
limit=None,
... | Loading book corpus and selected indexes
| BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
Making Recommendations | single_input_0 = "Harry Potter and the Philosopher's Stone"
single_input_1 = "The Hobbit"
multiple_inputs = ["Harry Potter and the Philosopher's Stone", "The Hobbit"]
def load_or_create_sim_matrix(
method,
corpus,
metric,
topic,
path="./",
bert_st_model="xlm-r-bert-base-nli-stsb-mean-tokens",
... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
BERT | # Remove n-grams for BERT training
corpus_no_ngrams = [
" ".join([t for t in text.split(" ") if "_" not in t]) for text in text_corpus
]
# We can pass kwargs for sentence_transformers.SentenceTransformer.encode
bert_sim_matrix = load_or_create_sim_matrix(
method="bert",
corpus=corpus_no_ngrams,
metric="... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
Doc2vec | # We can pass kwargs for gensim.models.doc2vec.Doc2Vec
doc2vec_sim_matrix = load_or_create_sim_matrix(
method="doc2vec",
corpus=text_corpus,
metric="cosine", # euclidean
topic=topic,
path="./",
vector_size=100,
epochs=10,
alpha=0.025,
)
model.recommend(
inputs=single_input_0,
ti... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
LDA | topic_nums_to_compare = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# We can pass kwargs for gensim.models.ldamulticore.LdaMulticore
utils.graph_lda_topic_evals(
corpus=text_corpus,
num_topic_words=10,
topic_nums_to_compare=topic_nums_to_compare,
metrics=True,
verbose=True,
)
plt.show()
# We can ... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
TFIDF | # We can pass kwargs for sklearn.feature_extraction.text.TfidfVectorizer
tfidf_sim_matrix = load_or_create_sim_matrix(
method="tfidf",
corpus=text_corpus,
metric="cosine", # euclidean
topic=topic,
path="./",
max_features=None,
norm='l2',
)
model.recommend(
inputs=single_input_0,
tit... | _____no_output_____ | BSD-3-Clause | examples/rec_books.ipynb | bizzyvinci/wikirec |
CI coverage, length and biasFor event related design. | # Directories of the data for different scenario's
DATAwd <- list(
'Take[8mmBox10]' = "/Volumes/2_TB_WD_Elements_10B8_Han/PhD/IBMAvsGLM/Results/Cambridge/ThirdLevel/8mm/boxcar10",
'Take[8mmEvent2]' = "/Volumes/2_TB_WD_Elements_10B8_Han/PhD/IBMAvsGLM/Results/Cambridge/ThirdLevel/8mm/event2"
)
NUMDATAwd <- length(DA... | _____no_output_____ | MIT | 3_Reports/12.03_22_17/Report_03_22_17.ipynb | NeuroStat/IBMAvsGLM |
Assignment 02: Evaluate the Diabetes Dataset*The comments/sections provided are your cues to perform the assignment. You don't need to limit yourself to the number of rows/cells provided. You can add additional rows in each section to add more lines of code.**If at any point in time you need help on solving this assig... | #Import the required libraries
import numpy as np
import pandas as pd
#Import the diabetes dataset
data = pd.read_csv("pima-indians-diabetes.data",header=None) | _____no_output_____ | Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
2: Analyze the dataset | #View the first five observations of the dataset
data.head() | _____no_output_____ | Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
3: Find the features of the dataset | #Use the .NAMES file to view and set the features of the dataset
feature_name = np.array(["Pregnant","Glucose","BP","Skin","Insulin","BMI","Pedigree","Age","label"])
df_data = pd.read_csv("pima-indians-diabetes.data",names=feature_name)
df_data
#View the number of observations and features of the dataset
df_data.shape | _____no_output_____ | Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
4: Find the response of the dataset | #Create the feature object
X_feature = df_data[["Pregnant","Glucose","BP","Skin","Insulin","BMI","Pedigree","Age"]]
X_feature
#Create the reponse object
y_target = df_data[["label"]]
y_target
#View the shape of the feature object
X_feature.shape
#View the shape of the target object
y_target.shape | _____no_output_____ | Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
5: Use training and testing datasets to train the model | #Split the dataset to test and train the model
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X_feature,y_target,test_size = 0.25,random_state = 20) | _____no_output_____ | Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
6: Create a model to predict the diabetes outcome | # Create a logistic regression model using the training set
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train,y_train)
#Make predictions using the testing set
Prediction = logreg.predict(X_test)
print(Prediction[10:20])
print(y_test[10:20]) | [1 1 0 0 1 0 0 0 0 1]
label
702 1
222 0
20 0
631 0
147 0
403 0
526 0
422 0
150 0
7 0
| Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
7: Check the accuracy of the model | #Evaluate the accuracy of your model
from sklearn import metrics
performance = metrics.accuracy_score(y_test,Prediction)
performance
#Print the first 30 actual and predicted responses
print(f"Predicted Value - {Prediction[0:30]}")
print(f"Actual Value - {y_test.values[0:30]}") | Predicted Value - [0 1 0 0 0 0 0 0 1 0 1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 1 0]
Actual Value - [[1]
[1]
[0]
[0]
[0]
[1]
[1]
[0]
[0]
[0]
[1]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[1]
[0]
[0]
[1]
[0]
[0]
[0]
[1]
[1]]
| Apache-2.0 | ML_Assignment 02_Diabetes Prediction/Diabetes_prediction.ipynb | parth111999/Data-Science-Assignment |
Mixture Density Networks with PyTorch Related posts:JavaScript [implementation](http://blog.otoro.net/2015/06/14/mixture-density-networks/).TensorFlow [implementation](http://blog.otoro.net/2015/11/24/mixture-density-networks-with-tensorflow/). | import matplotlib.pyplot as plt
import numpy as np
import torch
import math
from torch.autograd import Variable
import torch.nn as nn | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
Simple Data Fitting Before we talk about MDN's, we try to perform some simple data fitting using PyTorch to make sure everything works. To get started, let's try to quickly build a neural network to fit some fake data. As neural nets of even one hidden layer can be universal function approximators, we can see if we c... | NSAMPLE = 1000
x_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T
r_data = np.float32(np.random.normal(size=(NSAMPLE,1)))
y_data = np.float32(np.sin(0.75*x_data)*7.0+x_data*0.5+r_data*1.0)
plt.figure(figsize=(8, 8))
plot_out = plt.plot(x_data,y_data,'ro',alpha=0.3)
plt.show() | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We will define this simple neural network one-hidden layer and 100 nodes:$Y = W_{out} \max( W_{in} X + b_{in}, 0) + b_{out}$ | # N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
# from (https://github.com/jcjohnson/pytorch-examples)
N, D_in, H, D_out = NSAMPLE, 1, 100, 1
# Create random Tensors to hold inputs and outputs, and wrap them in Variables.
# since NSAMPLE is not large, we train entire data... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We can define a loss function as the sum of square error of the output vs the data (we can add regularisation if we want). | loss_fn = torch.nn.MSELoss() | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We will also define a training loop to minimise the loss function later. We can use the RMSProp gradient descent optimisation method. | learning_rate = 0.01
optimizer = torch.optim.RMSprop(model.parameters(), lr=learning_rate, alpha=0.8)
for t in range(100000):
y_pred = model(x)
loss = loss_fn(y_pred, y)
if (t % 10000 == 0):
print(t, loss.data[0])
optimizer.zero_grad()
loss.backward()
optimizer.step()
x_test = np.float32(np.random.unifo... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We see that the neural network can fit this sinusoidal data quite well, as expected. However, this type of fitting method only works well when the function we want to approximate with the neural net is a one-to-one, or many-to-one function. Take for example, if we invert the training data:$x=7.0 \sin( 0.75 y) + 0.5 y+ ... | temp_data = x_data
x_data = y_data
y_data = temp_data
plt.figure(figsize=(8, 8))
plot_out = plt.plot(x_data,y_data,'ro',alpha=0.3)
plt.show() | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
If we were to use the same method to fit this inverted data, obviously it wouldn't work well, and we would expect to see a neural network trained to fit only to the square mean of the data. | x = Variable(torch.from_numpy(x_data.reshape(NSAMPLE, D_in)))
y = Variable(torch.from_numpy(y_data.reshape(NSAMPLE, D_out)), requires_grad=False)
learning_rate = 0.01
optimizer = torch.optim.RMSprop(model.parameters(), lr=learning_rate, alpha=0.8)
for t in range(3000):
y_pred = model(x)
loss = loss_fn(y_pred, y)
... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
Our current model only predicts one output value for each input, so this approach will fail miserably. What we want is a model that has the capacity to predict a range of different output values for each input. In the next section we implement a Mixture Density Network (MDN) to achieve this task. Mixture Density Netwo... | NHIDDEN = 100 # hidden units
KMIX = 20 # number of mixtures
class MDN(nn.Module):
def __init__(self, hidden_size, num_mixtures):
super(MDN, self).__init__()
self.fc_in = nn.Linear(1, hidden_size)
self.relu = nn.ReLU()
self.pi_out = torch.nn.Sequential(
nn.Linear(hidden_size, num_mixtures),
... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
Let's define the inverted data we want to train our MDN to predict later. As this is a more involved prediction task, I used a higher number of samples compared to the simple data fitting task earlier. | NSAMPLE = 2500
y_data = np.float32(np.random.uniform(-10.5, 10.5, (1, NSAMPLE))).T
r_data = np.float32(np.random.normal(size=(NSAMPLE,1))) # random noise
x_data = np.float32(np.sin(0.75*y_data)*7.0+y_data*0.5+r_data*1.0)
x_train = Variable(torch.from_numpy(x_data.reshape(NSAMPLE, 1)))
y_train = Variable(torch.from_num... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We cannot simply use the min square error L2 lost function in this task the output is an entire description of the probability distribution. A more suitable loss function is to minimise the logarithm of the likelihood of the distribution vs the training data:$CostFunction(y | x) = -\log[ \sum_{k}^K \Pi_{k}(x) \phi(y, \... | oneDivSqrtTwoPI = 1.0 / math.sqrt(2.0*math.pi) # normalisation factor for gaussian.
def gaussian_distribution(y, mu, sigma):
# braodcast subtraction with mean and normalization to sigma
result = (y.expand_as(mu) - mu) * torch.reciprocal(sigma)
result = - 0.5 * (result * result)
return (torch.exp(result) * torch... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
Let's define our model, and use the Adam optimizer to train our model below: | model = MDN(hidden_size=NHIDDEN, num_mixtures=KMIX)
learning_rate = 0.00001
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(20000):
(out_pi, out_sigma, out_mu) = model(x_train)
loss = mdn_loss_function(out_pi, out_sigma, out_mu, y_train)
if (t % 1000 == 0):
print(t, loss.data... | 0 4.988687992095947
1000 3.4866292476654053
2000 3.1824162006378174
3000 2.9246561527252197
4000 2.7802634239196777
5000 2.672682523727417
6000 2.5783588886260986
7000 2.5089898109436035
8000 2.4450607299804688
9000 2.398449420928955
10000 2.3576488494873047
11000 2.3166143894195557
12000 2.276536464691162
13000 2.2393... | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
We want to use our network to generate the parameters of the pdf for us to sample from. In the code below, we will sample $M=10$ values of $y$ for every $x$ input, and compare the sampled results with the training data. | x_test_data = np.float32(np.random.uniform(-15, 15, (1, NSAMPLE))).T
x_test = Variable(torch.from_numpy(x_test_data.reshape(NSAMPLE, 1)))
(out_pi_test, out_sigma_test, out_mu_test) = model(x_test)
out_pi_test_data = out_pi_test.data.numpy()
out_sigma_test_data = out_sigma_test.data.numpy()
out_mu_test_data = out_mu_tes... | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
In the above graph, we plot out the generated data we sampled from the MDN distribution, in blue. We also plot the original training data in red over the predictions. Apart from a few outliers, the distributions seem to match the data. We can also plot a graph of $\mu(x)$ as well to interpret what the neural net is act... | plt.figure(figsize=(8, 8))
plt.plot(x_test_data,out_mu_test_data,'g.', x_data,y_data,'r.',alpha=0.3)
plt.show() | _____no_output_____ | MIT | pytorch_notebooks-master/mixtures_density_network_relu_version.ipynb | boyali/pytorch-mixture_of_density_networks |
LDA (Latent Dirichlet Allocation)In this notebook, I'll be showing you the practical example of topic modelling using LDA.For this I'll be using ABC news headlines dataset from kaggle - https://www.kaggle.com/therohk/million-headlines | # Let's first read the dataset
import pandas as pd
df = pd.read_csv("abcnews-date-text.csv")
# Let's check the head of the dataframe
df.head() | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Here our main focus is the headline_text column because we will be using these headlines to extract the topics. | df1 = df[:50000].drop("publish_date", axis = 1) | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Here I am taking only 50000 records. | df1.head()
# Length of the data
len(df1) | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Preprocessing | from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_df = 0.95, min_df = 3, stop_words = 'english')
# Create a document term matrix
dtm = cv.fit_transform(df1[0:50000]['headline_text'])
dtm | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Let's perfrom LDA***Here I'll be assuming that there are 20 topics present in this document*** | from sklearn.decomposition import LatentDirichletAllocation
lda = LatentDirichletAllocation(n_components = 20, random_state = 79)
# This will take some time to execute
lda.fit(dtm)
topics = lda.transform(dtm) | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Let's print 15 most common words for all the 20 topics | for index,topic in enumerate(lda.components_):
print(f'THE TOP 15 WORDS FOR TOPIC #{index}')
print([cv.get_feature_names()[i] for i in topic.argsort()[-15:]])
print('\n') | THE TOP 15 WORDS FOR TOPIC #0
['row', 'sale', 'telstra', 'indigenous', 'bid', 'campaign', 'budget', 'tax', 'airport', 'bomb', 'community', 'blast', 'funding', 'boost', 'security']
THE TOP 15 WORDS FOR TOPIC #1
['says', 'saddam', 'dump', 'qaeda', 'broken', 'gm', 'city', 'waste', 'israel', 'gets', 'industry', 'al', 'wa... | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Let's combine these topics with our original headlines | df1['Headline Topic'] = topics.argmax(axis = 1)
df1.head() | _____no_output_____ | MIT | B2-NLP/Ajay_NLP_TopicModelling.ipynb | Shreyansh-Gupta/Open-contributions |
Dictionary Details 1. r["title"] tells you the noramlized title2. r["gender"] tells you the gender (binary for simplicity, determined from the pronouns)3. 3. r["start_pos"] indicates the length of the first sentence.4. r["raw"] has the entire bio5. The field r["bio"] contains a scrubbed version of the bio (with the pe... | test_bio = all_bios[0]
test_bio['bio']
test_bio['raw'] | _____no_output_____ | MIT | Visualisation_codes.ipynb | punyajoy/biosbias |
Distribution of occupation | occupation_dict={}
for bio in all_bios:
occupation=bio['title']
try:
occupation_dict[occupation] = 1
except KeyError:
occupation_dict[occupation] += 1
import matplotlib.pyplot as plt
import numpy as np
keys = x.keys()
vals = x.values()
plt.bar(keys, np.divide(list(vals), sum(vals)), labe... | _____no_output_____ | MIT | Visualisation_codes.ipynb | punyajoy/biosbias |
Mithun add your codes here Model 1 : Bag of words | word_dict={}
for bio in all_bios:
index_to_start=bio['start_pos']
tokens=bio['raw'][index_to_start:].split()
for tok in tokens:
tok = tok.strip().lower()
try:
word_dict[tok] += 1
except:
word_dict[tok] = 1
len(list(word_dict))
import nltk
import pan... | _____no_output_____ | MIT | Visualisation_codes.ipynb | punyajoy/biosbias |
forwardfill - ffill - none value will be filled with the previous data backwardfill= null value will be filled with the next value | data.fillna(method='ffill')
df3 = pd.DataFrame({'Data':[10,20,30,np.nan,50,60],
'float':[1.5,2.5,3.2,4.5,5.5,np.nan],
})
df3
data.fillna(method='bfill')
import numpy as np
import pandas as pd
Data = pd.read_csv('california_cities.csv')
Data
Data.head()
Data.tail()
Data.describe()
D... | _____no_output_____ | Apache-2.0 | pandas.ipynb | Nikhila-padmanabhan/Python-project |
Process all microCT and save the output.This code begins by reading the CT data from every directory in ../data/microCT and processing it into a dataframe. It then stores these dataframes in a dictionary (key: site code, value: dataframe).The dictionary is then saved as a pickle file in data/microCT. | import os
import pandas as pd
import pickle
output_frames = {}
for site in os.listdir('../data/microCT'):
if '.' not in site:
data_dir='../data/microCT/' + site + '/'
[SSA_CT,height_min,height_max]=read_CT_txt_files(data_dir)
fig,ax = plt.subplots()
ax.plot(6/917/SSA_CT*1... | _____no_output_____ | BSD-3-Clause | notebooks/CheckOutCT.ipynb | chang306/microstructure |
Test that the saved data can be read out and plotted again The plots below should match the plots above! | # read data from pickle file
frames = pickle.load(open('../data/microCT/processed_mCT.p', 'rb'))
for site in frames.keys():
# extract dataframe from dict
df = frames[site]
# plot
fig,ax = plt.subplots()
ax.plot(df['Equiv. Diam (mm)'],
df['height (cm)'])
ax... | _____no_output_____ | BSD-3-Clause | notebooks/CheckOutCT.ipynb | chang306/microstructure |
Environment | %env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%autosave 20
import csv
import pandas as pd
from keras.backend import tf as ktf
import sys
import cv2
import six
# keras
import keras
from keras.models import Mo... | env: CUDA_DEVICE_ORDER=PCI_BUS_ID
env: CUDA_VISIBLE_DEVICES=0
| MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Load images | #[str(x) for x in list(SAMPLE_DATA_PATH.iterdir())]
logs = pd.DataFrame()
num_tracks = [0, 0]
include_folders = [
'/home/downloads/CarND-Behavioral-Cloning-P3/data/all/IMG',
'/home/downloads/CarND-Behavioral-Cloning-P3/data/all/driving_log_track1_recovery.csv',
'/home/downloads/CarND-Behavioral-Cloning-P3/d... | /home/downloads/CarND-Behavioral-Cloning-P3/data/all/driving_log_track1_recovery.csv 1458
/home/downloads/CarND-Behavioral-Cloning-P3/data/all/driving_log_track2_drive4.csv 10252
/home/downloads/CarND-Behavioral-Cloning-P3/data/all/driving_log_track2_curve.csv 6617
/home/downloads/CarND-Behavioral-Cloning-P3/data... | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Preprocessing and Augmentation | IMG_FOLDER_PATH = SAMPLE_DATA_PATH/'IMG'
def get_img_files(img_folder_path):
image_files = []
labels = dict()
correction = 0.2
for log in logs.iterrows():
center, left, right, y = log[1][:4]
for i, img_path in enumerate([center, left, right]):
img_path = img_path.split('/')... | _____no_output_____ | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Create data generator for Keras model training | # adpated from https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly.html
class GeneratorFromFiles(keras.utils.Sequence):
'''Generate data from list of image files.'''
def __init__(self, list_files, labels, batch_size=64,
dim=(160, 320, 3),
post_dim=(66... | _____no_output_____ | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Visualize flipping the image | data_generator = GeneratorFromFiles(TRAIN_IMG_FILES, LABELS)
res = next(iter(data_generator))
plt.imshow(res[0][56].astype(int))
plt.imshow(augment_data(res[0][56], res[1][60], 0.0)[0].astype(int))
plt.imshow(cv2.resize(res[0][56], (200, 66)).astype(int))
plt.imshow(cv2.resize(augment_data(res[0][56], res[1][60], 0.0)[... | _____no_output_____ | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Model Architecture and Parameter Nvidia model | def _bn_act_dropout(input, dropout_rate):
"""Helper to build a BN -> activation block
"""
norm = BatchNormalization(axis=2)(input)
relu = Activation('elu')(norm)
return Dropout(dropout_rate)(relu)
def _conv_bn_act_dropout(**conv_params):
'''Helper to build a conv -> BN -> activation block -> ... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 66, 200, 3) 0
________________________________________________________... | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Training and Validation | %%time
trn_data_generator = GeneratorFromFiles(TRAIN_IMG_FILES, LABELS, resize=True)
val_data_generator = GeneratorFromFiles(VAL_IMG_FILES, LABELS, resize=True)
model.fit_generator(trn_data_generator,
validation_data=val_data_generator,
epochs=12,
workers=... | _____no_output_____ | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Fine-Tuning the Model | %%time
opt = Adam(lr=1e-5)
model.compile(loss='mse', optimizer=opt)
model.fit_generator(trn_data_generator,
validation_data=val_data_generator,
epochs=5,
workers=3,
use_multiprocessing=True,
verbose=1)
%%time
opt = A... | Epoch 1/5
2243/2243 [==============================] - 180s 80ms/step - loss: 0.0568 - val_loss: 0.0523
Epoch 2/5
2243/2243 [==============================] - 180s 80ms/step - loss: 0.0566 - val_loss: 0.0522
Epoch 3/5
2243/2243 [==============================] - 190s 85ms/step - loss: 0.0563 - val_loss: 0.0522
Epoch 4/... | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Saving Model | model.save(ROOT_PATH/'models/model-nvidia-base-3.h5', include_optimizer=False) | _____no_output_____ | MIT | notebooks/behavior_cloning_tutorial-Copy1.ipynb | Jetafull/CarND-Behavioral-Cloning-P3 |
Sample Runs=========Basic Run--------The simplest test run requires that we specify a reference directory and atest directory. The default file matching assumes that our reference andtest files match names exactly and both end in '.xml'. With just thetwo directory arguments, we get micro-average scores for the defaul... | !python etude.py \
--reference-input tests/data/i2b2_2016_track-1_reference \
--test-input tests/data/i2b2_2016_track-1_test
| 100% (10 of 10) |##########################| Elapsed Time: 0:00:01 Time: 0:00:01
exact TP FP TN FN
micro-average 340.0 8.0 0.0 105.0
| Apache-2.0 | jupyter/README.ipynb | MUSC-TBIC/etude-engine |
In the next sample runs, you can see how to include a per-file score breakdown and a per-annotation-type score breakdown. | !python etude.py \
--reference-input tests/data/i2b2_2016_track-1_reference \
--test-input tests/data/i2b2_2016_track-1_test \
--by-file
!python etude.py \
--reference-input tests/data/i2b2_2016_track-1_reference \
--test-input tests/data/i2b2_2016_track-1_test \
--by-type | 100% (10 of 10) |##########################| Elapsed Time: 0:00:01 Time: 0:00:01
exact TP FP TN FN
micro-average 340.0 8.0 0.0 105.0
Age 63.0 2.0 0.0 29.0
DateTime 91.0 2.0 0.0 33.0
HCUnit 61.0 4.0 0.0 15.0
OtherID 7.0 0.0 0.0 0.0
OtherLoc 1.0 0.0 0.0 4.0
OtherOrg 18.0 0.0 0.0 3.0
Patient 16.0 0.0 0.0 3.0
PhoneFax 5.0... | Apache-2.0 | jupyter/README.ipynb | MUSC-TBIC/etude-engine |
Scoring on Different Fields-----------------------The above examples show scoring based on the default key in theconfiguration file used for matching the reference to the testconfiguration. You may wish to group annotations on different fields,such as the parent class or long description. | !python etude.py \
--reference-input tests/data/i2b2_2016_track-1_reference \
--test-input tests/data/i2b2_2016_track-1_test \
--by-type
!python etude.py \
--reference-input tests/data/i2b2_2016_track-1_reference \
--test-input tests/data/i2b2_2016_track-1_test \
--by-type \
--score-key "Pa... | 100% (10 of 10) |##########################| Elapsed Time: 0:00:01 Time: 0:00:01
exact TP FP TN FN
micro-average 340.0 8.0 0.0 105.0
Age Greater than 89 63.0 2.0 0.0 29.0
Date and Time Information 91.0 2.0 0.0 33.0
Electronic Address Information 2.0 0.0 0.0 0.0
Health Care Provider Name 54.0 0.0 0.0 10.0
Health Care U... | Apache-2.0 | jupyter/README.ipynb | MUSC-TBIC/etude-engine |
Testing=====Unit testing is done with the pytest module.Because of a bug in how tests are processed in Python 2.7, you should run pytest indirectly rather than directly.An [HTML-formatted coverage guide](../htmlcov/index.html) will be generated locally under the directory containing this code. | !python -m pytest --cov-report html --cov=./ tests | [1m============================= test session starts ==============================[0m
platform darwin -- Python 2.7.13, pytest-3.1.1, py-1.4.34, pluggy-0.4.0
rootdir: /Users/pmh/git/etude, inifile:
plugins: cov-2.5.1
collected 107 items [0m[1m1m[1m
[0m
tests/test_args_and_configs.py ..................
tests/test... | Apache-2.0 | jupyter/README.ipynb | MUSC-TBIC/etude-engine |
Read the data | dfXtrain = pd.read_csv('preprocessed_csv/train_tree.csv', index_col='id', sep=';')
dfXtest = pd.read_csv('preprocessed_csv/test_tree.csv', index_col='id', sep=';')
dfYtrain = pd.read_csv('preprocessed_csv/y_train_tree.csv', header=None, names=['ID', 'COTIS'], sep=';')
dfYtrain = dfYtrain.set_index('ID') | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Preprocessing Вынесем var14, department и subreg. | dropped_col_names = ['var14', 'department', 'subreg']
def drop_cols(df):
return df.drop(dropped_col_names, axis=1), df[dropped_col_names]
train, dropped_train = drop_cols(dfXtrain)
test, dropped_test = drop_cols(dfXtest) | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Добавим инфу о величине города из subreg'a | def add_big_city_cols(df, dropped_df):
df['big'] = np.where(dropped_df['subreg'] % 100 == 0, 1, 0)
df['average'] = np.where(dropped_df['subreg'] % 10 == 0, 1, 0)
df['average'] = df['average'] - df['big']
df['small'] = 1 - df['big'] - df['average']
return df
train = add_big_city_cols(train, dropped_t... | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Декодируем оставшиеся категориальные признаки | categorical = list(train.select_dtypes(exclude=[np.number]).columns)
categorical
list(test.select_dtypes(exclude=[np.number]).columns)
for col in categorical:
print(col, train[col].nunique()) | marque 154
energie_veh 5
profession 17
var6 5
var8 23
| MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
energie_veh и var6 с помощью get_dummies | small_cat = ['energie_veh', 'var6']
train = pd.get_dummies(train, columns=small_cat)
test = pd.get_dummies(test, columns=small_cat) | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Для остальных посчитаем сглаженные средние таргета | big_cat = ['marque', 'profession', 'var8'] | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Описание для начала | df = pd.concat([dfYtrain.describe()] + [train[col].value_counts().describe() for col in big_cat], axis=1)
df | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Сглаживать будем с 500 Будем использовать среднее, 25%, 50% и 75% Декодирование | class EncodeWithAggregates():
def __init__(self, cols, y_train, train, *tests):
self.cols = cols
self.y_train = y_train
self.train = train
self.tests = tests
self.Xs = (self.train,) + self.tests
self.smooth_coef = 500
self.miss_val = 'NAN'
se... | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Save routines | dfYtest = pd.DataFrame({'ID': dfXtest.index, 'COTIS': np.zeros(test.shape[0])})
dfYtest = dfYtest[['ID', 'COTIS']]
dfYtest.head()
def save_to_file(y, file_name):
dfYtest['COTIS'] = y
dfYtest.to_csv('results/{}'.format(file_name), index=False, sep=';')
model_name = 'lmse_without_size_xtr'
dfYtest_stacking = pd.D... | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Train XGB | from sklearn.ensemble import ExtraTreesRegressor
def plot_quality(grid_searcher, param_name):
means = []
stds = []
for elem in grid_searcher.grid_scores_:
means.append(np.mean(elem.cv_validation_scores))
stds.append(np.sqrt(np.var(elem.cv_validation_scores)))
means = np.array(means)
... | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Save | save_to_file_stacking(y_lmse_pred * 0.995, 'xbg_tune_eta015_num300_dropped_lmse.csv')
%%time
param = {'base_score':0.5, 'colsample_bylevel':1, 'colsample_bytree':1, 'gamma':0,
'eta':0.15, 'max_delta_step':0, 'max_depth':9,
'min_child_weight':1, 'nthread':-1,
'objective':'reg:linear',... | _____no_output_____ | MIT | xtr_tune_drop_lmse.ipynb | alexsyrom/datascience-ml-2 |
Test For The Best Machine Learning Algorithm For Prediction This notebook takes about 40 minutes to run, but we've already run it and saved the data for you. Please read through it, though, so that you understand how we came to the conclusions we'll use moving forward. Six AlgorithmsWe're going to compare six differen... | import warnings
warnings.filterwarnings("ignore")
import time
start = time.time()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from sklearn.metrics import confusion_matrix, precision_score
from sklearn.metrics import accuracy_score
from sklearn.preprocessing... | _____no_output_____ | UPL-1.0 | beginners/04.ML_Modelling.ipynb | MKulfan/redbull-analytics-hol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.