id
int64
0
25.6k
text
stringlengths
0
4.59k
11,500
fundamentals of machine learning in kerasweight regularization is added by passing weight regularizer instances to layers as keyword arguments let' add weight regularization to the movie-review classification network listing adding weight regularizat ion he model from keras import regularizers model models sequential(m...
11,501
overfitting and underfitting adding dropout dropout is one of the most effective and most commonly used regularization techniques for neural networksdeveloped by geoff hinton and his students at the university of toronto dropoutapplied to layerconsists of randomly dropping out (setting to zeroa number of output feature...
11,502
fundamentals of machine learning figured it must be because it would require cooperation between employees to successfully defraud the bank this made me realize that randomly removing different subset of neurons on each example would prevent conspiracies and thus reduce overfitting " the core idea is that introducing n...
11,503
the universal workflow of machine learning in this sectionwe'll present universal blueprint that you can use to attack and solve any machine-learning problem the blueprint ties together the concepts you've learned about in this problem definitionevaluationfeature engineeringand fighting overfitting defining the problem...
11,504
fundamentals of machine learning keep in mind that machine learning can only be used to memorize patterns that are present in your training data you can only recognize what you've seen before using machine learning trained on past data to predict the future is making the assumption that the future will behave like the ...
11,505
if different features take values in different ranges (heterogeneous data)then the data should be normalized you may want to do some feature engineeringespecially for small-data problems once your tensors of input data and target data are readyyou can begin to train models developing model that does better than baselin...
11,506
table fundamentals of machine learning choosing he right last -layer activation and loss function for your model problem ype last -layer activat ion loss function binary classification sigmoid binary_crossentropy multiclasssingle-label classification softmax categorical_crossentropy multiclassmultilabel classification ...
11,507
try different hyperparameters (such as the number of units per layer or the learning rate of the optimizerto find the optimal configuration optionallyiterate on feature engineeringadd new featuresor remove features that don' seem to be informative be mindful of the followingevery time you use feedback from your validat...
11,508
fundamentals of machine learning summary define the problem at hand and the data on which you'll train collect this dataor annotate it with labels if need be choose how you'll measure success on your problem which metrics will you monitor on your validation datadetermine your evaluation protocolhold-out validationk-fol...
11,509
deep learning in practice hapters - will help you gain practical intuition about how to solve realworld problems using deep learningand will familiarize you with essential deeplearning best practices most of the code examples in the book are concentrated in this second half licensed to
11,510
11,511
for computer vision this covers understanding convolutional neural networks (convnetsusing data augmentation to mitigate overfitting using pretrained convnet to do feature extraction fine-tuning pretrained convnet visualizing what convnets learn and how they make classification decisions this introduces convolutional n...
11,512
deep learning for computer vision introduction to convnets we're about to dive into the theory of what convnets are and why they have been so successful at computer vision tasks but firstlet' take practical look at simple convnet example it uses convnet to classify mnist digitsa task we performed in using densely conne...
11,513
as you go deeper in the network the number of channels is controlled by the first argument passed to the conv layers ( or the next step is to feed the last output tensor (of shape ( )into densely connected classifier network like those you're already familiar witha stack of dense layers these classifiers process vector...
11,514
deep learning for computer vision train_images train_images reshape(( )train_images train_images astype('float ' test_images test_images reshape(( )test_images test_images astype('float ' train_labels to_categorical(train_labelstest_labels to_categorical(test_labelsmodel compile(optimizer='rmsprop'loss='categorical_cro...
11,515
this key characteristic gives convnets two interesting propertiesthe patterns they learn are translation invariant after learning certain pattern in the lower-right corner of picturea convnet can recognize it anywherefor examplein the upper-left corner densely connected network would have to learn the pattern anew if i...
11,516
deep learning for computer vision different channels in that depth axis no longer stand for specific colors as in rgb inputratherthey stand for filters filters encode specific aspects of the input dataat high levela single filter could encode the concept "presence of face in the input,for instance in the mnist examplet...
11,517
width height input depth input feature map input patches dot product with kernel output depth transformed patches output feature map output depth figure how convolut ion works note that the output width and height may differ from the input width and height they may differ for two reasonsborder effectswhich can be count...
11,518
figure deep learning for computer vision valid locat ions of patches in input feat ure map if you want to get an output feature map with the same spatial dimensions as the inputyou can use padding padding consists of adding an appropriate number of rows and columns on each side of the input feature map so as to make it...
11,519
introduction to convnets understanding convolution strides the other factor that can influence output size is the notion of strides the description of convolution so far has assumed that the center tiles of the convolution windows are all contiguous but the distance between two successive windows is parameter of the co...
11,520
deep learning for computer vision stride in order to downsample the feature maps by factor of on the other handconvolution is typically done with windows and no stride (stride why downsample feature maps this waywhy not remove the max-pooling layers and keep fairly large feature maps all the way uplet' look at this opt...
11,521
use average pooling instead of max poolingwhere each local input patch is transformed by taking the average value of each channel over the patchrather than the max but max pooling tends to work better than these alternative solutions in nutshellthe reason is that features tend to encode the spatial presence of some pat...
11,522
deep learning for computer vision training convnet from scratch on small dataset having to train an image-classification model using very little data is common situationwhich you'll likely encounter in practice if you ever do computer vision in professional context "fewsamples can mean anywhere from few hundred to few ...
11,523
in the case of computer visionmany pretrained models (usually trained on the imagenet datasetare now publicly available for download and can be used to bootstrap powerful vision models out of very little data that' what you'll do in the next section let' start by getting your hands on the data downloading the data the ...
11,524
deep learning for computer vision following is the code to do this listing copying images rainingvalidationand est direct ories directory where you'll store your smaller dataset path to the directory where the original dataset was uncompressed import osshutil original_dataset_dir '/users/fchollet/downloads/kaggle_origi...
11,525
training convnet from scratch on small dataset fnames ['dog {jpgformat(ifor in range( )for fname in fnamessrc os path join(original_dataset_dirfnamedst os path join(train_dogs_dirfnameshutil copyfile(srcdstcopies the first , dog images to train_dogs_dir fnames ['dog {jpgformat(ifor in range( )for fname in fnamessrc os ...
11,526
deep learning for computer vision note the depth of the feature maps progressively increases in the network (from to )whereas the size of the feature maps decreases (from to this is pattern you'll see in almost all convnets because you're attacking binary-classification problemyou'll end the network with single unit ( ...
11,527
training convnet from scratch on small dataset dense_ (dense(none ===============================================================total params , , trainable params , , non-trainable params for the compilation stepyou'll go with the rmsprop optimizeras usual because you ended the network with single sigmoid unityou'll us...
11,528
deep learning for computer vision target_size=( )batch_size= class_mode='binary'understanding python generat ors python generator is an object that acts as an iteratorit' an object you can use with the for in operator generators are built using the yield operator here is an example of generator that yields integersdef ...
11,529
steps_per_epoch gradient descent steps--the fitting process will go to the next epoch in this casebatches are samplesso it will take batches until you see your target of , samples when using fit_generatoryou can pass validation_data argumentmuch as with the fit method it' important to note that this argument is allowed...
11,530
deep learning for computer vision figure training and validat ion accuracy figure training and validat ion loss these plots are characteristic of overfitting the training accuracy increases linearly over timeuntil it reaches nearly %whereas the validation accuracy stalls at - the validation loss reaches its minimum aft...
11,531
training convnet from scratch on small dataset would be exposed to every possible aspect of the data distribution at handyou would never overfit data augmentation takes the approach of generating more training data from existing training samplesby augmenting the samples via number of random transformations that yield b...
11,532
deep learning for computer vision image img_to_array(imgx reshape(( , shapeconverts it to numpy array with shape ( reshapes it to ( for batch in datagen flow(xbatch_size= )plt figure(iimgplot plt imshow(image array_to_img(batch[ ]) + if = break generates batches of randomly transformed images loops indefinitelyso you n...
11,533
training convnet from scratch on small dataset listing defining new convnet hat includes dropout model models sequential(model add(layers conv ( ( )activation='relu'input_shape=( ))model add(layers maxpooling (( ))model add(layers conv ( ( )activation='relu')model add(layers maxpooling (( ))model add(layers conv ( ( )a...
11,534
deep learning for computer vision let' save the model--you'll use it in section listing saving he model model save('cats_and_dogs_small_ 'and let' plot the results againsee figures and thanks to data augmentation and dropoutyou're no longer overfittingthe training curves are closely tracking the validation curves you n...
11,535
using pretrained convnet common and highly effective approach to deep learning on small image datasets is to use pretrained network pretrained network is saved network that was previously trained on large datasettypically on large-scale image-classification task if this original dataset is large enough and general enou...
11,536
deep learning for computer vision previously trained networkrunning the new data through itand training new classifier on top of the output (see figure prediction prediction prediction trained classifier trained classifier new classifier (randomly initializedtrained convolutional base trained convolutional base trained...
11,537
in this casebecause the imagenet class set contains multiple dog and cat classesit' likely to be beneficial to reuse the information contained in the densely connected layers of the original model but we'll choose not toin order to cover the more general case where the class set of the new problem doesn' overlap the cl...
11,538
deep learning for computer vision block _conv (convolution (none block _conv (convolution (none block _pool (maxpooling (none block _conv (convolution (none block _conv (convolution (none block _pool (maxpooling (none block _conv (convolution (none block _conv (convolution (none block _conv (convolution (none block _po...
11,539
extending the model you have (conv_baseby adding dense layers on topand running the whole thing end to end on the input data this will allow you to use data augmentationbecause every input image goes through the convolutional base every time it' seen by the model but for the same reasonthis technique is far more expens...
11,540
deep learning for computer vision train_features np reshape(train_features( )validation_features np reshape(validation_features( )test_features np reshape(test_features( )at this pointyou can define your densely connected classifier (note the use of dropout for regularizationand train it on the data and labels that you...
11,541
using pretrained convnet figure training and validation accuracy for simple feature extraction figure training and validat ion loss for simple feat ure ext ract ion you reach validation accuracy of about %--much better than you achieved in the previous section with the small model trained from scratch but the plots als...
11,542
deep learning for computer vision because models behave just like layersyou can add model (like conv_baseto sequential model just like you would add layer listing adding densely connect ed classifier on op of he convolut ional base from keras import models from keras import layers model models sequential(model add(conv...
11,543
using pretrained convnet with this setuponly the weights from the two dense layers that you added will be trained that' total of four weight tensorstwo per layer (the main weight matrix and the bias vectornote that in order for these changes to take effectyou must first compile the model if you ever modify weight train...
11,544
deep learning for computer vision figure training and validat ion accuracy for feat ure extraction wit data augment ation figure training and validat ion loss for feat ure ext ract ion wit dat augment ation fine-tuning another widely used technique for model reusecomplementary to feature extractionis fine-tuning (see f...
11,545
convolution convolution conv block frozen maxpooling convolution convolution conv block frozen maxpooling convolution convolution conv block frozen convolution maxpooling convolution convolution conv block frozen convolution maxpooling convolution convolution convolution we fine-tune conv block maxpooling flatten dense...
11,546
deep learning for computer vision stated earlier that it' necessary to freeze the convolution base of vgg in order to be able to train randomly initialized classifier on top for the same reasonit' only possible to fine-tune the top layers of the convolutional base once the classifier on top has already been trained if ...
11,547
block _conv (convolution (none block _conv (convolution (none block _conv (convolution (none block _pool (maxpooling (none ===============================================================total params you'll fine-tune the last three convolutional layerswhich means all layers up to block _pool should be frozenand the laye...
11,548
listing deep learning for computer vision fine- uning he model model compile(loss='binary_crossentropy'optimizer=optimizers rmsprop(lr= - )metrics=['acc']history model fit_generatortrain_generatorsteps_per_epoch= epochs= validation_data=validation_generatorvalidation_steps= let' plot the results using the same plotting...
11,549
listing smoot hing he plot def smooth_curve(pointsfactor= )smoothed_points [for point in pointsif smoothed_pointsprevious smoothed_points[- smoothed_points append(previous factor point ( factor)elsesmoothed_points append(pointreturn smoothed_points plt plot(epochssmooth_curve(acc)'bo'label='smoothed training acc'plt pl...
11,550
figure deep learning for computer vision smoot hed curves for raining and validation loss for fine-tuning the validation accuracy curve look much cleaner you're seeing nice absolute improvement in accuracyfrom about to above note that the loss curve doesn' show any real improvement (in factit' deterioratingyou may wond...
11,551
wrapping up here' what you should take away from the exercises in the past two sectionsconvnets are the best type of machine-learning models for computer-vision tasks it' possible to train one from scratch even on very small datasetwith decent results on small datasetoverfitting will be the main issue data augmentation...
11,552
deep learning for computer vision visualizing what convnets learn it' often said that deep-learning models are "black boxes"learning representations that are difficult to extract and present in human-readable form although this is partially true for certain types of deep-learning modelsit' definitely not true for convn...
11,553
visualizing what convnets learn conv d_ (conv (none maxpooling d_ (maxpooling (none conv d_ (conv (none maxpooling d_ (maxpooling (none flatten_ (flatten(none dropout_ (dropout(none dense_ (dense(none dense_ (dense(none ===============================================================total params , , trainable params , ,...
11,554
deep learning for computer vision figure the test cat picture in order to extract the feature maps you want to look atyou'll create keras model that takes batches of images as inputand outputs the activations of all convolution and pooling layers to do thisyou'll use the keras class model model is instantiated using tw...
11,555
visualizing what convnets learn listing running he model in predict mode activations activation_model predict(img_tensorreturns list of five numpy arraysone array per layer activation for instancethis is the activation of the first convolution layer for the cat image inputfirst_layer_activation activations[ print(first...
11,556
deep learning for computer vision figure sevent channel of the act ivation of he first layer on he est cat pict ure this one looks like "bright green dotdetectoruseful to encode cat eyes at this pointlet' plot complete visualization of all the activations in the network (see figure you'll extract and plot every channel...
11,557
figure every channel of every layer act ivat ion on he est cat pict ure licensed to
11,558
deep learning for computer vision there are few things to note herethe first layer acts as collection of various edge detectors at that stagethe activations retain almost all of the information present in the initial picture as you go higherthe activations become increasingly abstract and less visually interpretable th...
11,559
visualizing what convnets learn visualizing convnet filters another easy way to inspect the filters learned by convnets is to display the visual pattern that each filter is meant to respond to this can be done with gradient ascent in input space applying gradient descent to the value of the input image of convnet so as...
11,560
deep learning for computer vision function that takes numpy tensor (as list of tensors of size and returns list of two numpy tensorsthe loss value and the gradient value listing fet ching numpy out put values given numpy input values iterate function([model input][lossgrads]import numpy as np loss_valuegrads_value iter...
11,561
visualizing what convnets learn listing funct ion generat filt er visualizat ions builds loss function that maximizes the activation of the nth filter of the layer under consideration computes the gradient of the input picture with regard to this loss def generate_pattern(layer_namefilter_indexsize= )layer_output model...
11,562
listing deep learning for computer vision generat ing grid of all filt er response pat erns in layer layer_name 'block _conv size margin empty (blackimage to store results results np zeros(( size margin size margin )for in range( )iterates over the rows of the results grid for in range( )iterates over the columns of th...
11,563
figure filter pat erns for layer block _conv figure filter pat erns for layer block _conv licensed to
11,564
figure deep learning for computer vision filter pat erns for layer block _conv these filter visualizations tell you lot about how convnet layers see the worldeach layer in convnet learns collection of filters such that their inputs can be expressed as combination of the filters this is similar to how the fourier transf...
11,565
visualizing what convnets learn respect to the class under consideration for instancegiven an image fed into dogsversus-cats convnetcam visualization allows you to generate heatmap for the class "cat,indicating how cat-like different parts of the image areand also heatmap for the class "dog,indicating how dog-like part...
11,566
listing deep learning for computer vision preprocessing an input image for vgg from keras preprocessing import image from keras applications vgg import preprocess_inputdecode_predictions import numpy as np img_path '/users/fchollet/downloads/creative_commons_elephant jpgimg image load_img(img_pathtarget_size=( ) image ...
11,567
visualizing what convnets learn gradient of the african elephantclass with regard to the output feature map of block _conv vector of shape ( ,)where each entry is the mean intensity of the gradient over specific feature-map channel grads gradients(african_elephant_outputlast_conv_layer output)[ pooled_grads mean(gradsa...
11,568
deep learning for computer vision finallyyou'll use opencv to generate an image that superimposes the original image on the heatmap you just obtained (see figure listing superimposing he heat map wit he original pict ure import cv img cv imread(img_pathuses cv to load the original image resizes the heatmap to be the sa...
11,569
summary convnets are the best tool for attacking visual-classification problems convnets work by learning hierarchy of modular patterns and concepts to represent the visual world the representations they learn are easy to inspect--convnets are the opposite of black boxesyou're now capable of training your own convnet f...
11,570
text and sequences this covers preprocessing text data into useful representations working with recurrent neural networks using convnets for sequence processing this explores deep-learning models that can process text (understood as sequences of word or sequences of characters)timeseriesand sequence data in general the...
11,571
sequence-to-sequence learningsuch as decoding an english sentence into french sentiment analysissuch as classifying the sentiment of tweets or movie reviews as positive or negative timeseries forecastingsuch as predicting the future weather at certain locationgiven recent weather data this examples focus on two narrow ...
11,572
deep learning for text and sequences working with text data text is one of the most widespread forms of sequence data it can be understood as either sequence of characters or sequence of wordsbut it' most common to work at the level of words the deep-learning sequence-processing models introduced in the following secti...
11,573
understanding -grams and bag-of-words word -grams are groups of (or fewerconsecutive words that you can extract from sentence the same concept may also be applied to characters instead of words here' simple example consider the sentence the cat sat on the mat it may be decomposed into the following set of -grams{"the""...
11,574
listing deep learning for text and sequences word-level one-hot encoding ( oy examplebuilds an index of all tokens in the data initial dataone entry per sample (in this examplea sample is sentencebut it could be an entire documenttokenizes the samples via the split method in real lifeyou' also strip punctuation and spe...
11,575
working with text data listing using keras for word-level one-hot encoding from keras preprocessing text import tokenizer creates tokenizerconfigured to only take into account the , most common words samples ['the cat sat on the mat ''the dog ate my homework 'builds the word index tokenizer tokenizer(num_words= tokeniz...
11,576
deep learning for text and sequences using word embeddings another popular and powerful way to associate vector with word is the use of dense word vectorsalso called word embeddings whereas the vectors obtained through one-hot encoding are binarysparse (mostly made of zeros)and very high-dimensional (same dimensionalit...
11,577
learning word embeddings with the embedding layer the simplest way to associate dense vector with word is to choose the vector at random the problem with this approach is that the resulting embedding space has no structurefor instancethe words accurate and exact may end up with completely different embeddingseven thoug...
11,578
deep learning for text and sequences it' thus reasonable to learn new embedding space with every new task fortunatelybackpropagation makes this easyand keras makes it even easier it' about learning the weights of layerthe embedding layer listing inst ant iat ing an embedding layer from keras layers import embedding emb...
11,579
working with text data sequences ( integer tensorinto embedded sequences ( float tensor)flatten the tensor to dand train single dense layer on top for classification listing loading he imdb dat for use wit an embedding layer from keras datasets import imdb from keras import preprocessing max_features maxlen number of w...
11,580
deep learning for text and sequences using pretrained word embeddings sometimesyou have so little training data available that you can' use your data alone to learn an appropriate task-specific embedding of your vocabulary what do you do theninstead of learning word embeddings jointly with the problem you want to solve...
11,581
working with text data downloading the imdb data as raw text firsthead to nowlet' collect the individual training reviews into list of stringsone string per review you'll also collect the review labels (positive/negativeinto labels list listing processing he labels of he raw imdb dat import os imdb_dir '/users/fchollet...
11,582
deep learning for text and sequences word_index tokenizer word_index print('found % unique tokens len(word_index)data pad_sequences(sequencesmaxlen=maxlenlabels np asarray(labelsprint('shape of data tensor:'data shapeprint('shape of label tensor:'labels shapeindices np arange(data shape[ ]np random shuffle(indicesdata ...
11,583
working with text data listing preparing he glove word-embeddings mat rix embedding_dim embedding_matrix np zeros((max_wordsembedding_dim)for wordi in word_index items()if max_wordsembedding_vector embeddings_index get(wordif embedding_vector is not noneembedding_matrix[iembedding_vector words not found in the embeddin...
11,584
deep learning for text and sequences training and evaluating the model compile and train the model listing training and evaluat ion model compile(optimizer='rmsprop'loss='binary_crossentropy'metrics=['acc']history model fit(x_trainy_trainepochs= batch_size= validation_data=(x_valy_val)model save_weights('pre_trained_gl...
11,585
working with text data figure training and validat ion accuracy when using pret rained word embeddings the model quickly starts overfittingwhich is unsurprising given the small number of training samples validation accuracy has high variance for the same reasonbut it seems to reach the high note that your mileage may v...
11,586
deep learning for text and sequences figure training and validation loss wit hout using pret rained word embeddings figure training and validation accuracy wit hout using pret rained word embeddings validation accuracy stalls in the low so in this casepretrained word embeddings outperform jointly learned embeddings if ...
11,587
close(if label_type ='neg'labels append( elselabels append( sequences tokenizer texts_to_sequences(textsx_test pad_sequences(sequencesmaxlen=maxleny_test np asarray(labelsnextload and evaluate the first model listing evaluat ing the model on he est set model load_weights('pre_trained_glove_model 'model evaluate(x_testy...
11,588
deep learning for text and sequences understanding recurrent neural networks major characteristic of all neural networks you've seen so farsuch as densely connected networks and convnetsis that they have no memory each input shown to them is processed independentlywith no state kept in between inputs with such networks...
11,589
understanding recurrent neural networks you can even flesh out the function fthe transformation of the input and state into an output will be parameterized by two matricesw and uand bias vector it' similar to the transformation operated by densely connected layer in feedforward network listing more det ailed pseudocode...
11,590
deep learning for text and sequences output - output output_t activationw*input_t *state_t bostate input - figure output + state + input input + simple rnnunrolled over ime in this examplethe final output is tensor of shape (timestepsoutput_features)where each timestep is the output of the loop at time each timestep in...
11,591
layer (typeoutput shape param ===============================================================embedding_ (embedding(nonenone simplernn_ (simplernn(none ===============================================================total params , trainable params , non-trainable params the following example returns the full state sequen...
11,592
deep learning for text and sequences nowlet' use such model on the imdb movie-review-classification problem firstpreprocess the data listing preparing he imdb dat from keras datasets import imdb from keras preprocessing import sequence max_features maxlen batch_size number of words to consider as features cuts off text...
11,593
plt title('training and validation accuracy'plt legend(plt figure(plt plot(epochsloss'bo'label='training loss'plt plot(epochsval_loss' 'label='validation loss'plt title('training and validation loss'plt legend(plt show(figure training and validation loss on imdb wit simplernn figure training and validation accuracy on ...
11,594
deep learning for text and sequences other types of recurrent layers perform much better let' look at some moreadvanced layers understanding the lstm and gru layers simplernn isn' the only recurrent layer available in keras there are two otherslstm and gru in practiceyou'll always use one of thesebecause simplernn is g...
11,595
understanding recurrent neural networks let' add to this picture an additional data flow that carries information across timesteps call its values at different timesteps ctwhere stands for carry this information will have the following impact on the cellit will be combined with the input connection and the recurrent co...
11,596
deep learning for text and sequences output - - output compute new carry ct ct state compute new carry output_t activationwo*input_t uo*state_t vo*c_t boinput - figure output + input + carry track ct state + input + anatomy of an lstm if you want to get philosophicalyou can interpret what each of these operations is me...
11,597
defaults keras has good defaultsand things will almost always "just workwithout you having to spend time tuning parameters by hand listing using he lstm layer in keras from keras layers import lstm model sequential(model add(embedding(max_features )model add(lstm( )model add(dense( activation='sigmoid')model compile(op...
11,598
deep learning for text and sequences this timeyou achieve up to validation accuracy not badcertainly much better than the simplernn network--that' largely because lstm suffers much less from the vanishing-gradient problem--and slightly better than the fully connected approach from even though you're looking at less dat...
11,599
advanced use of recurrent neural networks in this sectionwe'll review three advanced techniques for improving the performance and generalization power of recurrent neural networks by the end of the sectionyou'll know most of what there is to know about using recurrent networks with keras we'll demonstrate all three con...