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
Rather than using batches, we could just import all the data into an array to save some processing time. (In most examples I'm using the batches, however - just because that's how I happened to start out.)
trn = get_data(path+'train') val = get_data(path+'valid') save_array(path+'results/val.dat', val) save_array(path+'results/trn.dat', trn) val = load_array(path+'results/val.dat') trn = load_array(path+'results/trn.dat')
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Re-run sample experiments on full dataset We should find that everything that worked on the sample (see statefarm-sample.ipynb), works on the full dataset too. Only better! Because now we have more data. So let's see how they go - the models in this section are exact copies of the sample notebook models. Single conv ...
def conv1(batches): model = Sequential([ BatchNormalization(axis=1, input_shape=(3,224,224)), Convolution2D(32,3,3, activation='relu'), BatchNormalization(axis=1), MaxPooling2D((3,3)), Convolution2D(64,3,3, activation='relu'), BatchNormalizatio...
Epoch 1/2 18946/18946 [==============================] - 114s - loss: 0.2273 - acc: 0.9405 - val_loss: 2.4946 - val_acc: 0.2826 Epoch 2/2 18946/18946 [==============================] - 114s - loss: 0.0120 - acc: 0.9990 - val_loss: 1.5872 - val_acc: 0.5253 Epoch 1/4 18946/18946 [==============================] - 114s - ...
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Interestingly, with no regularization or augmentation we're getting some reasonable results from our simple convolutional model. So with augmentation, we hopefully will see some very good results. Data augmentation
gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05, shear_range=0.1, channel_shift_range=20, width_shift_range=0.1) batches = get_batches(path+'train', gen_t, batch_size=batch_size) model = conv1(batches) model.optimizer.lr = 0.0001 model.fit_generator(batches, batches.nb_sampl...
Epoch 1/15 18946/18946 [==============================] - 114s - loss: 0.2391 - acc: 0.9361 - val_loss: 1.2511 - val_acc: 0.6886 Epoch 2/15 18946/18946 [==============================] - 114s - loss: 0.2075 - acc: 0.9430 - val_loss: 1.1327 - val_acc: 0.7294 Epoch 3/15 18946/18946 [==============================] - 114s...
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
I'm shocked by *how* good these results are! We're regularly seeing 75-80% accuracy on the validation set, which puts us into the top third or better of the competition. With such a simple model and no dropout or semi-supervised learning, this really speaks to the power of this approach to data augmentation. Four conv...
gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05, shear_range=0.1, channel_shift_range=20, width_shift_range=0.1) batches = get_batches(path+'train', gen_t, batch_size=batch_size) model = Sequential([ BatchNormalization(axis=1, input_shape=(3,224,224)), Convol...
Epoch 1/10 18946/18946 [==============================] - 159s - loss: 0.3183 - acc: 0.8976 - val_loss: 1.0359 - val_acc: 0.7688 Epoch 2/10 18946/18946 [==============================] - 158s - loss: 0.2788 - acc: 0.9109 - val_loss: 1.5806 - val_acc: 0.6705 Epoch 3/10 18946/18946 [==============================] - 158s...
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
This is looking quite a bit better - the accuracy is similar, but the stability is higher. There's still some way to go however... Imagenet conv features Since we have so little data, and it is similar to imagenet images (full color photos), using pre-trained VGG weights is likely to be helpful - in fact it seems like...
vgg = Vgg16() model=vgg.model last_conv_idx = [i for i,l in enumerate(model.layers) if type(l) is Convolution2D][-1] conv_layers = model.layers[:last_conv_idx+1] conv_model = Sequential(conv_layers) (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = get_classes(path) con...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Batchnorm dense layers on pretrained conv layers Since we've pre-computed the output of the last convolutional layer, we need to create a network that takes that as input, and predicts our 10 classes. Let's try using a simplified version of VGG's dense layers.
def get_bn_layers(p): return [ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dropout(p/2), Dense(128, activation='relu'), BatchNormalization(), Dropout(p/2), Dense(128, activation='relu'), BatchNormalization(), Dropout(...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Looking good! Let's try pre-computing 5 epochs worth of augmented data, so we can experiment with combining dropout and augmentation on the pre-trained model. Pre-computed data augmentation + dropout We'll use our usual data augmentation parameters:
gen_t = image.ImageDataGenerator(rotation_range=15, height_shift_range=0.05, shear_range=0.1, channel_shift_range=20, width_shift_range=0.1) da_batches = get_batches(path+'train', gen_t, batch_size=batch_size, shuffle=False)
Found 18946 images belonging to 10 classes.
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
We use those to create a dataset of convolutional features 5x bigger than the training set.
da_conv_feat = conv_model.predict_generator(da_batches, da_batches.nb_sample*5) save_array(path+'results/da_conv_feat2.dat', da_conv_feat) da_conv_feat = load_array(path+'results/da_conv_feat2.dat')
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Let's include the real training data as well in its non-augmented form.
da_conv_feat = np.concatenate([da_conv_feat, conv_feat])
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Since we've now got a dataset 6x bigger than before, we'll need to copy our labels 6 times too.
da_trn_labels = np.concatenate([trn_labels]*6)
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Based on some experiments the previous model works well, with bigger dense layers.
def get_bn_da_layers(p): return [ MaxPooling2D(input_shape=conv_layers[-1].output_shape[1:]), Flatten(), Dropout(p), Dense(256, activation='relu'), BatchNormalization(), Dropout(p), Dense(256, activation='relu'), BatchNormalization(), Dropout(p...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Now we can train the model as usual, with pre-computed augmented data.
bn_model.fit(da_conv_feat, da_trn_labels, batch_size=batch_size, nb_epoch=1, validation_data=(conv_val_feat, val_labels)) bn_model.optimizer.lr=0.01 bn_model.fit(da_conv_feat, da_trn_labels, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) bn_model.optimizer.lr...
Train on 113676 samples, validate on 3478 samples Epoch 1/4 113676/113676 [==============================] - 16s - loss: 0.3837 - acc: 0.8775 - val_loss: 0.6904 - val_acc: 0.8197 Epoch 2/4 113676/113676 [==============================] - 16s - loss: 0.3576 - acc: 0.8872 - val_loss: 0.6593 - val_acc: 0.8209 Epoch 3/4 11...
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Looks good - let's save those weights.
bn_model.save_weights(path+'models/da_conv8_1.h5')
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Pseudo labeling We're going to try using a combination of [pseudo labeling](http://deeplearning.net/wp-content/uploads/2013/03/pseudo_label_final.pdf) and [knowledge distillation](https://arxiv.org/abs/1503.02531) to allow us to use unlabeled data (i.e. do semi-supervised learning). For our initial experiment we'll us...
val_pseudo = bn_model.predict(conv_val_feat, batch_size=batch_size)
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
...concatenate them with our training labels...
comb_pseudo = np.concatenate([da_trn_labels, val_pseudo]) comb_feat = np.concatenate([da_conv_feat, conv_val_feat])
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
...and fine-tune our model using that data.
bn_model.load_weights(path+'models/da_conv8_1.h5') bn_model.fit(comb_feat, comb_pseudo, batch_size=batch_size, nb_epoch=1, validation_data=(conv_val_feat, val_labels)) bn_model.fit(comb_feat, comb_pseudo, batch_size=batch_size, nb_epoch=4, validation_data=(conv_val_feat, val_labels)) bn_mode...
Train on 117154 samples, validate on 3478 samples Epoch 1/4 117154/117154 [==============================] - 17s - loss: 0.2837 - acc: 0.9134 - val_loss: 0.7901 - val_acc: 0.8200 Epoch 2/4 117154/117154 [==============================] - 17s - loss: 0.2760 - acc: 0.9155 - val_loss: 0.7648 - val_acc: 0.8275 Epoch 3/4 11...
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
That's a distinct improvement - even although the validation set isn't very big. This looks encouraging for when we try this on the test set.
bn_model.save_weights(path+'models/bn-ps8.h5')
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Submit We'll find a good clipping amount using the validation set, prior to submitting.
def do_clip(arr, mx): return np.clip(arr, (1-mx)/9, mx) keras.metrics.categorical_crossentropy(val_labels, do_clip(val_preds, 0.93)).eval() conv_test_feat = load_array(path+'results/conv_test_feat.dat') preds = bn_model.predict(conv_test_feat, batch_size=batch_size*2) subm = do_clip(preds,0.93) subm_name = path+'result...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
This gets 0.534 on the leaderboard. The "things that didn't really work" section You can safely ignore everything from here on, because they didn't really help. Finetune some conv layers too
for l in get_bn_layers(p): conv_model.add(l) for l1,l2 in zip(bn_model.layers, conv_model.layers[last_conv_idx+1:]): l2.set_weights(l1.get_weights()) for l in conv_model.layers: l.trainable =False for l in conv_model.layers[last_conv_idx+1:]: l.trainable =True comb = np.concatenate([trn, val]) gen_t = image.ImageDa...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Ensembling
drivers_ds = pd.read_csv(path+'driver_imgs_list.csv') drivers_ds.head() img2driver = drivers_ds.set_index('img')['subject'].to_dict() driver2imgs = {k: g["img"].tolist() for k,g in drivers_ds[['subject', 'img']].groupby("subject")} def get_idx(driver_list): return [i for i,f in enumerate(filenames) ...
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Built-in function
print(abs(4.5)) print(abs(-4.5))
4.5 4.5
MIT
mod_05_list_tuple_dict/Untitled0.ipynb
merazlab/python
all - Return True if all elements of the iterable are true (or if the iterable is empty)
a = [2, 3, 4, 5] b = [0] c = [] d = [2, 3, 4, 0] print(all(a)) print(all(b)) print(all(c)) print(all(d))
True False True False
MIT
mod_05_list_tuple_dict/Untitled0.ipynb
merazlab/python
any - Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
a = [2, 3, 4, 5] b = [0] c = [] d = [2, 3, 4, 0] print(any(a)) print(any(b)) print(any(c)) print(any(d))
True False False True
MIT
mod_05_list_tuple_dict/Untitled0.ipynb
merazlab/python
ascii
print(ascii(1111)) dir() dir(struct) meta = {} meta[item] = []
_____no_output_____
MIT
mod_05_list_tuple_dict/Untitled0.ipynb
merazlab/python
Using notebooks we will explore the process of trainign and consuming a modelFirst let's load some packages to maniupulate images
#r "nuget:SixLabors.ImageSharp,1.0.2"
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
Get imagesWe can download images from the web, let's create some helper function
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System.Net.Http; Image GetImage(string url) { var client = new HttpClient(); var image = client.GetByteArrayAsync(url).Result; return Image.Load(image); } var image = GetImage("https://user-images.githubusercontent.com/2546640/56708...
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
it would be better to see the image, let's use the foramtter api
using System.IO; using SixLabors.ImageSharp.Formats.Png; using Microsoft.DotNet.Interactive.Formatting; Formatter.Register<Image>((image, writer) => { var id = Guid.NewGuid().ToString("N"); using var stream = new MemoryStream(); image.Save(stream, new PngEncoder()); stream.Flush(); var data = strea...
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
Good but something smaller would be better
using SixLabors.ImageSharp.Processing; Image Reduce(Image source, int maxSize = 300){ var max = Math.Max(source.Width, source.Height); var ratio = ((double)(maxSize)) / max; return source.Clone(c => c.Resize((int)(source.Width * ratio), (int)(source.Height * ratio))); } Reduce(image)
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
Better, now I am interested in bayblade, let's display some
var urls = new string[]{ "https://cdn.shopify.com/s/files/1/0016/0674/6186/products/B154_1_1024x1024.jpg?v=1573909023", "https://i.ytimg.com/vi/yUH2QeluaIU/maxresdefault.jpg", "https://www.biggerbids.com/members/images/29371/public/8065336_-DSC5628-32467-26524-.jpg", "https://i.ytimg.com/vi/BT4SwVmnqqQ/...
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
Enter lobeWe will now use lobe and it's .NET Bindings to developa model to classify those images. Let's start lobe and have a look first, then we will proceed with loading the pacakges we need.
#r "nuget:lobe" #r "nuget:lobe.ImageSharp" using lobe; using lobe.ImageSharp;
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
Lobe can be accessed via web api let's use that for fast loops
#r "nuget:lobe.Http" using lobe.Http; var beyblades_start = new Uri("http://localhost:38100/predict/3af915df-14b7-4834-afbd-6615deca4e26"); var beyblades = new Uri("http://localhost:38100/predict/f56e1050-391e-4cd6-9bb9-ff74dc4d84f5"); var beyblades_2 = new Uri("http://localhost:38100/predict/f56e1050-391e-4cd6-9bb9-...
_____no_output_____
MIT
Notebooks/Classifier.ipynb
colombod/MachineTeaching
- Install TPOT within Anancoda - https://anaconda.org/conda-forge/tpot- More Details - https://epistasislab.github.io/tpot/using/- GitHub - https://github.com/EpistasisLab/tpot/
import pandas as pd from tpot import TPOTClassifier from sklearn.model_selection import train_test_split train = pd.read_csv("excel_full_train.csv") test = pd.read_csv("excel_test.csv") X = train.drop(['PassengerId','Survived'], axis = 1) y = train['Survived'] #### Use Test Train Split to divide into train and test imp...
_____no_output_____
MIT
Titanic Solution using Excel and Python/21_Titanic_Solution_TPOT_All_feat_30Jan2019.ipynb
KunaalNaik/YT_Kaggle_Titanic_Solution
Run AutoML with TPOT **Verbose** - How much information TPOT communicates while it is running.- 0 = none, 1 = minimal, 2 = high, 3 = all.- A setting of 2 or higher will add a progress bar during the optimization procedure.
#Set max time for 10 Minutes tpot = TPOTClassifier(verbosity=2, max_time_mins=1) tpot.fit(X_train, y_train) print(f'Train : {tpot.score(X_test, y_test):.3f}') print(f'Test : {tpot.score(X_train, y_train):.3f}')
Train : 0.840 Test : 0.867
MIT
Titanic Solution using Excel and Python/21_Titanic_Solution_TPOT_All_feat_30Jan2019.ipynb
KunaalNaik/YT_Kaggle_Titanic_Solution
Export Best Pipeline
tpot.export('Auto_ML_TPOT_titanic_pipeline2.py')
_____no_output_____
MIT
Titanic Solution using Excel and Python/21_Titanic_Solution_TPOT_All_feat_30Jan2019.ipynb
KunaalNaik/YT_Kaggle_Titanic_Solution
Prediction of Test
sub_test = test.drop(['PassengerId'], axis = 1) sub_test_pred = tpot.predict(sub_test).astype(int) AllSub = pd.DataFrame({ 'PassengerId': test['PassengerId'], 'Survived' : sub_test_pred }) AllSub.to_csv("Auto_ML_TPOT_Titanic_Solution.csv", index = False) #Kaggle LB Score - 0.78468
_____no_output_____
MIT
Titanic Solution using Excel and Python/21_Titanic_Solution_TPOT_All_feat_30Jan2019.ipynb
KunaalNaik/YT_Kaggle_Titanic_Solution
Display Sample Records
import gzip import json import re import os import sys import numpy as np import pandas as pd
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**Specify your directory here:**
DIR = './data'
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**This function shows how to load datasets**
def load_data(file_name, head = 500): ''' Given a *.json.gz file, returns a list of dictionaries, optionally can select the first n records ''' count = 0 data = [] with gzip.open(file_name) as fin: for l in fin: d = json.loads(l) count += 1 ...
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**Load and display sample records of books/authors/works/series**
poetry = load_data(os.path.join(DIR, 'goodreads_books_poetry.json.gz')) # books = load_data(os.path.join(DIR, 'goodreads_books.json.gz')) # authors = load_data(os.path.join(DIR, 'goodreads_book_authors.json.gz')) # works = load_data(os.path.join(DIR, 'goodreads_book_works.json.gz')) # series = load_data(os.path.join(D...
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**Load and display sample records of user-book interactions (shelves)**
interactions = load_data(os.path.join(DIR, 'goodreads_interactions_poetry.json.gz')) np.random.choice(interactions)
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**Load and display sample records of book reviews**
reviews = load_data(os.path.join(DIR, 'goodreads_reviews_poetry.json.gz')) np.random.choice(reviews)
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
**Load and display sample records of book reviews (with spoiler tags)**
spoilers = load_data(os.path.join(DIR, 'goodreads_reviews_spoiler.json.gz')) np.random.choice([s for s in spoilers if s['has_spoiler']]) # spoilers = load_data(os.path.join(DIR, 'goodreads_reviews_spoiler_raw.json.gz')) # np.random.choice([s for s in spoilers if 'view spoiler' in s['review_text']])
_____no_output_____
Apache-2.0
samples.ipynb
nancywen25/goodreads
Introduction to the Interstellar Medium Jonathan Williams Figure 4.2: Extinction curve uses extcurve_s16.py and cubicspline.py from https://faun.rc.fas.harvard.edu/eschlafly/apored/extcurve.html
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import extcurve_s16 fig = plt.figure(figsize=(6,4)) ax1 = fig.add_subplot(1,1,1) #ax1.set_xlabel('$\lambda$ (nm)', fontsize=16) ax1.set_xlabel('$\lambda\ (\mu m)$', fontsize=16) ax1.set_ylabel('$A(\lambda)/A_K$', fontsize=16) #ax1.set_xlim(350,2500) ...
R_V = 3.3 power law index = -1.76 R_V = 3.6 power law index = -1.72 R_V = 3.0 power law index = -1.79
CC0-1.0
dust/.ipynb_checkpoints/extinction-checkpoint.ipynb
CambridgeUniversityPress/IntroductionInterstellarMedium
dataset = [ ['i1','i2','i5'], ['i2', 'i4'], ['i2', 'i3'], ['i1', 'i2', 'i4'], ['i1', 'i3'], ['i2', 'i3'], ['i1','i3'], ['i1', 'i2', 'i3','i5'], ['i1', 'i2','i3']] import pandas as pd from mlxtend.preprocessing import TransactionEncoder te ...
_____no_output_____
Apache-2.0
ASSIGNMENT_7.ipynb
archana1822/DMDW
.. _data_tutorial:.. currentmodule:: seaborn Data structures accepted by seaborn===================================.. raw:: html As a data visualization library, seaborn requires that you provide it with data. This chapter explains the various ways to accomplish that task. Seaborn supports several different dataset f...
import numpy as np import pandas as pd import seaborn as sns sns.set_theme()
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Long-form vs. wide-form data----------------------------Most plotting functions in seaborn are oriented towards *vectors* of data. When plotting ``x`` against ``y``, each variable should be a vector. Seaborn accepts data *sets* that have more than one vector organized in some tabular fashion. There is a fundamental dis...
flights = sns.load_dataset("flights") flights.head()
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
With long-form data, columns in the table are given roles in the plot by explicitly assigning them to one of the variables. For example, making a monthly plot of the number of passengers per year looks like this:
sns.relplot(data=flights, x="year", y="passengers", hue="month", kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
The advantage of long-form data is that it lends itself well to this explicit specification of the plot. It can accommodate datasets of arbitrary complexity, so long as the variables and observations can be clearly defined. But this format takes some getting used to, because it is often not the model of the data that o...
flights_wide = flights.pivot(index="year", columns="month", values="passengers") flights_wide.head()
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Here we have the same three variables, but they are organized differently. The variables in this dataset are linked to the *dimensions* of the table, rather than to named fields. Each observation is defined by both the value at a cell in the table and the coordinates of that cell with respect to the row and column indi...
sns.relplot(data=flights_wide, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
This plot looks very similar to the one before. Seaborn has assigned the index of the dataframe to ``x``, the values of the dataframe to ``y``, and it has drawn a separate line for each month. There is a notable difference between the two plots, however. When the dataset went through the "pivot" operation that convert...
sns.relplot(data=flights, x="month", y="passengers", hue="year", kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
To achieve the same remapping with the wide-form dataset, we would need to transpose the table:
sns.relplot(data=flights_wide.transpose(), kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
(This example also illustrates another wrinkle, which is that seaborn currently considers the column variable in a wide-form dataset to be categorical regardless of its datatype, whereas, because the long-form variable is numeric, it is assigned a quantitative color palette and legend. This may change in the future).Th...
sns.catplot(data=flights_wide, kind="box")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
When using pandas to represent wide-form data, you are limited to just a few variables (no more than three). This is because seaborn does not make use of multi-index information, which is how pandas represents additional variables in a tabular format. The `xarray `_ project offers labeled N-dimensional array objects, w...
import matplotlib.pyplot as plt f = plt.figure(figsize=(7, 5)) gs = plt.GridSpec( ncols=6, nrows=2, figure=f, left=0, right=.35, bottom=0, top=.9, height_ratios=(1, 20), wspace=.1, hspace=.01 ) colors = [c + (.5,) for c in sns.color_palette()] f.add_subplot(gs[0, :], facecolor=".8") [ f.add_subpl...
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Messy data~~~~~~~~~~Many datasets cannot be clearly interpreted using either long-form or wide-form rules. If datasets that are clearly long-form or wide-form are `"tidy" `_, we might say that these more ambiguous datasets are "messy". In a messy dataset, the variables are neither uniquely defined by the keys nor by th...
anagrams = sns.load_dataset("anagrams") anagrams
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
The attention variable is *between-subjects*, but there is also a *within-subjects* variable: the number of possible solutions to the anagrams, which varied from 1 to 3. The dependent measure is a score of memory performance. These two variables (number and score) are jointly encoded across several columns. As a result...
anagrams_long = anagrams.melt(id_vars=["subidr", "attnr"], var_name="solutions", value_name="score") anagrams_long.head()
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Now we can make the plot that we want:
sns.catplot(data=anagrams_long, x="solutions", y="score", hue="attnr", kind="point")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Further reading and take-home points~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~For a longer discussion about tabular data structures, you could read the `"Tidy Data" `_ paper by Hadley Whickham. Note that seaborn uses a slightly different set of concepts than are defined in the paper. While the paper associates tidyness with ...
flights_dict = flights.to_dict() sns.relplot(data=flights_dict, x="year", y="passengers", hue="month", kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Many pandas operations, such as a the split-apply-combine operations of a group-by, will produce a dataframe where information has moved from the columns of the input dataframe to the index of the output. So long as the name is retained, you can still reference the data as normal:
flights_avg = flights.groupby("year").mean() sns.relplot(data=flights_avg, x="year", y="passengers", kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Additionally, it's possible to pass vectors of data directly as arguments to ``x``, ``y``, and other plotting variables. If these vectors are pandas objects, the ``name`` attribute will be used to label the plot:
year = flights_avg.index passengers = flights_avg["passengers"] sns.relplot(x=year, y=passengers, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Numpy arrays and other objects that implement the Python sequence interface work too, but if they don't have names, the plot will not be as informative without further tweaking:
sns.relplot(x=year.to_numpy(), y=passengers.to_list(), kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Options for visualizing wide-form data--------------------------------------The options for passing wide-form data are even more flexible. As with long-form data, pandas objects are preferable because the name (and, in some cases, index) information can be used. But in essence, any format that can be viewed as a single...
flights_wide_list = [col for _, col in flights_wide.items()] sns.relplot(data=flights_wide_list, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
The vectors in a collection do not need to have the same length. If they have an ``index``, it will be used to align them:
two_series = [flights_wide.loc[:1955, "Jan"], flights_wide.loc[1952:, "Aug"]] sns.relplot(data=two_series, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Whereas an ordinal index will be used for numpy arrays or simple Python sequences:
two_arrays = [s.to_numpy() for s in two_series] sns.relplot(data=two_arrays, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
But a dictionary of such vectors will at least use the keys:
two_arrays_dict = {s.name: s.to_numpy() for s in two_series} sns.relplot(data=two_arrays_dict, kind="line")
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
Rectangular numpy arrays are treated just like a dataframe without index information, so they are viewed as a collection of column vectors. Note that this is different from how numpy indexing operations work, where a single indexer will access a row. But it is consistent with how pandas would turn the array into a data...
flights_array = flights_wide.to_numpy() sns.relplot(data=flights_array, kind="line") # TODO once the categorical module is refactored, its single vectors will get special treatment # (they'll look like collection of singletons, rather than a single collection). That should be noted.
_____no_output_____
MIT
doc/tutorial/data_structure.ipynb
luzpaz/seaborn
风格迁移的实现本文件是集智学园开发的“火炬上的深度学习”课程的配套源代码。我们讲解了Prisma软件实现风格迁移的实现原理在这节课中,我们将学会玩图像的风格迁移。我们需要准备两张图像,一张作为化作风格,一张作为图像内容同时,在本文件中,我们还展示了如何实用GPU来进行计算 本文件是集智学园http://campus.swarma.org 出品的“火炬上的深度学习”第IV课的配套源代码
#导入必要的包 from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim from PIL import Image import matplotlib.pyplot as plt import torchvision.transforms as transforms import torchvision.models as models import copy # 是否用GPU计算,如果检测到有安装好的GPU,则利用它来计算 use_cuda = torch.cuda.is_av...
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
一、准备输入文件我们需要准备两张同样大小的文件,一张作为风格,一张作为内容
#风格图像的路径,自行设定 style = 'images/escher.jpg' #内容图像的路径,自行设定 content = 'images/portrait1.jpg' #风格损失所占比重 style_weight=1000 #内容损失所占比重 content_weight=1 #希望得到的图片大小(越大越清晰,计算越慢) imsize = 128 loader = transforms.Compose([ transforms.Resize(imsize), # 将加载的图像转变为指定的大小 transforms.ToTensor()]) # 将图像转化为tensor #图片加载函数 def...
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
二、风格迁移网络的实现值得注意的是,风格迁移的实现并没有训练一个神经网络,而是将已训练好的卷积神经网络价格直接迁移过来网络的学习过程并不体现为对神经网络权重的训练,而是训练一张输入的图像,让它尽可能地靠近内容图像的内容和风格图像的风格为了实现风格迁移,我们需要在迁移网络的基础上再构建一个计算图,这样可以加速计算。构建计算图分为两部:1、加载一个训练好的CNN;2、在原网络的基础上添加计算风格损失和内容损失的新计算层 1. 加载已训练好的大型网络VGG
cnn = models.vgg19(pretrained=True).features # 如果可能就用GPU计算: if use_cuda: cnn = cnn.cuda()
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
2. 重新定义新的计算模块
#内容损失模块 class ContentLoss(nn.Module): def __init__(self, target, weight): super(ContentLoss, self).__init__() # 由于网络的权重都是从target上迁移过来,所以在计算梯度的时候,需要把它和原始计算图分离 self.target = target.detach() * weight self.weight = weight self.criterion = nn.MSELoss() def forward(self, inpu...
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
二、风格迁移的训练 1. 首先,我们需要现准备一张原始的图像,可以是一张噪音图或者就是内容图
# 如果想从调整一张噪声图像开始,请用下面一行的代码 input_img = torch.randn(content_img.data.size()) if use_cuda: input_img = input_img.cuda() content_img = content_img.cuda() style_img = style_img.cuda() # 将选中的待调整图打印出来: plt.figure() imshow(input_img.data, title='Input Image')
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
2. 优化输入的图像(训练过程)
# 首先,需要先讲输入图像变成神经网络的参数,这样我们就可以用反向传播算法来调节这个输入图像了 input_param = nn.Parameter(input_img.data) #定义个优化器,采用LBFGS优化算法来优化(试验效果很好,它的特点是可以计算大规模数据的梯度下降) optimizer = optim.LBFGS([input_param]) # 迭代步数 num_steps=300 """运行风格迁移的主算法过程.""" print('正在构造风格迁移模型..') print('开始优化..') for i in range(num_steps): #每一个训练周期 # 限制输入...
_____no_output_____
Apache-2.0
07_StyleTransfer/图像风格迁移_Style_Transfer.ipynb
swarmapytorch/book_DeepLearning_in_PyTorch_Source
Overfitting and regularization (with ``gluon``)Now that we've built a [regularized logistic regression model from scratch](regularization-scratch.html), let's make this more efficient with ``gluon``. We recommend that you read that section for a description as to why regularization is a good idea. As always, we begin ...
from __future__ import print_function import mxnet as mx from mxnet import autograd from mxnet import gluon import mxnet.ndarray as nd import numpy as np ctx = mx.cpu() # for plotting purposes %matplotlib inline import matplotlib import matplotlib.pyplot as plt
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
The MNIST Dataset
mnist = mx.test_utils.get_mnist() num_examples = 1000 batch_size = 64 train_data = mx.gluon.data.DataLoader( mx.gluon.data.ArrayDataset(mnist["train_data"][:num_examples], mnist["train_label"][:num_examples].astype(np.float32)), batch_size, shuffle=True...
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Multiclass Logistic Regression
net = gluon.nn.Sequential() with net.name_scope(): net.add(gluon.nn.Dense(10))
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Parameter initialization
net.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx)
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Softmax Cross Entropy Loss
loss = gluon.loss.SoftmaxCrossEntropyLoss()
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
OptimizerBy default ``gluon`` tries to keep the coefficients from diverging by using a *weight decay* penalty. So, to get the real overfitting experience we need to switch it off. We do this by passing `'wd': 0.0'` when we instantiate the trainer.
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.01, 'wd': 0.0})
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Evaluation Metric
def evaluate_accuracy(data_iterator, net, loss_fun): acc = mx.metric.Accuracy() loss_avg = 0. for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(ctx).reshape((-1,784)) label = label.as_in_context(ctx) output = net(data) loss = loss_fun(output, label) ...
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Execute training loop
epochs = 700 moving_loss = 0. niter=0 loss_seq_train = [] loss_seq_test = [] acc_seq_train = [] acc_seq_test = [] for e in range(epochs): for i, (data, label) in enumerate(train_data): data = data.as_in_context(ctx).reshape((-1,784)) label = label.as_in_context(ctx) with autograd.record():...
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
RegularizationNow let's see what this mysterious *weight decay* is all about. We begin with a bit of math. When we add an L2 penalty to the weights we are effectively adding $\frac{\lambda}{2} \|w\|^2$ to the loss. Hence, every time we compute the gradient it gets an additional $\lambda w$ term that is added to $g_t$,...
net.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx, force_reinit=True) trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.01, 'wd': 0.001}) moving_loss = 0. niter=0 loss_seq_train = [] loss_seq_test = [] acc_seq_train = [] acc_seq_test = [] for e in range(epochs): for i,...
_____no_output_____
Apache-2.0
chapter02_supervised-learning/regularization-gluon.ipynb
andylamp/mxnet-the-straight-dope
Introduction**Prerequisites**- Python Fundamentals**Outcomes**- Understand the core pandas objects - Series - DataFrame - Index into particular elements of a Series and DataFrame - Understand what `.dtype`/`.dtypes` do - Make basic visualizations **Data**- US regional unemployment data from Bureau of Labor Stati...
import pandas as pd # Don't worry about this line for now! %matplotlib inline
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Sometimes it will be helpful to know which version of pandas we areusingWe can check this by running the code below SeriesThe first main pandas type we will introduce is called SeriesA Series is a single column of data, with row labels for eachobservationPandas refers to the row labels as the *index* of the Series Be...
values = [5.6, 5.3, 4.3, 4.2, 5.8, 5.3, 4.6, 7.8, 9.1, 8., 5.7] years = list(range(1995, 2017, 2)) unemp = pd.Series(data=values, index=years, name="Unemployment") unemp
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
We can look at the index and values in our Series
unemp.index unemp.values unemp.
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
What can we do with a Series object? `.head` and `.tail`Often our data will have many rows and we won’t want to display it allat onceThe methods `.head` and `.tail` show rows at the beginning and endof our Series, respectively
unemp.head() unemp.tail()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Basic PlottingWe can also plot data using the `.plot` methodThis is why we needed the `%matplotlib inline` — it tells the notebookto display figures inside the notebook itself*Note*: Pandas can do much more in terms of visualizationWe will talk about more advanced visualization features later
unemp.plot(kind="bar")
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Unique valuesIn this dataset it doesn’t make much sense, but we may want to find theunique values in a SeriesThis can be done with the `.unique` method
unemp.unique()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
IndexingSometimes we will want to select particular elements from a SeriesWe can do this using `.loc[index_things]`; where `index_things` isan item from the index, or a list of items in the indexWe will see this more in depth in a coming lecture, but for now wedemonstrate how to select one or multiple elements of the ...
unemp unemp.loc[[2009, 1995]] unemp.iloc[-1] unemp.loc[[1995, 2005, 2015]]
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
**Check for understanding**For each of the following exercises, we recommend reading the documentationfor help- Display only the first 2 elements of the Series using the `.head` method - Using the `plot` method, make a bar plot - Use `.loc` to select the lowest/highest unemployment rate shown in the Series - Run the...
unemp.loc[[unemp.idxmin(), unemp.idxmax()]]
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
DataFrameA DataFrame is how pandas stores one or more columns of dataWe can think a DataFrames a multiple Series stacked side by side ascolumnsThis is similar to a sheet in an Excel workbook or a table in a SQLdatabaseIn addition to row labels (an index), DataFrames also have column labelsWe refer to these column labe...
data = {"NorthEast": [5.9, 5.6, 4.4, 3.8, 5.8, 4.9, 4.3, 7.1, 8.3, 7.9, 5.7], "MidWest": [4.5, 4.3, 3.6, 4. , 5.7, 5.7, 4.9, 8.1, 8.7, 7.4, 5.1], "South": [5.3, 5.2, 4.2, 4. , 5.7, 5.2, 4.3, 7.6, 9.1, 7.4, 5.5], "West": [6.6, 6., 5.2, 4.6, 6.5, 5.5, 4.5, 8.6, 10.7, ...
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
We can retrieve the index and the DataFrame values in the same way wedid with a Series
unemp_region.index unemp_region.values
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
What can we do with a DataFrame?Pretty much everything we can do with a Series `.head` and `.tail`As with Series, we can use `.head` and `.tail` to show only thefirst or last `n` rows
unemp_region.head() unemp_region.tail(3)
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
PlottingWe can generate plots with the `.plot` methodNotice we now have a separate line for each column of data
unemp_region.plot()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
IndexingWe can also do indexing using `.loc`However, there is a little more to it than before because we can choosesubsets of both row and columns
unemp_region.head() unemp_region.loc[1995, "NorthEast"] unemp_region.loc[[1995, 2005], "South"] unemp_region.loc[1995, ["NorthEast", "National"]] unemp_region.loc[:, "NorthEast"] # `[string]` with no `.loc` extracts a whole column unemp_region["MidWest"]
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Computations with columnsPandas can do various computations and mathematical operations oncolumnsLet’s take a look at a few of them
# Divide by 100 to move from percent units to a rate unemp_region["West"] / 100 # Find maximum unemp_region["West"].max() unemp_region["West"].iloc[1:5] unemp_region["MidWest"].head(6) # Find the difference between two columns # Notice that pandas applies `-` to _all rows_ at one time # We'll see more of this throughou...
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
**Check for understanding**For each of the following, we recommend reading the documentation for help- Use introspection (or google-fu) to find a way to obtain a list with all of the column names in `unemp_region` - Using the `plot` method, make a bar plot. What does it look like now? - Use `.loc` to select the the...
unemp.dtype unemp_region.dtypes
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
DataFrames will only distinguish between a few types- Booleans (`bool`) - Floating point numbers (`float64`) - Integers (`int64`) - Dates (`datetime`) — we will learn this soon - Categorical data (`categorical`) - Everything else, including strings (`object`) In the future, we will often refer to the type of data...
str_unemp = unemp_region.copy() str_unemp["South"] = str_unemp["South"].astype(str) str_unemp.dtypes
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Everything *looks* ok…
str_unemp.head()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
But if we try to do something like compute the sum of all the columns,we get unexpected results…
str_unemp.sum()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
This happened because `.sum` effectively calls `+` on all rows ineach columnRecall that when we apply `+` to two strings, the result is thestrings mashed togetherSo in this case we saw that the entries in all the rows of the Southcolumn were stitched together into one long string Changing DataFramesWe can change the d...
unemp_region["UnweightedMean"] = (unemp_region["NorthEast"] + unemp_region["MidWest"] + unemp_region["South"] + unemp_region["West"])/4 unemp_region.head()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop
Changing valuesChanging the values inside of a DataFrame should be done sparinglyHowever, it can be done by assigning a value to a location in theDataFrame`df.loc[index, column] = value`
unemp_region.loc[1995, "UnweightedMean"] = 0.0 unemp_region.head()
_____no_output_____
MIT
2019-07-09__InDepthPandas/03_pandas_intro.ipynb
snowdj/UCF-MSDA-workshop