markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Standard Errors of the Standard Deviation
Above we explored how the spread in our estimates of the mean changed with sample size. We can similarly explore how our estimates of the standard deviation of the population change as we vary our sample size. | # the label arguments get used when we create a legend
plt.hist(std25, normed=True, alpha=0.75, histtype="stepfilled", label="n=25")
plt.hist(std50, normed=True, alpha=0.75, histtype="stepfilled", label="n=50")
plt.hist(std100, normed=True, alpha=0.75, histtype="stepfilled", label="n=100")
plt.hist(std200, normed=Tru... | Introduction-to-Simulation.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
You can show mathematically for normally distributed data, that the expected Standard Error of the Standard Deviation is approximately
$$
\mbox{Standard Error of Standard Deviation} \approx \frac{\sigma}{\sqrt{2(n-1)}}
$$
where $\sigma$ is the population standard deviation, and $n$ is the sample size.
Let's compare tha... | x = [25,50,100,200]
y = [ss25,ss50,ss100,ss200]
plt.scatter(x,y, label="Simulation estimates")
plt.xlabel("Sample size")
plt.ylabel("Std Error of Std Dev")
theory = [np.std(popn)/(np.sqrt(2.0*(i-1))) for i in range(10,250)]
plt.plot(range(10,250), theory, color='red', label="Theoretical expectation")
plt.xlim(0,300)
... | Introduction-to-Simulation.ipynb | Bio204-class/bio204-notebooks | cc0-1.0 |
TensorFlow Model Analysis
An Example of a Key TFX Library
This example colab notebook illustrates how TensorFlow Model Analysis (TFMA) can be used to investigate and visualize the characteristics of a dataset and the performance of a model. We'll use a model that we trained previously, and now you get to play with the... | !pip install -q -U \
tensorflow==2.0.0 \
tfx==0.15.0rc0 | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Import packages
We import necessary packages, including standard TFX component classes. | import csv
import io
import os
import requests
import tempfile
import zipfile
from google.protobuf import text_format
import tensorflow as tf
import tensorflow_data_validation as tfdv
import tensorflow_model_analysis as tfma
from tensorflow_metadata.proto.v0 import schema_pb2
tf.__version__
tfma.version.VERSION_ST... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Load The Files
We'll download a zip file that has everything we need. That includes:
Training and evaluation datasets
Data schema
Training results as EvalSavedModels
Note: We are downloading with HTTPS from a Google Cloud server. | # Download the zip file from GCP and unzip it
BASE_DIR = tempfile.mkdtemp()
TFMA_DIR = os.path.join(BASE_DIR, 'eval_saved_models-2.0')
DATA_DIR = os.path.join(TFMA_DIR, 'data')
OUTPUT_DIR = os.path.join(TFMA_DIR, 'output')
SCHEMA = os.path.join(TFMA_DIR, 'schema.pbtxt')
response = requests.get('https://storage.googlea... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Parse the Schema
Among the things we downloaded was a schema for our data that was created by TensorFlow Data Validation. Let's parse that now so that we can use it with TFMA. | schema = schema_pb2.Schema()
contents = tf.io.read_file(SCHEMA).numpy()
schema = text_format.Parse(contents, schema)
tfdv.display_schema(schema) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Use the Schema to Create TFRecords
We need to give TFMA access to our dataset, so let's create a TFRecords file. We can use our schema to create it, since it gives us the correct type for each feature. | datafile = os.path.join(DATA_DIR, 'eval', 'data.csv')
reader = csv.DictReader(open(datafile))
examples = []
for line in reader:
example = tf.train.Example()
for feature in schema.feature:
key = feature.name
if len(line[key]) > 0:
if feature.type == schema_pb2.FLOAT:
example.features.feature[ke... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Run TFMA and Render Metrics
Now we're ready to create a function that we'll use to run TFMA and render metrics. It requires an EvalSavedModel, a list of SliceSpecs, and an index into the SliceSpec list. It will create an EvalResult using tfma.run_model_analysis, and use it to create a SlicingMetricsViewer using tfma.... | def run_and_render(eval_model=None, slice_list=None, slice_idx=0):
"""Runs the model analysis and renders the slicing metrics
Args:
eval_model: An instance of tf.saved_model saved with evaluation data
slice_list: A list of tfma.slicer.SingleSliceSpec giving the slices
slice_idx: An integer index ... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Slicing and Dicing
We previously trained a model, and now we've loaded the results. Let's take a look at our visualizations, starting with using TFMA to slice along particular features. But first we need to read in the EvalSavedModel from one of our previous training runs.
To define the slice you want to visualize ... | # Load the TFMA results for the first training run
# This will take a minute
eval_model_base_dir_0 = os.path.join(TFMA_DIR, 'run_0', 'eval_model_dir')
eval_model_dir_0 = os.path.join(eval_model_base_dir_0,
max(os.listdir(eval_model_base_dir_0)))
eval_shared_model_0 = tfma.default_eval_sh... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Slices Overview
The default visualization is the Slices Overview when the number of slices is small. It shows the values of metrics for each slice. Since we've selected trip_start_hour above, it's showing us metrics like accuracy and AUC for each hour, which allows us to look for issues that are specific to some hours ... | slices = [tfma.slicer.SingleSliceSpec(columns=['trip_start_hour']),
tfma.slicer.SingleSliceSpec(columns=['trip_start_day']),
tfma.slicer.SingleSliceSpec(columns=['trip_start_month'])]
run_and_render(eval_model=eval_shared_model_0, slice_list=slices, slice_idx=0) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
You can create feature crosses to analyze combinations of features. Let's create a SliceSpec to look at a cross of trip_start_day and trip_start_hour: | slices = [tfma.slicer.SingleSliceSpec(columns=['trip_start_day', 'trip_start_hour'])]
run_and_render(eval_shared_model_0, slices, 0) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Crossing the two columns creates a lot of combinations! Let's narrow down our cross to only look at trips that start at noon. Then let's select accuracy from the visualization: | slices = [tfma.slicer.SingleSliceSpec(columns=['trip_start_day'], features=[('trip_start_hour', 12)])]
run_and_render(eval_shared_model_0, slices, 0) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Tracking Model Performance Over Time
Your training dataset will be used for training your model, and will hopefully be representative of your test dataset and the data that will be sent to your model in production. However, while the data in inference requests may remain the same as your training data, in many cases i... | def get_eval_result(base_dir, run_name, data_loc, slice_spec):
eval_model_base_dir = os.path.join(base_dir, run_name, "eval_model_dir")
versions = os.listdir(eval_model_base_dir)
eval_model_dir = os.path.join(eval_model_base_dir, max(versions))
output_dir = os.path.join(base_dir, "output", run_name)
eval_shar... | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Next, let's use TFMA to see how these runs compare using render_time_series.
How does it look today?
First, we'll imagine that we've trained and deployed our model yesterday, and now we want to see how it's doing on the new data coming in today. We can specify particular slices to look at. Let's compare our training r... | output_dirs = [os.path.join(TFMA_DIR, "output", run_name)
for run_name in ("run_0", "run_1", "run_2")]
eval_results_from_disk = tfma.load_eval_results(
output_dirs[:2], tfma.constants.MODEL_CENTRIC_MODE)
tfma.view.render_time_series(eval_results_from_disk, slices[0]) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Now we'll imagine that another day has passed and we want to see how it's doing on the new data coming in today, compared to the previous two days. Again add AUC and average loss by using the "Add metric series" menu: | eval_results_from_disk = tfma.load_eval_results(
output_dirs, tfma.constants.MODEL_CENTRIC_MODE)
tfma.view.render_time_series(eval_results_from_disk, slices[0]) | tfx_labs/Lab_6_Model_Analysis.ipynb | tensorflow/workshops | apache-2.0 |
Several Useful Functions
These are functions that I reuse often to encode the feature vector (FV). | # These are several handy functions that I use in my class:
# Encode a text field to dummy variables
def encode_text_dummy(df,name):
dummies = pd.get_dummies(df[name])
for x in dummies.columns:
dummy_name = "{}-{}".format(name,x)
df[dummy_name] = dummies[x]
df.drop(name, axis=1, inplace=Tru... | tf_kdd99.ipynb | jbliss1234/ML | apache-2.0 |
Read in Raw KDD-99 Dataset |
# This file is a CSV, just no CSV extension or headers
# Download from: http://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html
df = pd.read_csv("/Users/jeff/Downloads/data/kddcup.data_10_percent", header=None)
print("Read {} rows.".format(len(df)))
# df = df.sample(frac=0.1, replace=False) # Uncomment this line to s... | tf_kdd99.ipynb | jbliss1234/ML | apache-2.0 |
Encode the feature vector
Encode every row in the database. This is not instant! | # Now encode the feature vector
encode_numeric_zscore(df, 'duration')
encode_text_dummy(df, 'protocol_type')
encode_text_dummy(df, 'service')
encode_text_dummy(df, 'flag')
encode_numeric_zscore(df, 'src_bytes')
encode_numeric_zscore(df, 'dst_bytes')
encode_text_dummy(df, 'land')
encode_numeric_zscore(df, 'wrong_fragme... | tf_kdd99.ipynb | jbliss1234/ML | apache-2.0 |
Train the Neural Network | # Break into X (predictors) & y (prediction)
x, y = to_xy(df,'outcome')
# Create a test/train split. 25% test
# Split into train/test
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.25, random_state=42)
# Create a deep neural network with 3 hidden layers of 10, 20, 10
classifier = skflow.T... | tf_kdd99.ipynb | jbliss1234/ML | apache-2.0 |
nltk
Si vous utilisez la librairie nltk pour la première fois, il est nécessaire d'utiliser la commande suivante. Cette commande permet de télécharger de nombreux corpus de texte, mais également des informations grammaticales sur différentes langues. Information notamment nécessaire à l'étape de racinisation. | # nltk.download("all") | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Les données
Dans le dossier Cdiscount/data de ce répértoire vous trouverez les fichiers suivants :
cdiscount_test.csv.zip: Fichier d'apprentissage constitué de 1.000.000 de lignes
cdisount_test: Fichier test constitué de 50.000 lignes
### Read & Split Dataset
On définit une fonction permettant de lire le fichier d'ap... | def split_dataset(input_path, nb_line, tauxValid):
data_all = pd.read_csv(input_path,sep=",", nrows=nb_line)
data_all = data_all.fillna("")
data_train, data_valid = scv.train_test_split(data_all, test_size = tauxValid)
time_end = time.time()
return data_train, data_valid | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Bien que déjà réduit par rapport au fichier original du concours, contenant plus de 15M de lignes, le fichier cdiscount_test.csv.zip, contenant 1M de lignes est encore volumineux.
Nous allons charger en mémoire qu'une partie de ce fichier grace à l'argument nb_line afin d'éviter des temps de calcul trop couteux.
Nous... | input_path = "data/cdiscount_train.csv.zip"
nb_line=100000 # part totale extraite du fichier initial ici déjà réduit
tauxValid = 0.05
data_train, data_valid = split_dataset(input_path, nb_line, tauxValid)
# Cette ligne permet de visualiser les 5 premières lignes de la DataFrame
N_train = data_train.shape[0]
N_valid =... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
La commande suivante permet d'afficher les premières lignes du fichiers.
Vous pouvez observer que chaque produit possède 3 niveaux de Catégories, qui correspondent au différents niveaux de l'arborescence que vous retrouverez sur le site.
Il y a 44 catégories de niveau 1, 428 de niveau 2 et 3170 de niveau 3.
Dans ce T... | data_train.head(5) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
La commande suivante permet d'afficher un exemple de produits pour chaque Catégorie de niveau 1. | data_train.groupby("Categorie1").first()[["Description","Libelle","Marque"]] | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Distribution des classes | #Count occurence of each Categorie
data_count = data_train["Categorie1"].value_counts()
#Rename index to add percentage
new_index = [k+ ": %.2f%%" %(v*100/N_train) for k,v in data_count.iteritems()]
data_count.index = new_index
fig=plt.figure(figsize= (10,10))
ax = fig.add_subplot(1,1,1)
data_count.plot.barh(logx = Fa... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Q Que peut-on dire sur la distribution de ces classes?
Sauvegarde des données
On sauvegarde dans des csv les fichiers train et validation afin que ces mêmes fichiers soit ré-utilisés plus tard dans d'autre calepin | data_valid.to_csv("data/cdiscount_valid.csv", index=False)
data_train.to_csv("data/cdiscount_train_subset.csv", index=False) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Nettoyage des données
Afin de limiter la dimension de l'espace des variables ou features (i.e les mots présents dans le document), tout en conservant les informations essentielles, il est nécessaire de nettoyer les données en appliquant plusieurs étapes:
Chaque mot est écrit en minuscule.
Les termes numériques, de pon... | i = 0
description = data_train.Description.values[i]
print("Original Description : " + description) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Suppression des posibles balises HTML dans la description
Les descriptions produits étant parfois extraites d'autres sites commerçant, des balises HTML peuvent être incluts dans la description.
La librairie 'BeautifulSoup' permet de supprimer ces balises | from bs4 import BeautifulSoup #Nettoyage d'HTML
txt = BeautifulSoup(description,"html.parser",from_encoding='utf-8').get_text()
print(txt) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Conversion du texte en minuscule
Certaines mots peuvent être écrits en majuscule dans les descriptions textes, cela à pour conséquence de dupliquer le nombre de features et une perte d'information. | txt = txt.lower()
print(txt) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Remplacement de caractères spéciaux
Certains caractères spéciaux sont supprimés comme par exemple :
\u2026: …
\u00a0: NO-BREAK SPACE
Cette liste est non exhaustive et peut être etayée en fonction du jeu de donées étudié, de l'objectif souhaité ou encore du résultat de l'étude explorative. | txt = txt.replace(u'\u2026','.')
txt = txt.replace(u'\u00a0',' ')
print(txt) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Suppression des accents | txt = unicodedata.normalize('NFD', txt).encode('ascii', 'ignore').decode("utf-8")
print(txt) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Supprime les caractères qui ne sont ne sont pas des lettres minuscules
Une fois ces premières étapes passées, on supprime tous les caractères qui sont pas des lettres minusculres, c'est à dire les signes de ponctuation, les caractères numériques etc... | txt = re.sub('[^a-z_]', ' ', txt)
print(txt) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Remplace la description par une liste de mots (tokens), supprime les mots de moins de 2 lettres ainsi que les stopwords
On va supprimer maintenant tous les mots considérés comme "non-informatif". Par exemple : "le", "la", "de" ...
Des listes contenants ces mots sont proposés dans des libraires tels que nltk ou encore l... | ## listes de mots à supprimer dans la description des produits
## Depuis NLTK
nltk_stopwords = nltk.corpus.stopwords.words('french')
## Depuis Un fichier externe.
lucene_stopwords =open("data/lucene_stopwords.txt","r").read().split(",") #En local
## Union des deux fichiers de stopwords
stopwords = list(set(nltk_stopw... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
On applique également la suppression des accents à cette liste | stopwords = [unicodedata.normalize('NFD', sw).encode('ascii', 'ignore').decode("utf-8") for sw in stopwords]
stopwords[:10] | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Enfin on crée des tokens, liste de mots dans la description produit, en supprimant les éléments de notre description produit qui sont présent dans la liste de stopword. | tokens = [w for w in txt.split() if (len(w)>2) and (w not in stopwords)]
remove_words = [w for w in txt.split() if (len(w)<2) or (w in stopwords)]
print(tokens)
print(remove_words) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Racinisation (Stem) chaque tokens
Pour chaque mot de notre liste de token, on va ramener ce mot à sa racine au sens de l'algorithme de Snowball présent dans la librairie nltk.
Cette liste de mots néttoyé et racinisé va constitué les features de cette description produits. | ## Fonction de setmming de stemming permettant la racinisation
stemmer=nltk.stem.SnowballStemmer('french')
tokens_stem = [stemmer.stem(token) for token in tokens]
print(tokens_stem) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Fonction de nettoyage de texte
On définit une fonction clean-txt qui prend en entrée un texte de description produit et qui retourne le texte nettoyé en appliquant successivement les étapes présentés précedemment.
On définit également une fonction clean_marque qui contient signifcativement moins d'étape de nettoyage. | # Fonction clean générale
def clean_txt(txt):
### remove html stuff
txt = BeautifulSoup(txt,"html.parser",from_encoding='utf-8').get_text()
### lower case
txt = txt.lower()
### special escaping character '...'
txt = txt.replace(u'\u2026','.')
txt = txt.replace(u'\u00a0',' ')
### remove a... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Applique le nettoyage sur toutes les lignes de la DataFrame et créé deux nouvelles Dataframe (avant et sans l'étape de racinisation). |
# fonction de nettoyage du fichier(stemming et liste de mots à supprimer)
def clean_df(input_data, column_names= ['Description', 'Libelle', 'Marque']):
nb_line = input_data.shape[0]
print("Start Clean %d lines" %nb_line)
# Cleaning start for each columns
time_start = time.time()
clean_list=[]... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Nettoyage des DataFrames | # Take approximately 2 minutes fors 100.000 rows
warnings.filterwarnings("ignore")
data_valid_clean, data_valid_clean_stem = clean_df(data_valid)
warnings.filterwarnings("ignore")
data_train_clean, data_train_clean_stem = clean_df(data_train) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Affiche les 5 premières lignes de la DataFrame d'apprentissage après nettoyage. | data_train_clean.head(5)
data_train_clean_stem.head(5) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Taille du dictionnaire de mots pour le dataset avant et après la racinisation. | concatenate_text = " ".join(data_train["Description"].values)
list_of_word = concatenate_text.split(" ")
N = len(set(list_of_word))
print(N)
concatenate_text = " ".join(data_train_clean["Description"].values)
list_of_word = concatenate_text.split(" ")
N = len(set(list_of_word))
print(N)
concatenate_text = " ".join(da... | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Wordcloud
Les représentations Wordcloud permettent des représentations de l'ensemble des mots d'un corpus de documents. Dans cette représentation plus un mot apparait de manière fréquent dans le corpus, plus sa taille sera grande dans la représentation du corpus. | from wordcloud import WordCloud
A=WordCloud(background_color="black")
A.generate_from_text? | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Wordcloud de l'ensemble des description à l'état brut. | all_descr = " ".join(data_valid.Description.values)
wordcloud_word = WordCloud(background_color="black", collocations=False).generate_from_text(all_descr)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_word,cmap=plt.cm.Paired)
plt.axis("off")
plt.show() | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Wordcloud après racinisation et nettoyage | all_descr_clean_stem = " ".join(data_valid_clean_stem.Description.values)
wordcloud_word = WordCloud(background_color="black", collocations=False).generate_from_text(all_descr_clean_stem)
plt.figure(figsize=(10,10))
plt.imshow(wordcloud_word,cmap=plt.cm.Paired)
plt.axis("off")
plt.show() | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Vous pouvez observer que les mots "voir et "present" sont les plus représentés. Cela est du au fait que la pluspart des descriptions se terminent par "Voir la présentation". C'est deux mots ne sont donc pas informatif car présent dans beaucoup de catégorie différente. C'est une bon exemple de stopword propre à un probl... | data_valid_clean.to_csv("data/cdiscount_valid_clean.csv", index=False)
data_train_clean.to_csv("data/cdiscount_train_clean.csv", index=False)
data_valid_clean_stem.to_csv("data/cdiscount_valid_clean_stem.csv", index=False)
data_train_clean_stem.to_csv("data/cdiscount_train_clean_stem.csv", index=False) | Cdiscount/Part1-1-AIF-PythonNltk-Explore&CleanText-Cdiscount.ipynb | wikistat/Ateliers-Big-Data | mit |
Compilers: Numba and Cython
Requirement
To get Cython working, Winpython 3.7+ users should install "Microsoft Visual C++ Build Tools 2017" (visualcppbuildtools_full.exe, a 4 Go installation) at https://beta.visualstudio.com/download-visual-studio-vs/
To get Numba working, not-windows10 users may have to install "Micros... | # checking Numba JIT toolchain
import numpy as np
image = np.zeros((1024, 1536), dtype = np.uint8)
#from pylab import imshow, show
import matplotlib.pyplot as plt
from timeit import default_timer as timer
from numba import jit
@jit
def create_fractal(min_x, max_x, min_y, max_y, image, iters , mandelx):
height = im... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Cython (a compiler for writing C extensions for the Python language)
WinPython 3.5 and 3.6 users may not have mingwpy available, and so need "VisualStudio C++ Community Edition 2015" https://www.visualstudio.com/downloads/download-visual-studio-vs#d-visual-c | # Cython + Mingwpy compiler toolchain test
%load_ext Cython
%%cython -a
# with %%cython -a , full C-speed lines are shown in white, slowest python-speed lines are shown in dark yellow lines
# ==> put your cython rewrite effort on dark yellow lines
def create_fractal_cython(min_x, max_x, min_y, max_y, image, iters , m... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Graphics: Matplotlib, Pandas, Seaborn, Holoviews, Bokeh, bqplot, ipyleaflet, plotnine | # Matplotlib 3.4.1
# for more examples, see: http://matplotlib.org/gallery.html
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, rstride=... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Ipython Notebook: Interactivity & other | import IPython;IPython.__version__
# Audio Example : https://github.com/ipython/ipywidgets/blob/master/examples/Beat%20Frequencies.ipynb
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interactive
from IPython.display import Audio, display
def beat_freq(f1=220.0, f2=224.0):... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Mathematical: statsmodels, lmfit, | # checking statsmodels
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import statsmodels.api as sm
data = sm.datasets.anes96.load_pandas()
party_ID = np.arange(7)
labels = ["Strong Democrat", "Weak Democrat", "Independent-Democrat",
"Independent-Independent", "Independent-Republica... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
DataFrames: Pandas, Dask | #Pandas
import pandas as pd
import numpy as np
idx = pd.date_range('2000', '2005', freq='d', closed='left')
datas = pd.DataFrame({'Color': [ 'green' if x> 1 else 'red' for x in np.random.randn(len(idx))],
'Measure': np.random.randn(len(idx)), 'Year': idx.year},
index=idx.date)
datas.head() | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Split / Apply / Combine
Split your data into multiple independent groups.
Apply some function to each group.
Combine your groups back into a single data object. | datas.query('Measure > 0').groupby(['Color','Year']).size().unstack() | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Web Scraping: Beautifulsoup | # checking Web Scraping: beautifulsoup and requests
import requests
from bs4 import BeautifulSoup
URL = 'http://en.wikipedia.org/wiki/Franklin,_Tennessee'
req = requests.get(URL, headers={'User-Agent' : "Mining the Social Web"})
soup = BeautifulSoup(req.text, "lxml")
geoTag = soup.find(True, 'geo')
if geoTag and l... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Operations Research: Pulp | # Pulp example : minimizing the weight to carry 99 pennies
# (from Philip I Thomas)
# see https://www.youtube.com/watch?v=UmMn-N5w-lI#t=995
# Import PuLP modeler functions
from pulp import *
# The prob variable is created to contain the problem data
prob = LpProblem("99_pennies_Problem",LpMinimiz... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Deep Learning: see tutorial-first-neural-network-python-keras
Symbolic Calculation: sympy | # checking sympy
import sympy
a, b =sympy.symbols('a b')
e=(a+b)**5
e.expand() | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
SQL tools: sqlite, Ipython-sql, sqlite_bro, baresql, db.py | # checking Ipython-sql, sqlparse, SQLalchemy
%load_ext sql
%%sql sqlite:///.baresql.db
DROP TABLE IF EXISTS writer;
CREATE TABLE writer (first_name, last_name, year_of_death);
INSERT INTO writer VALUES ('William', 'Shakespeare', 1616);
INSERT INTO writer VALUES ('Bertold', 'Brecht', 1956);
SELECT * , sqlite_version()... | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
Qt libraries Demo
See Dedicated Qt Libraries Demo
Wrap-up | # optional scipy full test (takes up to 10 minutes)
#!cmd /C start cmd /k python.exe -c "import scipy;scipy.test()"
%pip list
!jupyter labextension list
!pip check
!pipdeptree
!pipdeptree -p pip | docs/Winpython_checker.ipynb | stonebig/winpython_afterdoc | mit |
IP Addresses of Compute Nodes | ips = saz.arm.view_info() | ipynb/Use Case - NIST Pedestrian and Face Detection on Simple Azure (under development).ipynb | lee212/simpleazure | gpl-3.0 |
Load Ansible API with IPs | from simpleazure.ansible_api import AnsibleAPI
ansible_client = AnsibleAPI(ips) | ipynb/Use Case - NIST Pedestrian and Face Detection on Simple Azure (under development).ipynb | lee212/simpleazure | gpl-3.0 |
Download Ansible Playbooks from Github
The ansible scripts for Pedestrian and Face Detection is here: https://github.com/futuresystems/pedestrian-and-face-detection.
We clone the repository using Github command line tools. | from simpleazure.github_cli import GithubCLI
git_client = GithubCLI()
git_client.set_repo('https://github.com/futuresystems/pedestrian-and-face-detection')
git_client.clone() | ipynb/Use Case - NIST Pedestrian and Face Detection on Simple Azure (under development).ipynb | lee212/simpleazure | gpl-3.0 |
Install Software Stacks to Targeted VMs | ansible_client.playbook(git_client.path + "/site.yml")
ansible_client.run() | ipynb/Use Case - NIST Pedestrian and Face Detection on Simple Azure (under development).ipynb | lee212/simpleazure | gpl-3.0 |
Check shed words pattern-matching requiremnts
Ref:
- Dodds, P. S., Harris, K. D., Kloumann, I. M., Bliss, C. A., & Danforth, C. M. (2011). Temporal patterns of happiness and information in a global social network: Hedonometrics and Twitter. PloS one, 6(12), e26752.
Notes:
- See 2.1 Algorithm for Hedonometer P3
- See... | """
Check all shed words
"""
if 1 == 1:
ind_shed_word_dict = pd.read_pickle(config.IND_SHED_WORD_DICT_PKL)
print(ind_shed_word_dict.values()) | develop/20171019-daheng-build_shed_words_freq_dicts.ipynb | adamwang0705/cross_media_affect_analysis | mit |
Build single shed words freq dict for topic_news docs
Result single dict format (for all topic_news docs)
{topic_ind_0: {
news_native_id_0_0: {shed_word_0_ind: shed_word_0_freq,
shed_word_1_ind: shed_word_1_freq,
...},
news_native_id_0_1: {shed_word_0_ind: shed_... | %%time
"""
Build single shed words freq dict for all topic_news docs
Register
TOPICS_NEWS_SHED_WORDS_FREQ_DICT_PKL = os.path.join(DATA_DIR, 'topics_news_shed_words_freq.dict.pkl')
in config
"""
if 0 == 1:
topics_news_shed_words_freq_dict = {}
for topic_ind, topic in enumerate(config.MANUALLY_SELECTED_... | develop/20171019-daheng-build_shed_words_freq_dicts.ipynb | adamwang0705/cross_media_affect_analysis | mit |
Check basic statistics | """
Print out sample news shed_words_freq_dicts inside single topic
"""
if 0 == 1:
target_topic_ind = 0
with open(config.TOPICS_NEWS_SHED_WORDS_FREQ_DICT_PKL, 'rb') as f:
topics_news_shed_words_freq_dict = pickle.load(f)
count = 0
for news_native_id, news_doc_shed_words_freq_dict i... | develop/20171019-daheng-build_shed_words_freq_dicts.ipynb | adamwang0705/cross_media_affect_analysis | mit |
Build shed words freq dicts for each topic_tweets doc separately
Result dict format (for each given topic_tweets doc)
{tweet_id_0_0: {shed_word_0_ind: shed_word_0_freq,
shed_word_1_ind: shed_word_1_freq,
...},
tweet_id_0_1: {shed_word_0_ind: shed_word_0_freq,
shed_word_1_i... | %%time
"""
Build shed words freq dict for each topic separately
Register
TOPICS_TWEETS_SHED_WORDS_FREQ_DICT_PKLS_DIR = os.path.join(DATA_DIR, 'topics_tweets_shed_words_freq_dict_pkls')
in config
Note:
- Number of tweets is large. Process each topic_tweets doc individually to avoid crash
- Execute second time fo... | develop/20171019-daheng-build_shed_words_freq_dicts.ipynb | adamwang0705/cross_media_affect_analysis | mit |
Check basic statistics | %%time
"""
Print out sample tweet shed_words_freq_dicts inside single topic
"""
if 0 == 1:
target_topic_ind = 0
topic_tweets_shed_words_freq_dict_pkl_file = os.path.join(config.TOPICS_TWEETS_SHED_WORDS_FREQ_DICT_PKLS_DIR, '{}.updated.dict.pkl'.format(target_topic_ind))
with open(topic_tweets_shed_words... | develop/20171019-daheng-build_shed_words_freq_dicts.ipynb | adamwang0705/cross_media_affect_analysis | mit |
Linear classifier on sensor data with plot patterns and filters
Decoding, a.k.a MVPA or supervised machine learning applied to MEG and EEG
data in sensor space. Fit a linear classifier with the LinearModel object
providing topographical patterns which are more neurophysiologically
interpretable [1]_ than the classifier... | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Romain Trachel <trachelr@gmail.com>
# Jean-Remi King <jeanremi.king@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne import io, EvokedArray
from mne.datasets import sample
from mne.decoding import Vectorizer, get_coef... | 0.14/_downloads/plot_linear_model_patterns.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Set parameters | raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.4
event_id = dict(aud_l=1, vis_l=3)
# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(.5, 25)
events = mne.read... | 0.14/_downloads/plot_linear_model_patterns.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Decoding in sensor space using a LogisticRegression classifier | clf = LogisticRegression()
scaler = StandardScaler()
# create a linear model with LogisticRegression
model = LinearModel(clf)
# fit the classifier on MEG data
X = scaler.fit_transform(meg_data)
model.fit(X, labels)
# Extract and plot spatial filters and spatial patterns
for name, coef in (('patterns', model.patterns... | 0.14/_downloads/plot_linear_model_patterns.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Let's do the same on EEG data using a scikit-learn pipeline | X = epochs.pick_types(meg=False, eeg=True)
y = epochs.events[:, 2]
# Define a unique pipeline to sequentially:
clf = make_pipeline(
Vectorizer(), # 1) vectorize across time and channels
StandardScaler(), # 2) normalize features across trials
LinearModel(LogisticRegre... | 0.14/_downloads/plot_linear_model_patterns.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
This cell can be used for all data sets except colon. colon is special because it has 3 types of events instead of just 2. Just change the first line to run a different data set. | #data = ds._pbc
#data = ds._lung
#data = ds._nwtco
data = ds._flchain
df = pd.read_csv(data['filename'][:-4] + "_org.csv",
sep=None, engine='python')
k = 4
# flchain has three guys at zero, remove them
if 'flchain' in data['filename']:
df = df[(df[data['timecol']] > 0)]
# Need shape later
n, d =... | DataSetStratification.ipynb | spacecowboy/article-annriskgroups-source | gpl-3.0 |
Print the labeled to data to a new file. | fname = data['filename']
print(fname)
df.to_csv(fname, na_rep='NA', index=False) | DataSetStratification.ipynb | spacecowboy/article-annriskgroups-source | gpl-3.0 |
Colon
Is kind of special. It has 3 events where two must be combined before stratification is possible. | data = ds._colon
df = pd.read_csv(data['filename'], sep=None, engine='python')
n, d = df.shape
k = 4
# Construct lists of events, censored
events = []
censored = []
for i in df['id'].unique():
x = ((df['id'] == i) & (df['etype'] == 1))
if df[x]['status'].sum() < 1:
censored.append(i)
else:
... | DataSetStratification.ipynb | spacecowboy/article-annriskgroups-source | gpl-3.0 |
Print data to file. | fname = data['filename'][:-8] + '.csv'
print(fname)
df.to_csv(fname, na_rep='NA', index=False) | DataSetStratification.ipynb | spacecowboy/article-annriskgroups-source | gpl-3.0 |
Model results
Rule learning and rule application in the matching task
Rule Learning > Rule Application | l1cope="3"
l2cope="1"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule Application > Rule Learning | l1cope="3"
l2cope="1"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule Learning > Baseline | l1cope="2"
l2cope="1"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Baseline > Rule Learning | l1cope="2"
l2cope="1"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule Application > Baseline | l1cope="1"
l2cope="1"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Baseline > Rule Application | l1cope="1"
l2cope="1"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
Image(sliced_img)
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule learning and rule application in the classification task
Rule Learning > Rule Application | l1cope="3"
l2cope="2"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule Learning > Baseline | l1cope="2"
l2cope="2"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Baseline > Rule Learning | l1cope="2"
l2cope="2"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule Application > Baseline | l1cope="1"
l2cope="2"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Baseline > Rule Application | l1cope="1"
l2cope="2"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule learning in the matching and classification tasks
Matching > Classification | l1cope="2"
l2cope="3"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Classification > Matching | l1cope="2"
l2cope="3"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Rule application in the matching and classification tasks
Matching > Classification | l1cope="1"
l2cope="3"
l3cope="1"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Classification > Matching | l1cope="1"
l2cope="3"
l3cope="2"
sliced_img,wb_img,cluster_corr,tstat_img,html_cl,html_t = paths()
render(html_cl,[wb_img,cluster_corr]) | thresholded_results/RulesFPC/model_1_FPC/model_1_FPC.ipynb | dpaniukov/RulesFPC | mit |
Define path to data: (It's a good idea to put it in a subdirectory of your notebooks folder, and then exclude that directory from git control by adding it to .gitignore.) | path = "data/dogscats/"
#path = "data/dogscats/sample/" | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
We have created a file most imaginatively called 'utils.py' to store any little convenience functions we'll want to use. We will discuss these as we use them. | import utils; reload(utils)
from utils import plots | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Use a pretrained VGG model with our Vgg16 class
Our first step is simply to use a model that has been fully created for us, which can recognise a wide variety (1,000 categories) of images. We will use 'VGG', which won the 2014 Imagenet competition, and is a very simple model to create and understand. The VGG Imagenet t... | # As large as you can, but no larger than 64 is recommended.
# If you have an older or cheaper GPU, you'll run out of memory, so will have to decrease this.
batch_size=64
# Import our class, and instantiate
import vgg16; reload(vgg16)
from vgg16 import Vgg16
vgg = Vgg16()
# Grab a few images at a time for training a... | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
(BTW, when Keras refers to 'classes', it doesn't mean python classes - but rather it refers to the categories of the labels, such as 'pug', or 'tabby'.)
Batches is just a regular python iterator. Each iteration returns both the images themselves, as well as the labels. | imgs,labels = next(batches) | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
That shows all of the steps involved in using the Vgg16 class to create an image recognition model using whatever labels you are interested in. For instance, this process could classify paintings by style, or leaves by type of disease, or satellite photos by type of crop, and so forth.
Next up, we'll dig one level deep... | from numpy.random import random, permutation
from scipy import misc, ndimage
from scipy.ndimage.interpolation import zoom
import keras
from keras import backend as K
from keras.utils.data_utils import get_file
from keras.models import Sequential, Model
from keras.layers.core import Flatten, Dense, Dropout, Lambda
from... | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Let's import the mappings from VGG ids to imagenet category ids and descriptions, for display purposes later. | FILES_PATH = 'http://files.fast.ai/models/'; CLASS_FILE='imagenet_class_index.json'
# Keras' get_file() is a handy function that downloads files, and caches them for re-use later
fpath = get_file(CLASS_FILE, FILES_PATH+CLASS_FILE, cache_subdir='models')
with open(fpath) as f: class_dict = json.load(f)
# Convert diction... | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Here's a few examples of the categories we just imported: | classes[:5] | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Model creation
Creating the model involves creating the model architecture, and then loading the model weights into that architecture. We will start by defining the basic pieces of the VGG architecture.
VGG has just one type of convolutional block, and one type of fully connected ('dense') block. Here's the convolution... | def ConvBlock(layers, model, filters):
for i in range(layers):
model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(filters, 3, 3, activation='relu'))
model.add(MaxPooling2D((2,2), strides=(2,2))) | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
...and here's the fully-connected definition. | def FCBlock(model):
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5)) | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
When the VGG model was trained in 2014, the creators subtracted the average of each of the three (R,G,B) channels first, so that the data for each channel had a mean of zero. Furthermore, their software that expected the channels to be in B,G,R order, whereas Python by default uses R,G,B. We need to preprocess our data... | # Mean of each channel as provided by VGG researchers
vgg_mean = np.array([123.68, 116.779, 103.939]).reshape((3,1,1))
def vgg_preprocess(x):
x = x - vgg_mean # subtract mean
return x[:, ::-1] # reverse axis bgr->rgb | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Now we're ready to define the VGG model architecture - look at how simple it is, now that we have the basic blocks defined! | def VGG_16():
model = Sequential()
model.add(Lambda(vgg_preprocess, input_shape=(3,224,224)))
ConvBlock(2, model, 64)
ConvBlock(2, model, 128)
ConvBlock(3, model, 256)
ConvBlock(3, model, 512)
ConvBlock(3, model, 512)
model.add(Flatten())
FCBlock(model)
FCBlock(model)
model... | deeplearning1/nbs/lesson1.ipynb | sainathadapa/fastai-courses | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.