id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
11,600 | listing deep learning for text and sequences inspect ing the dat of he jena weat her dat aset import os data_dir '/users/fchollet/downloads/jena_climatefname os path join(data_dir'jena_climate_ csv' open(fnamedata read( close(lines data split('\ 'header lines[ split(','lines lines[ :print(headerprint(len(lines)this outputs count of , lines of data (each line is timestepa record of date and weather-related values)as well as the following header["date time"" (mbar)"" (degc)""tpot ( )""tdew (degc)""rh (%)""vpmax (mbar)""vpact (mbar)""vpdef (mbar)""sh ( /kg)"" oc (mmol/mol)""rho ( / ** )""wv ( / )""max wv ( / )""wd (deg)"nowconvert all , lines of data into numpy array listing parsing he dat import numpy as np float_data np zeros((len(lines)len(header )for iline in enumerate(lines)values [float(xfor in line split(',')[ :]float_data[ :values for instancehere is the plot of temperature (in degrees celsiusover time (see figure on this plotyou can clearly see the yearly periodicity of temperature licensed to |
11,601 | advanced use of recurrent neural networks listing plot ing he emperat ure imeseries from matplotlib import pyplot as plt temp float_data[: temperature (in degrees celsiusplt plot(range(len(temp))tempfigure temperat ure over the full emporal range of he dat aset (ochere is more narrow plot of the first days of temperature data (see figure because the data is recorded every minutesyou get data points per day listing plot ing he first days of he emperat ure imeseries plt plot(range( )temp[: ]figure temperat ure over he first days of the dat aset (oclicensed to |
11,602 | deep learning for text and sequences on this plotyou can see daily periodicityespecially evident for the last days also note that this -day period must be coming from fairly cold winter month if you were trying to predict average temperature for the next month given few months of past datathe problem would be easydue to the reliable year-scale periodicity of the data but looking at the data over scale of daysthe temperature looks lot more chaotic is this timeseries predictable at daily scalelet' find out preparing the data the exact formulation of the problem will be as followsgiven data going as far back as lookback timesteps ( timestep is minutesand sampled every steps timestepscan you predict the temperature in delay timestepsyou'll use the following parameter valueslookback --observations will go back days steps --observations will be sampled at one data point per hour delay --targets will be hours in the future to get startedyou need to do two thingspreprocess the data to format neural network can ingest this is easythe data is already numericalso you don' need to do any vectorization but each timeseries in the data is on different scale (for exampletemperature is typically between - and + but atmospheric pressuremeasured in mbaris around , you'll normalize each timeseries independently so that they all take small values on similar scale write python generator that takes the current array of float data and yields batches of data from the recent pastalong with target temperature in the future because the samples in the dataset are highly redundant (sample and sample will have most of their timesteps in common)it would be wasteful to explicitly allocate every sample insteadyou'll generate the samples on the fly using the original data you'll preprocess the data by subtracting the mean of each timeseries and dividing by the standard deviation you're going to use the first , timesteps as training dataso compute the mean and standard deviation only on this fraction of the data listing normalizing he dat mean float_data[: mean(axis= float_data -mean std float_data[: std(axis= float_data /std listing shows the data generator you'll use it yields tuple (samplestargets)where samples is one batch of input data and targets is the corresponding array of target temperatures it takes the following argumentslicensed to |
11,603 | data--the original array of floating-point datawhich you normalized in listing lookback--how many timesteps back the input data should go delay--how many timesteps in the future the target should be min_index and max_index--indices in the data array that delimit which timesteps to draw from this is useful for keeping segment of the data for validation and another for testing shuffle--whether to shuffle the samples or draw them in chronological order batch_size--the number of samples per batch step--the periodin timestepsat which you sample data you'll set it to in order to draw one data point every hour listing generat or yielding imeseries samples and heir arget def generator(datalookbackdelaymin_indexmax_indexshuffle=falsebatch_size= step= )if max_index is nonemax_index len(datadelay min_index lookback while if shufflerows np random randintmin_index lookbackmax_indexsize=batch_sizeelseif batch_size >max_indexi min_index lookback rows np arange(imin( batch_sizemax_index) +len(rowssamples np zeros((len(rows)lookback /stepdata shape[- ])targets np zeros((len(rows),)for jrow in enumerate(rows)indices range(rows[jlookbackrows[ ]stepsamples[jdata[indicestargets[jdata[rows[jdelay][ yield samplestargets nowlet' use the abstract generator function to instantiate three generatorsone for trainingone for validationand one for testing each will look at different temporal segments of the original datathe training generator looks at the first , timestepsthe validation generator looks at the following , and the test generator looks at the remainder listing preparing he rainingvalidat ionand est generat ors lookback step delay batch_size licensed to |
11,604 | deep learning for text and sequences train_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index= shuffle=truestep=stepbatch_size=batch_sizeval_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index= step=stepbatch_size=batch_sizetest_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index=nonestep=stepbatch_size=batch_sizehow many steps to draw from val_gen in order to see the entire validation set val_steps ( lookbacktest_steps (len(float_data lookbackhow many steps to draw from test_gen in order to see the entire test set common-sensenon-machine-learning baseline before you start using black-box deep-learning models to solve the temperatureprediction problemlet' try simplecommon-sense approach it will serve as sanity checkand it will establish baseline that you'll have to beat in order to demonstrate the usefulness of more-advanced machine-learning models such common-sense baselines can be useful when you're approaching new problem for which there is no known solution (yeta classic example is that of unbalanced classification taskswhere some classes are much more common than others if your dataset contains instances of class and instances of class bthen common-sense approach to the classification task is to always predict "awhen presented with new sample such classifier is accurate overalland any learning-based approach should therefore beat this score in order to demonstrate usefulness sometimessuch elementary baselines can prove surprisingly hard to beat in this casethe temperature timeseries can safely be assumed to be continuous (the temperatures tomorrow are likely to be close to the temperatures todayas well as periodical with daily period thus common-sense approach is to always predict that the temperature hours from now will be equal to the temperature right now let' evaluate this approachusing the mean absolute error (maemetricnp mean(np abs(preds targets)licensed to |
11,605 | here' the evaluation loop listing comput ing he common-sense baseline mae def evaluate_naive_method()batch_maes [for step in range(val_steps)samplestargets next(val_genpreds samples[:- mae np mean(np abs(preds targets)batch_maes append(maeprint(np mean(batch_maes)evaluate_naive_method(this yields an mae of because the temperature data has been normalized to be centered on and have standard deviation of this number isn' immediately interpretable it translates to an average absolute error of temperature_std degrees celsius @ listing convert ing he mae back celsius error celsius_mae std[ that' fairly large average absolute error now the game is to use your knowledge of deep learning to do better basic machine-learning approach in the same way that it' useful to establish common-sense baseline before trying machine-learning approachesit' useful to try simplecheap machine-learning models (such as smalldensely connected networksbefore looking into complicated and computationally expensive models such as rnns this is the best way to make sure any further complexity you throw at the problem is legitimate and delivers real benefits the following listing shows fully connected model that starts by flattening the data and then runs it through two dense layers note the lack of activation function on the last dense layerwhich is typical for regression problem you use mae as the loss because you evaluate on the exact same data and with the exact same metric you did with the common-sense approachthe results will be directly comparable listing training and evaluat ing densely connect ed model from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers flatten(input_shape=(lookback /stepfloat_data shape[- ]))model add(layers dense( activation='relu')model add(layers dense( )licensed to |
11,606 | deep learning for text and sequences model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepslet' display the loss curves for validation and training (see figure listing plot ing result import matplotlib pyplot as plt loss history history['loss'val_loss history history['val_loss'epochs range( len(loss 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 he jena temperatureforecast ing task wit simpledensely connect ed net work some of the validation losses are close to the no-learning baselinebut not reliably this goes to show the merit of having this baseline in the first placeit turns out to be not easy to outperform your common sense contains lot of valuable information that machine-learning model doesn' have access to you may wonderif simplewell-performing model exists to go from the data to the targets (the common-sense baseline)why doesn' the model you're training find it and improve on itbecause this simple solution isn' what your training setup is looking for the space of models in which you're searching for solution--that isyour hypothesis space--is the space of all possible two-layer networks with the configuration you defined these networks are already fairly complicated when you're looking for licensed to |
11,607 | solution with space of complicated modelsthe simplewell-performing baseline may be unlearnableeven if it' technically part of the hypothesis space that is pretty significant limitation of machine learning in generalunless the learning algorithm is hardcoded to look for specific kind of simple modelparameter learning can sometimes fail to find simple solution to simple problem first recurrent baseline the first fully connected approach didn' do wellbut that doesn' mean machine learning isn' applicable to this problem the previous approach first flattened the timeserieswhich removed the notion of time from the input data let' instead look at the data as what it isa sequencewhere causality and order matter you'll try recurrent-sequence processing model--it should be the perfect fit for such sequence dataprecisely because it exploits the temporal ordering of data pointsunlike the first approach instead of the lstm layer introduced in the previous sectionyou'll use the gru layerdeveloped by chung et al in gated recurrent unit (grulayers work using the same principle as lstmbut they're somewhat streamlined and thus cheaper to run (although they may not have as much representational power as lstmthis trade-off between computational expensiveness and representational power is seen everywhere in machine learning listing training and evaluat ing gru-based model from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers gru( input_shape=(nonefloat_data shape[- ]))model add(layers dense( )model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepsfigure shows the results much betteryou can significantly beat the commonsense baselinedemonstrating the value of machine learning as well as the superiority of recurrent networks compared to sequence-flattening dense networks on this type of task junyoung chung et al "empirical evaluation of gated recurrent neural networks on sequence modeling,conference on neural information processing systems ( )licensed to |
11,608 | deep learning for text and sequences figure training and validation loss on he jena temperatureforecast ing task with gru the new validation mae of ~ (before you start significantly overfittingtranslates to mean absolute error of @ after denormalization that' solid gain on the initial error of @cbut you probably still have bit of margin for improvement using recurrent dropout to fight overfitting it' evident from the training and validation curves that the model is overfittingthe training and validation losses start to diverge considerably after few epochs you're already familiar with classic technique for fighting this phenomenondropoutwhich randomly zeros out input units of layer in order to break happenstance correlations in the training data that the layer is exposed to but how to correctly apply dropout in recurrent networks isn' trivial question it has long been known that applying dropout before recurrent layer hinders learning rather than helping with regularization in yarin galas part of his phd thesis on bayesian deep learning, determined the proper way to use dropout with recurrent networkthe same dropout mask (the same pattern of dropped unitsshould be applied at every timestepinstead of dropout mask that varies randomly from timestep to timestep what' morein order to regularize the representations formed by the recurrent gates of layers such as gru and lstma temporally constant dropout mask should be applied to the inner recurrent activations of the layer ( recurrent dropout maskusing the same dropout mask at every timestep allows the network to properly propagate its learning error through timea temporally random dropout mask would disrupt this error signal and be harmful to the learning process yarin gal did his research using keras and helped build this mechanism directly into keras recurrent layers every recurrent layer in keras has two dropout-related argumentsdropouta float specifying the dropout rate for input units of the layer see yarin gal"uncertainty in deep learning (phd thesis),october yarin/blog_ html licensed to |
11,609 | and recurrent_dropoutspecifying the dropout rate of the recurrent units let' add dropout and recurrent dropout to the gru layer and see how doing so impacts overfitting because networks being regularized with dropout always take longer to fully convergeyou'll train the network for twice as many epochs listing training and evaluat ing dropout-regularized gru-based model from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers gru( dropout= recurrent_dropout= input_shape=(nonefloat_data shape[- ]))model add(layers dense( )model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepsfigure shows the results successyou're no longer overfitting during the first epochs but although you have more stable evaluation scoresyour best scores aren' much lower than they were previously figure training and validation loss on the jena emperat ureforecasting task with dropout regularized gru stacking recurrent layers because you're no longer overfitting but seem to have hit performance bottleneckyou should consider increasing the capacity of the network recall the description of the universal machine-learning workflowit' generally good idea to increase the capacity of your network until overfitting becomes the primary obstacle (assuming licensed to |
11,610 | deep learning for text and sequences you're already taking basic steps to mitigate overfittingsuch as using dropoutas long as you aren' overfitting too badlyyou're likely under capacity increasing network capacity is typically done by increasing the number of units in the layers or adding more layers recurrent layer stacking is classic way to build more-powerful recurrent networksfor instancewhat currently powers the google translate algorithm is stack of seven large lstm layers--that' huge to stack recurrent layers on top of each other in kerasall intermediate layers should return their full sequence of outputs ( tensorrather than their output at the last timestep this is done by specifying return_sequences=true listing training and evaluat ing dropout-regularizedst acked gru model from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers gru( dropout= recurrent_dropout= return_sequences=trueinput_shape=(nonefloat_data shape[- ]))model add(layers gru( activation='relu'dropout= recurrent_dropout= )model add(layers dense( )model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepsfigure shows the results you can see that the added layer does improve the results bitthough not significantly you can draw two conclusionsbecause you're still not overfitting too badlyyou could safely increase the size of your layers in quest for validation-loss improvement this has non-negligible computational costthough adding layer didn' help by significant factorso you may be seeing diminishing returns from increasing network capacity at this point licensed to |
11,611 | figure training and validat ion loss on he jena temperat ureforecast ing ask wit st acked gru net work using bidirectional rnns the last technique introduced in this section is called bidirectional rnns bidirectional rnn is common rnn variant that can offer greater performance than regular rnn on certain tasks it' frequently used in natural-language processing--you could call it the swiss army knife of deep learning for natural-language processing rnns are notably order dependentor time dependentthey process the timesteps of their input sequences in orderand shuffling or reversing the timesteps can completely change the representations the rnn extracts from the sequence this is precisely the reason they perform well on problems where order is meaningfulsuch as the temperature-forecasting problem bidirectional rnn exploits the order sensitivity of rnnsit consists of using two regular rnnssuch as the gru and lstm layers you're already familiar witheach of which processes the input sequence in one direction (chronologically and antichronologically)and then merging their representations by processing sequence both waysa bidirectional rnn can catch patterns that may be overlooked by unidirectional rnn remarkablythe fact that the rnn layers in this section have processed sequences in chronological order (older timesteps firstmay have been an arbitrary decision at leastit' decision we made no attempt to question so far could the rnns have performed well enough if they processed input sequences in antichronological orderfor instance (newer timesteps first)let' try this in practice and see what happens all you need to do is write variant of the data generator where the input sequences are reverted along the time dimension (replace the last line with yield samples[:::- :]targetstraining the same one-gru-layer network that you used in the first experiment in this sectionyou get the results shown in figure licensed to |
11,612 | deep learning for text and sequences figure training and validation loss on the jena emperat ureforecasting task with gru rained on reversed sequences the reversed-order gru strongly underperforms even the common-sense baselineindicating that in this casechronological processing is important to the success of your approach this makes perfect sensethe underlying gru layer will typically be better at remembering the recent past than the distant pastand naturally the more recent weather data points are more predictive than older data points for the problem (that' what makes the common-sense baseline fairly strongthus the chronological version of the layer is bound to outperform the reversed-order version importantlythis isn' true for many other problemsincluding natural languageintuitivelythe importance of word in understanding sentence isn' usually dependent on its position in the sentence let' try the same trick on the lstm imdb example from section listing training and evaluat ing an lstm using reversed sequences from keras datasets import imdb from keras preprocessing import sequence from keras import layers number of words from keras models import sequential to consider as features max_features maxlen loads data cuts off texts after this number of words (among the max_features most common words(x_trainy_train)(x_testy_testimdb load_datanum_words=max_featuresx_train [ [::- for in x_trainx_test [ [::- for in x_testreverses sequences x_train sequence pad_sequences(x_trainmaxlen=maxlenx_test sequence pad_sequences(x_testmaxlen=maxlenmodel sequential(model add(layers embedding(max_features )model add(layers lstm( )model add(layers dense( activation='sigmoid')model compile(optimizer='rmsprop'loss='binary_crossentropy'metrics=['acc']licensed to pads sequences |
11,613 | history model fit(x_trainy_trainepochs= batch_size= validation_split= you get performance nearly identical to that of the chronological-order lstm remarkablyon such text datasetreversed-order processing works just as well as chronological processingconfirming the hypothesis thatalthough word order does matter in understanding languagewhich order you use isn' crucial importantlyan rnn trained on reversed sequences will learn different representations than one trained on the original sequencesmuch as you would have different mental models if time flowed backward in the real world--if you lived life where you died on your first day and were born on your last day in machine learningrepresentations that are different yet useful are always worth exploitingand the more they differthe betterthey offer new angle from which to look at your datacapturing aspects of the data that were missed by other approachesand thus they can help boost performance on task this is the intuition behind ensemblinga concept we'll explore in bidirectional rnn exploits this idea to improve on the performance of chronologicalorder rnns it looks at its input sequence both ways (see figure )obtaining potentially richer representations and capturing patterns that may have been missed by the chronological-order version alone input data merge (addconcatenaternn rnn abcde edcba chronological sequence abcde reversed sequence figure how bidirect ional rnn layer works to instantiate bidirectional rnn in kerasyou use the bidirectional layerwhich takes as its first argument recurrent layer instance bidirectional creates secondseparate instance of this recurrent layer and uses one instance for processing the input sequences in chronological order and the other instance for processing the input sequences in reversed order let' try it on the imdb sentiment-analysis task listing training and evaluat ing bidirectional lstm model sequential(model add(layers embedding(max_features )model add(layers bidirectional(layers lstm( ))model add(layers dense( activation='sigmoid')licensed to |
11,614 | deep learning for text and sequences model compile(optimizer='rmsprop'loss='binary_crossentropy'metrics=['acc']history model fit(x_trainy_trainepochs= batch_size= validation_split= it performs slightly better than the regular lstm you tried in the previous sectionachieving over validation accuracy it also seems to overfit more quicklywhich is unsurprising because bidirectional layer has twice as many parameters as chronological lstm with some regularizationthe bidirectional approach would likely be strong performer on this task now let' try the same approach on the temperature-prediction task listing training bidirect ional gru from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers bidirectionallayers gru( )input_shape=(nonefloat_data shape[- ]))model add(layers dense( )model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepsthis performs about as well as the regular gru layer it' easy to understand whyall the predictive capacity must come from the chronological half of the networkbecause the antichronological half is known to be severely underperforming on this task (againbecause the recent past matters much more than the distant past in this casegoing even further there are many other things you could tryin order to improve performance on the temperature-forecasting problemadjust the number of units in each recurrent layer in the stacked setup the current choices are largely arbitrary and thus probably suboptimal adjust the learning rate used by the rmsprop optimizer try using lstm layers instead of gru layers try using bigger densely connected regressor on top of the recurrent layersthat isa bigger dense layer or even stack of dense layers don' forget to eventually run the best-performing models (in terms of validation maeon the test setotherwiseyou'll develop architectures that are overfitting to the validation set licensed to |
11,615 | as alwaysdeep learning is more an art than science we can provide guidelines that suggest what is likely to work or not work on given problembutultimatelyevery problem is uniqueyou'll have to evaluate different strategies empirically there is currently no theory that will tell you in advance precisely what you should do to optimally solve problem you must iterate wrapping up here' what you should take away from this sectionas you first learned in when approaching new problemit' good to first establish common-sense baselines for your metric of choice if you don' have baseline to beatyou can' tell whether you're making real progress try simple models before expensive onesto justify the additional expense sometimes simple model will turn out to be your best option when you have data where temporal ordering mattersrecurrent networks are great fit and easily outperform models that first flatten the temporal data to use dropout with recurrent networksyou should use time-constant dropout mask and recurrent dropout mask these are built into keras recurrent layersso all you have to do is use the dropout and recurrent_dropout arguments of recurrent layers stacked rnns provide more representational power than single rnn layer they're also much more expensive and thus not always worth it although they offer clear gains on complex problems (such as machine translation)they may not always be relevant to smallersimpler problems bidirectional rnnswhich look at sequence both waysare useful on naturallanguage processing problems but they aren' strong performers on sequence data where the recent past is much more informative than the beginning of the sequence there are two important concepts we won' cover in detail hererecurrent attention and sequence masking both tend to be especially relevant for natural-language processingand they aren' particularly applicable to the temperature-forecasting problem we'll leave them for future study outside of this book note licensed to |
11,616 | deep learning for text and sequences market and machine learning some readers are bound to want to take the techniques we've introduced here and try them on the problem of forecasting the future price of securities on the stock market (or currency exchange ratesand so onmarkets have very different statistical characteristics than natural phenomena such as weather patterns trying to use machine learning to beat marketswhen you only have access to publicly available datais difficult endeavorand you're likely to waste your time and resources with nothing to show for it always remember that when it comes to marketspast performance is not good predictor of future returns--looking in the rear-view mirror is bad way to drive machine learningon the other handis applicable to datasets where the past is good predictor of the future licensed to |
11,617 | sequence processing with convnets sequence processing with convnets in you learned about convolutional neural networks (convnetsand how they perform particularly well on computer vision problemsdue to their ability to operate convolutionallyextracting features from local input patches and allowing for representation modularity and data efficiency the same properties that make convnets excel at computer vision also make them highly relevant to sequence processing time can be treated as spatial dimensionlike the height or width of image such convnets can be competitive with rnns on certain sequence-processing problemsusually at considerably cheaper computational cost recently convnetstypically used with dilated kernelshave been used with great success for audio generation and machine translation in addition to these specific successesit has long been known that small convnets can offer fast alternative to rnns for simple tasks such as text classification and timeseries forecasting understanding convolution for sequence data the convolution layers introduced previously were convolutionsextracting patches from image tensors and applying an identical transformation to every patch in the same wayyou can use convolutionsextracting local patches (subsequencesfrom sequences (see figure window of size input features input time extracted patch dot product with weights output output features figure how convolut ion workseach output timest ep is obtained from emporal patch in the input sequence such convolution layers can recognize local patterns in sequence because the same input transformation is performed on every patcha pattern learned at certain position in sentence can later be recognized at different positionmaking convnets translation invariant (for temporal translationsfor instancea convnet processing sequences of characters using convolution windows of size should be able to learn words or word fragments of length or lessand it should be able to recognize licensed to |
11,618 | deep learning for text and sequences these words in any context in an input sequence character-level convnet is thus able to learn about word morphology pooling for sequence data you're already familiar with pooling operationssuch as average pooling and max poolingused in convnets to spatially downsample image tensors the pooling operation has equivalentextracting patches (subsequencesfrom an input and outputting the maximum value (max poolingor average value (average poolingjust as with convnetsthis is used for reducing the length of inputs (subsamplingimplementing convnet in kerasyou use convnet via the conv layerwhich has an interface similar to conv it takes as input tensors with shape (samplestimefeaturesand returns similarly shaped tensors the convolution window is window on the temporal axisaxis in the input tensor let' build simple two-layer convnet and apply it to the imdb sentimentclassification task you're already familiar with as reminderthis is the code for obtaining and preprocessing the data listing preparing he imdb dat from keras datasets import imdb from keras preprocessing import sequence max_features max_len print('loading data '(x_trainy_train)(x_testy_testimdb load_data(num_words=max_featuresprint(len(x_train)'train sequences'print(len(x_test)'test sequences'print('pad sequences (samples time)'x_train sequence pad_sequences(x_trainmaxlen=max_lenx_test sequence pad_sequences(x_testmaxlen=max_lenprint('x_train shape:'x_train shapeprint('x_test shape:'x_test shape convnets are structured in the same way as their counterpartswhich you used in they consist of stack of conv and maxpooling layersending in either global pooling layer or flatten layerthat turn the outputs into outputsallowing you to add one or more dense layers to the model for classification or regression one differencethoughis the fact that you can afford to use larger convolution windows with convnets with convolution layera convolution window contains feature vectorsbut with convolution layera convolution window of size contains only feature vectors you can thus easily afford convolution windows of size or licensed to |
11,619 | this is the example convnet for the imdb dataset listing training and evaluat ing simple convnet on he imdb dat from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers embedding(max_features input_length=max_len)model add(layers conv ( activation='relu')model add(layers maxpooling ( )model add(layers conv ( activation='relu')model add(layers globalmaxpooling ()model add(layers dense( )model summary(model compile(optimizer=rmsprop(lr= - )loss='binary_crossentropy'metrics=['acc']history model fit(x_trainy_trainepochs= batch_size= validation_split= figures and show the training and validation results validation accuracy is somewhat less than that of the lstmbut runtime is faster on both cpu and gpu (the exact increase in speed will vary greatly depending on your exact configurationat this pointyou could retrain this model for the right number of epochs (eightand run it on the test set this is convincing demonstration that convnet can offer fastcheap alternative to recurrent network on word-level sentiment-classification task figure training and validation loss on imdb wit simple convnet licensed to |
11,620 | deep learning for text and sequences figure training and validat ion accuracy on imdb wit simple convnet combining cnns and rnns to process long sequences because convnets process input patches independentlythey aren' sensitive to the order of the timesteps (beyond local scalethe size of the convolution windows)unlike rnns of courseto recognize longer-term patternsyou can stack many convolution layers and pooling layersresulting in upper layers that will see long chunks of the original inputs--but that' still fairly weak way to induce order sensitivity one way to evidence this weakness is to try convnets on the temperature-forecasting problemwhere order-sensitivity is key to producing good predictions the following example reuses the following variables defined previouslyfloat_datatrain_genval_genand val_steps listing training and evaluat ing simple convnet on he jena dat from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers conv ( activation='relu'input_shape=(nonefloat_data shape[- ]))model add(layers maxpooling ( )model add(layers conv ( activation='relu')model add(layers maxpooling ( )model add(layers conv ( activation='relu')model add(layers globalmaxpooling ()model add(layers dense( )model compile(optimizer=rmsprop()loss='mae'history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepslicensed to |
11,621 | figure shows the training and validation maes figure training and validation loss on the jena temperature-forecast ing ask with simple convnet the validation mae stays in the syou can' even beat the common-sense baseline using the small convnet againthis is because the convnet looks for patterns anywhere in the input timeseries and has no knowledge of the temporal position of pattern it sees (toward the beginningtoward the endand so onbecause more recent data points should be interpreted differently from older data points in the case of this specific forecasting problemthe convnet fails at producing meaningful results this limitation of convnets isn' an issue with the imdb databecause patterns of keywords associated with positive or negative sentiment are informative independently of where they're found in the input sentences one strategy to combine the speed and lightness of convnets with the order-sensitivity of rnns is to use convnet as preprocessing step before an rnn (see figure this is especially beneficial when you're dealing with sequences that are so long they can' realistically be processed with rnnssuch as sequences with thousands of steps the convrnn net will turn the long input sequence into much shorter (downsampledsequences of higher-level features this sequence of shorter cnn features sequence extracted features then becomes the input to the rnn part of the network this technique isn' seen often in cnn research papers and practical applicationspossibly because it isn' well known it' effective and ought to be more common let' try long sequence it on the temperature-forecasting dataset because this strategy allows you to manipufigure combining convnet and late much longer sequencesyou can either an rnn for processing long sequences licensed to |
11,622 | deep learning for text and sequences look at data from longer ago (by increasing the lookback parameter of the data generatoror look at high-resolution timeseries (by decreasing the step parameter of the generatorheresomewhat arbitrarilyyou'll use step that' half as largeresulting in timeseries twice as longwhere the temperature data is sampled at rate of point per minutes the example reuses the generator function defined earlier listing unchanged preparing higher-resolut ion dat generat ors for he jena dat aset step lookback delay previously set to ( point per hour)now ( point per mintrain_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index= shuffle=truestep=stepval_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index= step=steptest_gen generator(float_datalookback=lookbackdelay=delaymin_index= max_index=nonestep=stepval_steps ( lookback/ test_steps (len(float_data lookback/ this is the modelstarting with two conv layers and following up with gru layer figure shows the results listing model combining convolut ional base and gru layer from keras models import sequential from keras import layers from keras optimizers import rmsprop model sequential(model add(layers conv ( activation='relu'input_shape=(nonefloat_data shape[- ]))model add(layers maxpooling ( )model add(layers conv ( activation='relu')model add(layers gru( dropout= recurrent_dropout= )model add(layers dense( )model summary(model compile(optimizer=rmsprop()loss='mae'licensed to |
11,623 | history model fit_generator(train_gensteps_per_epoch= epochs= validation_data=val_genvalidation_steps=val_stepsfigure training and validat ion loss on he jena temperat ureforecast ing ask wit convnet followed by gru judging from the validation lossthis setup isn' as good as the regularized gru alonebut it' significantly faster it looks at twice as much datawhich in this case doesn' appear to be hugely helpful but may be important for other datasets wrapping up here' what you should take away from this sectionin the same way that convnets perform well for processing visual patterns in space convnets perform well for processing temporal patterns they offer faster alternative to rnns on some problemsin particular naturallanguage processing tasks typically convnets are structured much like their equivalents from the world of computer visionthey consist of stacks of conv layers and maxpooling layersending in global pooling operation or flattening operation because rnns are extremely expensive for processing very long sequencesbut convnets are cheapit can be good idea to use convnet as preprocessing step before an rnnshortening the sequence and extracting useful representations for the rnn to process licensed to |
11,624 | deep learning for text and sequences summary in this you learned the following techniqueswhich are widely applicable to any dataset of sequence datafrom text to timeserieshow to tokenize text what word embeddings areand how to use them what recurrent networks areand how to use them how to stack rnn layers and use bidirectional rnns to build more-powerful sequence-processing models how to use convnets for sequence processing how to combine convnets and rnns to process long sequences you can use rnns for timeseries regression ("predicting the future")timeseries classificationanomaly detection in timeseriesand sequence labeling (such as identifying names or dates in sentencessimilarlyyou can use convnets for machine translation (sequence-tosequence convolutional modelslike slicenet )document classificationand spelling correction if global order matters in your sequence datathen it' preferable to use recurrent network to process it this is typically the case for timeserieswhere the recent past is likely to be more informative than the distant past if global ordering isn' fundamentally meaningfulthen convnets will turn out to work at least as well and are cheaper this is often the case for text datawhere keyword found at the beginning of sentence is just as meaningful as keyword found at the end see licensed to |
11,625 | best practices this covers the keras functional api using keras callbacks working with the tensorboard visualization tool important best practices for developing state-ofthe-art models this explores number of powerful tools that will bring you closer to being able to develop state-of-the-art models on difficult problems using the keras functional apiyou can build graph-like modelsshare layer across different inputsand use keras models just like python functions keras callbacks and the tensorboard browser-based visualization tool let you monitor models during training we'll also discuss several other best practices including batch normalizationresidual connectionshyperparameter optimizationand model ensembling licensed to |
11,626 | going beyond the sequential modelthe keras functional api advanced deep-learning best practices until nowall neural networks introduced in this book output have been implemented using the sequential model the sequential model makes the assumption that the layer network has exactly one input and exactly one outputand that it consists of linear stack of layers (see figure this is commonly verified assumptionthe configulayer ration is so common that we've been able to cover many topics and practical applications in these pages so far layer using only the sequential model class but this set of sequential assumptions is too inflexible in number of cases some input networks require several independent inputsothers require multiple outputsand some networks have interfigure sequential nal branching between layers that makes them look like modela linear stack of layers graphs of layers rather than linear stacks of layers some tasksfor instancerequire multimodal inputsthey merge data coming from different input sourcesprocessing each type of data using different kinds of neural layers imagine deep-learning model trying to predict the most likely market price of second-hand piece of clothingusing the following inputsuser-provided metadata (such as the item' brandageand so on) user-provided text descriptionand picture of the item if you had only the metadata availableyou could one-hot encode it and use densely connected network to predict the price if you had only the text description availableyou could use an rnn or convnet if you had only the pictureyou could use convnet but how can you use all three at the same timea naive approach would be to train three separate models and then do weighted average of their predictions but this may be suboptimalbecause the information extracted by the models may be redundant better way is to jointly learn more accurate model of the data by using model that can see all available input modalities simultaneouslya model with three input branches (see figure price prediction merging module dense module rnn module convnet module metadata text description picture figure licensed to mult -input model |
11,627 | similarlysome tasks need to predict multiple target attributes of input data given the text of novel or short storyyou might want to automatically classify it by genre (such as romance or thrillerbut also predict the approximate date it was written of courseyou could train two separate modelsone for the genre and one for the date but because these attributes aren' statistically independentyou could build better model by learning to jointly predict both genre and date at the same time such joint model would then have two outputsor heads (see figure due to correlations between genre and dateknowing the date of novel would help the model learn richaccurate representations of the space of novel genresand vice versa genre date genre classifier date regressor text-processing module novel text figure mult -out put (or multiheadmodel additionallymany recently developed neural architectures require nonlinear network topologynetworks structured as directed acyclic graphs the inception family of networks (developed by szegedy et al at google), for instancerelies on inception moduleswhere the input is processed by several parallel convolutional branches whose outputs are then merged back into single tensor (see figure there' also the recent trend of adding residual connections to modelwhich started with the resnet family of networks (developed by he et al at microsoft residual connection consists of reinjecting previous representations into the downstream flow of data by adding past output tensor to later output tensor (see figure )which helps prevent information loss along the data-processing flow there are many other examples of such graph-like networks christian szegedy et al "going deeper with convolutions,conference on computer vision and pattern recognition ( )kaiming he et al "deep residual learning for image recognition,conference on computer vision and pattern recognition ( )licensed to |
11,628 | advanced deep-learning best practices output concatenate conv strides= conv strides= conv strides= conv conv conv avgpool strides= conv input figure an incept ion modulea subgraph of layers wit several parallel convolut ional branches layer layer residual connection layer layer figure residual connectionreinjection of prior informat ion downst ream via feature-map addit ion these three important use cases--multi-input modelsmulti-output modelsand graph-like models--aren' possible when using only the sequential model class in keras but there' another far more general and flexible way to use kerasthe functional api this section explains in detail what it iswhat it can doand how to use it introduction to the functional api in the functional apiyou directly manipulate tensorsand you use layers as functions that take tensors and return tensors (hencethe name functional api )from keras import inputlayers input_tensor input(shape=( ,) tensor licensed to |
11,629 | going beyond the sequential modelthe keras functional api dense layers dense( activation='relu'output_tensor dense(input_tensora layer is function layer may be called on tensorand it returns tensor let' start with minimal example that shows side by side simple sequential model and its equivalent in the functional apifrom keras models import sequentialmodel from keras import layers from keras import input sequential modelwhich you already know about seq_model sequential(seq_model add(layers dense( activation='relu'input_shape=( ,))seq_model add(layers dense( activation='relu')seq_model add(layers dense( activation='softmax')input_tensor input(shape=( ,) layers dense( activation='relu')(input_tensorx layers dense( activation='relu')(xoutput_tensor layers dense( activation='softmax')(xmodel model(input_tensoroutput_tensormodel summary(let' look at itits functional equivalent the model class turns an input tensor and output tensor into model this is what the call to model summary(displayslayer (typeoutput shape param ================================================================input_ (inputlayer(none dense_ (dense(none dense_ (dense(none dense_ (dense(none ================================================================total params , trainable params , non-trainable params the only part that may seem bit magical at this point is instantiating model object using only an input tensor and an output tensor behind the sceneskeras retrieves every layer involved in going from input_tensor to output_tensorbringing them together into graph-like data structure-- model of coursethe reason it works is that output_tensor was obtained by repeatedly transforming input_tensor if you tried to build model from inputs and outputs that weren' relatedyou' get runtimeerrorunrelated_input input(shape=( ,)bad_model model model(unrelated_inputoutput_tensorlicensed to |
11,630 | advanced deep-learning best practices runtimeerrorgraph disconnectedcannot obtain value for tensor tensor("input_ : "shape=(? )dtype=float at layer "input_ this error tells youin essencethat keras couldn' reach input_ from the provided output tensor when it comes to compilingtrainingor evaluating such an instance of modelthe api is the same as that of sequentialmodel compile(optimizer='rmsprop'loss='categorical_crossentropy'import numpy as np x_train np random random(( )y_train np random random(( )generates dummy numpy data to train on model fit(x_trainy_trainepochs= batch_size= score model evaluate(x_trainy_trainevaluates the model multi-input models compiles the model trains the model for epochs the functional api can be used to build models that have multiple inputs typicallysuch models at some point merge their different input branches using layer that can combine several tensorsby adding themconcatenating themand so on this is usually done via keras merge operation such as keras layers addkeras layers concatenateand so on let' look at very simple example of multi-input modela question-answering model typical question-answering model has two inputsa natural-language question and text snippet (such as news articleproviding information to be used for answering the question the model must then produce an answerin the simplest possible setupthis is one-word answer obtained via softmax over some predefined vocabulary (see figure answer dense concatenate lstm lstm embedding embedding reference text question figure quest ion-answering model licensed to |
11,631 | going beyond the sequential modelthe keras functional api following is an example of how you can build such model with the functional api you set up two independent branchesencoding the text input and the question input as representation vectorsthenconcatenate these vectorsand finallyadd softmax classifier on top of the concatenated representations listing funct ional api implement at ion of wo-input quest ion-answering model from keras models import model from keras import layers from keras import input text_vocabulary_size question_vocabulary_size answer_vocabulary_size the text input is variablelength sequence of integers note that you can optionally name the inputs text_input input(shape=(none,)dtype='int 'name='text'embedded_text layers embedding text_vocabulary_size)(text_inputembeds the inputs into sequence of vectors of size encodes the vectors in single vector via an lstm encoded_text layers lstm( )(embedded_textquestion_input input(shape=(none,)dtype='int 'name='question'embedded_question layers embedding question_vocabulary_size)(question_inputencoded_question layers lstm( )(embedded_questionsame process (with different layer instancesfor the question concatenated layers concatenate([encoded_textencoded_question]axis=- concatenates the encoded question and encoded text answer layers dense(answer_vocabulary_sizeactivation='softmax')(concatenatedmodel model([text_inputquestion_input]answermodel compile(optimizer='rmsprop'loss='categorical_crossentropy'metrics=['acc']adds softmax classifier on top at model instantiationyou specify the two inputs and the output nowhow do you train this two-input modelthere are two possible apisyou can feed the model list of numpy arrays as inputsor you can feed it dictionary that maps input names to numpy arrays naturallythe latter option is available only if you give names to your inputs listing feeding dat mult -input model import numpy as np generates dummy numpy data num_samples max_length text np random randint( text_vocabulary_sizesize=(num_samplesmax_length)licensed to |
11,632 | advanced deep-learning best practices answers are onequestion np random randint( question_vocabulary_sizehot encodedsize=(num_samplesmax_length)not integers answers np random randint( size=(num_samplesanswer_vocabulary_size)model fit([textquestion]answersepochs= batch_size= model fit({'text'text'question'question}answersepochs= batch_size= fitting using dictionary of inputs (only if inputs are namedfitting using list of inputs multi-output models in the same wayyou can use the functional api to build models with multiple outputs (or multiple headsa simple example is network that attempts to simultaneously predict different properties of the datasuch as network that takes as input series of social media posts from single anonymous person and tries to predict attributes of that personsuch as agegenderand income level (see figure listing funct ional api implement at ion of hree-out put model from keras import layers from keras import input from keras models import model vocabulary_size num_income_groups posts_input input(shape=(none,)dtype='int 'name='posts'embedded_posts layers embedding( vocabulary_size)(posts_inputx layers conv ( activation='relu')(embedded_postsx layers maxpooling ( )(xx layers conv ( activation='relu')(xx layers conv ( activation='relu')(xx layers maxpooling ( )(xx layers conv ( activation='relu')(xx layers conv ( activation='relu')(xx layers globalmaxpooling ()(xx layers dense( activation='relu')(xnote that the output layers are given names age_prediction layers dense( name='age')(xincome_prediction layers dense(num_income_groupsactivation='softmax'name='income')(xgender_prediction layers dense( activation='sigmoid'name='gender')(xmodel model(posts_input[age_predictionincome_predictiongender_prediction]licensed to |
11,633 | going beyond the sequential modelthe keras functional api age income gender dense dense dense convnet social media posts figure social media model with hree heads importantlytraining such model requires the ability to specify different loss functions for different heads of the networkfor instanceage prediction is scalar regression taskbut gender prediction is binary classification taskrequiring different training procedure but because gradient descent requires you to minimize scalaryou must combine these losses into single value in order to train the model the simplest way to combine different losses is to sum them all in kerasyou can use either list or dictionary of losses in compile to specify different objects for different outputsthe resulting loss values are summed into global losswhich is minimized during training listing compilat ion opt ions of mult -out put modelmult iple losses model compile(optimizer='rmsprop'loss=['mse''categorical_crossentropy''binary_crossentropy']model compile(optimizer='rmsprop'loss={'age''mse''income''categorical_crossentropy''gender''binary_crossentropy'}equivalent (possible only if you give names to the output layersnote that very imbalanced loss contributions will cause the model representations to be optimized preferentially for the task with the largest individual lossat the expense of the other tasks to remedy thisyou can assign different levels of importance to the loss values in their contribution to the final loss this is useful in particular if the lossesvalues use different scales for instancethe mean squared error (mseloss used for the age-regression task typically takes value around - whereas the crossentropy loss used for the gender-classification task can be as low as in such situationto balance the contribution of the different lossesyou can assign weight of to the crossentropy loss and weight of to the mse loss listing compilat ion opt ions of mult -out put modelloss weighting model compile(optimizer='rmsprop'loss=['mse''categorical_crossentropy''binary_crossentropy']loss_weights=[ ]licensed to |
11,634 | advanced deep-learning best practices model compile(optimizer='rmsprop'loss={'age''mse''income''categorical_crossentropy''gender''binary_crossentropy'}loss_weights={'age' 'income' 'gender' }equivalent (possible only if you give names to the output layersmuch as in the case of multi-input modelsyou can pass numpy data to the model for training either via list of arrays or via dictionary of arrays listing feeding dat mult -out put model model fit(posts[age_targetsincome_targetsgender_targets]epochs= batch_size= model fit(posts{'age'age_targets'income'income_targets'gender'gender_targets}epochs= batch_size= equivalent (possible only if you give names to the output layersage_targetsincome_targetsand gender_targets are assumed to be numpy arrays directed acyclic graphs of layers with the functional apinot only can you build models with multiple inputs and multiple outputsbut you can also implement networks with complex internal topology neural networks in keras are allowed to be arbitrary directed acyclic graphs of layers the qualifier acyclic is importantthese graphs can' have cycles it' impossible for tensor to become the input of one of the layers that generated the only processing loops that are allowed (that isrecurrent connectionsare those internal to recurrent layers several common neural-network components are implemented as graphs two notable ones are inception modules and residual connections to better understand how the functional api can be used to build graphs of layerslet' take look at how you can implement both of them in keras inception modules inception is popular type of network architecture for convolutional neural networksit was developed by christian szegedy and his colleagues at google in - inspired by the earlier network-in-network architecture it consists of stack of modules that themselves look like small independent networkssplit into several parallel branches the most basic form of an inception module has three to four branches starting with convolutionfollowed by convolutionand ending with the concatenation of the resulting features this setup helps the network separately learn min linqiang chenand shuicheng yan"network in network,international conference on learning representations ( )licensed to |
11,635 | spatial features and channel-wise featureswhich is more efficient than learning them jointly more-complex versions of an inception module are also possibletypically involving pooling operationsdifferent spatial convolution sizes (for example instead of on some branches)and branches without spatial convolution (only convolutionan example of such moduletaken from inception is shown in figure output concatenate conv strides= conv strides= conv strides= conv conv conv avgpool strides= conv figure module an inception input the purpose of convolut ions you already know that convolutions extract spatial patches around every tile in an input tensor and apply the same transformation to each patch an edge case is when the patches extracted consist of single tile the convolution operation then becomes equivalent to running each tile vector through dense layerit will compute features that mix together information from the channels of the input tensorbut it won' mix information across space (because it' looking at one tile at timesuch convolutions (also called pointwise convolutionsare featured in inception moduleswhere they contribute to factoring out channel-wise feature learning and spacewise feature learning-- reasonable thing to do if you assume that each channel is highly autocorrelated across spacebut different channels may not be highly correlated with each other here' how you' implement the module featured in figure using the functional api this example assumes the existence of input tensor xlicensed to |
11,636 | advanced deep-learning best practices every branch has the same stride value ( )which is necessary to keep all branch outputs the same size so you can concatenate them in this branchthe striding occurs in the spatial convolution layer from keras import layers branch_a layers conv ( activation='relu'strides= )(xbranch_b layers conv ( activation='relu')(xbranch_b layers conv ( activation='relu'strides= )(branch_bbranch_c layers averagepooling ( strides= )(xbranch_c layers conv ( activation='relu')(branch_cbranch_d layers conv ( activation='relu')(xbranch_d layers conv ( activation='relu')(branch_dbranch_d layers conv ( activation='relu'strides= )(branch_doutput layers concatenate[branch_abranch_bbranch_cbranch_d]axis=- in this branchthe striding occurs in the average pooling layer concatenates the branch outputs to obtain the module output note that the full inception architecture is available in keras as keras applications inception_v inceptionv including weights pretrained on the imagenet dataset another closely related model available as part of the keras applications module is xception xceptionwhich stands for extreme inceptionis convnet architecture loosely inspired by inception it takes the idea of separating the learning of channel-wise and space-wise features to its logical extremeand replaces inception modules with depthwise separable convolutions consisting of depthwise convolution ( spatial convolution where every input channel is handled separatelyfollowed by pointwise convolution ( convolution)--effectivelyan extreme form of an inception modulewhere spatial features and channel-wise features are fully separated xception has roughly the same number of parameters as inception but it shows better runtime performance and higher accuracy on imagenet as well as other large-scale datasetsdue to more efficient use of model parameters residual connections residual connections are common graph-like network component found in many post network architecturesincluding xception they were introduced by he et al from microsoft in their winning entry in the ilsvrc imagenet challenge in late they tackle two common problems that plague any large-scale deep-learning modelvanishing gradients and representational bottlenecks in generaladding residual connections to any model that has more than layers is likely to be beneficial francois chollet"xceptiondeep learning with depthwise separable convolutions,conference on computer vision and pattern recognition ( )he et al "deep residual learning for image recognition,licensed to |
11,637 | residual connection consists of making the output of an earlier layer available as input to later layereffectively creating shortcut in sequential network rather than being concatenated to the later activationthe earlier output is summed with the later activationwhich assumes that both activations are the same size if they're different sizesyou can use linear transformation to reshape the earlier activation into the target shape (for examplea dense layer without an activation orfor convolutional feature mapsa convolution without an activationhere' how to implement residual connection in keras when the feature-map sizes are the sameusing identity residual connections this example assumes the existence of input tensor xapplies transformation to from keras import layers layers conv ( activation='relu'padding='same')(xy layers conv ( activation='relu'padding='same')(yy layers conv ( activation='relu'padding='same')(yy layers add([yx]adds the original back to the output features and the following implements residual connection when the feature-map sizes differusing linear residual connection (againassuming the existence of input tensor )uses convolution to linearly downsample the original tensor to the same shape as from keras import layers layers conv ( activation='relu'padding='same')(xy layers conv ( activation='relu'padding='same')(yy layers maxpooling ( strides= )(yresidual layers conv ( strides= padding='same')(xy layers add([yresidual]adds the residual tensor back to the output features representational bot tlenecks in deep learning in sequential modeleach successive representation layer is built on top of the previous onewhich means it only has access to information contained in the activation of the previous layer if one layer is too small (for exampleit has features that are too low-dimensional)then the model will be constrained by how much information can be crammed into the activations of this layer licensed to |
11,638 | advanced deep-learning best practices (continuedyou can grasp this concept with signal-processing analogyif you have an audioprocessing pipeline that consists of series of operationseach of which takes as input the output of the previous operationthen if one operation crops your signal to low-frequency range (for example - khz)the operations downstream will never be able to recover the dropped frequencies any loss of information is permanent residual connectionsby reinjecting earlier information downstreampartially solve this issue for deep-learning models vanishing gradients in deep learning backpropagationthe master algorithm used to train deep neural networksworks by propagating feedback signal from the output loss down to earlier layers if this feedback signal has to be propagated through deep stack of layersthe signal may become tenuous or even be lost entirelyrendering the network untrainable this issue is known as vanishing gradients this problem occurs both with deep networks and with recurrent networks over very long sequences--in both casesa feedback signal must be propagated through long series of operations you're already familiar with the solution that the lstm layer uses to address this problem in recurrent networksit introduces carry track that propagates information parallel to the main processing track residual connections work in similar way in feedforward deep networksbut they're even simplerthey introduce purely linear information carry track parallel to the main layer stackthus helping to propagate gradients through arbitrarily deep stacks of layers layer weight sharing one more important feature of the functional api is the ability to reuse layer instance several times when you call layer instance twiceinstead of instantiating new layer for each callyou reuse the same weights with every call this allows you to build models that have shared branches--several branches that all share the same knowledge and perform the same operations that isthey share the same representations and learn these representations simultaneously for different sets of inputs for exampleconsider model that attempts to assess the semantic similarity between two sentences the model has two inputs (the two sentences to compareand outputs score between and where means unrelated sentences and means sentences that are either identical or reformulations of each other such model could be useful in many applicationsincluding deduplicating natural-language queries in dialog system in this setupthe two input sentences are interchangeablebecause semantic similarity is symmetrical relationshipthe similarity of to is identical to the similarity of to for this reasonit wouldn' make sense to learn two independent models for licensed to |
11,639 | processing each input sentence ratheryou want to process both with single lstm layer the representations of this lstm layer (its weightsare learned based on both inputs simultaneously this is what we call siamese lstm model or shared lstm here' how to implement such model using layer sharing (layer reusein the keras functional apifrom keras import layers from keras import input from keras models import model instantiates single lstm layeronce lstm layers lstm( building the left branch of the modelinputs are variable-length sequences of vectors of size left_input input(shape=(none )left_output lstm(left_inputright_input input(shape=(none )right_output lstm(right_inputbuilding the right branch of the modelwhen you call an existing layer instanceyou reuse its weights merged layers concatenate([left_outputright_output]axis=- predictions layers dense( activation='sigmoid')(mergedmodel model([left_inputright_input]predictionsmodel fit([left_dataright_data]targetsbuilds the classifier on top instantiating and training the modelwhen you train such modelthe weights of the lstm layer are updated based on both inputs naturallya layer instance may be used more than once--it can be called arbitrarily many timesreusing the same set of weights every time models as layers importantlyin the functional apimodels can be used as you' use layers--effectivelyyou can think of model as "bigger layer this is true of both the sequential and model classes this means you can call model on an input tensor and retrieve an output tensory model(xif the model has multiple input tensors and multiple output tensorsit should be called with list of tensorsy model([ ]when you call model instanceyou're reusing the weights of the model--exactly like what happens when you call layer instance calling an instancewhether it' layer instance or model instancewill always reuse the existing learned representations of the instance--which is intuitive one simple practical example of what you can build by reusing model instance is vision model that uses dual camera as its inputtwo parallel camerasa few centimeters (one inchapart such model can perceive depthwhich can be useful in many applications you shouldn' need two independent models to extract visual licensed to |
11,640 | advanced deep-learning best practices features from the left camera and the right camera before merging the two feeds such low-level processing can be shared across the two inputsthat isdone via layers that use the same weights and thus share the same representations here' how you' implement siamese vision model (shared convolutional basein kerasfrom keras import layers from keras import applications from keras import input the base image-processing model is the xception network (convolutional base onlyxception_base applications xception(weights=noneinclude_top=falseleft_input input(shape=( )right_input input(shape=( )the inputs are rgb images left_features xception_base(left_inputright_input xception_base(right_inputcalls the same vision model twice merged_features layers concatenate[left_featuresright_input]axis=- the merged features contain information from the right visual feed and the left visual feed wrapping up this concludes our introduction to the keras functional api--an essential tool for building advanced deep neural network architectures now you know the followingto step out of the sequential api whenever you need anything more than linear stack of layers how to build keras models with several inputsseveral outputsand complex internal network topologyusing the keras functional api how to reuse the weights of layer or model across different processing branchesby calling the same layer or model instance several times licensed to |
11,641 | inspecting and monitoring deep-learning models using keras callbacks and tensorboard in this sectionwe'll review ways to gain greater access to and control over what goes on inside your model during training launching training run on large dataset for tens of epochs using model fit(or model fit_generator(can be bit like launching paper airplanepast the initial impulseyou don' have any control over its trajectory or its landing spot if you want to avoid bad outcomes (and thus wasted paper airplanes)it' smarter to use not paper planebut drone that can sense its environmentsend data back to its operatorand automatically make steering decisions based on its current state the techniques we present here will transform the call to model fit(from paper airplane into smartautonomous drone that can selfintrospect and dynamically take action using callbacks to act on model during training when you're training modelthere are many things you can' predict from the start in particularyou can' tell how many epochs will be needed to get to an optimal validation loss the examples so far have adopted the strategy of training for enough epochs that you begin overfittingusing the first run to figure out the proper number of epochs to train forand then finally launching new training run from scratch using this optimal number of coursethis approach is wasteful much better way to handle this is to stop training when you measure that the validation loss in no longer improving this can be achieved using keras callback callback is an object ( class instance implementing specific methodsthat is passed to the model in the call to fit and that is called by the model at various points during training it has access to all the available data about the state of the model and its performanceand it can take actioninterrupt trainingsave modelload different weight setor otherwise alter the state of the model here are some examples of ways you can use callbacksmodel checkpointing--saving the current weights of the model at different points during training early stopping--interrupting training when the validation loss is no longer improving (and of coursesaving the best model obtained during trainingdynamically adjusting the value of certain parameters during training--such as the learning rate of the optimizer logging training and validation metrics during trainingor visualizing the representations learned by the model as they're updated--the keras progress bar that you're familiar with is callbackthe keras callbacks module includes number of built-in callbacks (this is not an exhaustive list)keras callbacks modelcheckpoint keras callbacks earlystopping licensed to |
11,642 | advanced deep-learning best practices keras callbacks learningratescheduler keras callbacks reducelronplateau keras callbacks csvlogger let' review few of them to give you an idea of how to use themmodelcheckpointearlystoppingand reducelronplateau the odelcheckpoint and earlystopping callbacks you can use the earlystopping callback to interrupt training once target metric being monitored has stopped improving for fixed number of epochs for instancethis callback allows you to interrupt training as soon as you start overfittingthus avoiding having to retrain your model for smaller number of epochs this callback is typically used in combination with modelcheckpointwhich lets you continually save the model during training (andoptionallysave only the current best model so farthe version of the model that achieved the best performance at the end of an epoch)callbacks are passed to the model via the callbacks argument in fitwhich takes list of callbacks you can pass any number of callbacks interrupts training when improvement stops import keras monitors the model' validation accuracy interrupts training when callbacks_list accuracy has stopped keras callbacks earlystoppingimproving for more than one monitor='acc'epoch (that istwo epochspatience= )keras callbacks modelcheckpointsaves the current weights after every epoch filepath='my_model 'path to the destination model file monitor='val_loss'save_best_only=truethese two arguments mean you won' overwrite the model file unless val_loss has improvedwhich allows you to keep the best model seen during training model compile(optimizer='rmsprop'loss='binary_crossentropy'metrics=['acc']model fit(xyepochs= batch_size= callbacks=callbacks_listvalidation_data=(x_valy_val)you monitor accuracyso it should be part of the model' metrics note that because the callback will monitor validation loss and validation accuracyyou need to pass validation_data to the call to fit the reducelronplateau callback you can use this callback to reduce the learning rate when the validation loss has stopped improving reducing or increasing the learning rate in case of loss plateau is is an effective strategy to get out of local minima during training the following example uses the reducelronplateau callbacklicensed to |
11,643 | callbacks_list monitors the model' validation loss keras callbacks reducelronplateaumonitor='val_lossfactor= divides the learning rate by when triggered patience= the callback is triggered after the validation loss has stopped improving for epochs model fit(xyepochs= batch_size= callbacks=callbacks_listvalidation_data=(x_valy_val)because the callback will monitor the validation lossyou need to pass validation_data to the call to fit writing your own callback if you need to take specific action during training that isn' covered by one of the built-in callbacksyou can write your own callback callbacks are implemented by subclassing the class keras callbacks callback you can then implement any number of the following transparently named methodswhich are called at various points during trainingon_epoch_begin on_epoch_end called at the start of every epoch called at the end of every epoch on_batch_begin on_batch_end called right before processing each batch called right after processing each batch on_train_begin on_train_end called at the start of training called at the end of training these methods all are called with logs argumentwhich is dictionary containing information about the previous batchepochor training runtraining and validation metricsand so on additionallythe callback has access to the following attributesself model--the model instance from which the callback is being called self validation_data--the value of what was passed to fit as validation data here' simple example of custom callback that saves to disk (as numpy arraysthe activations of every layer of the model at the end of every epochcomputed on the first sample of the validation setimport keras import numpy as np class activationlogger(keras callbacks callback)called by the parent model before trainingto inform the callback of what model will be calling it def set_model(selfmodel)self model model layer_outputs [layer output for layer in model layersself activations_model keras models model(model inputlayer_outputsdef on_epoch_end(selfepochlogs=none)if self validation_data is noneraise runtimeerror('requires validation_data 'licensed to model instance that returns the activations of every layer |
11,644 | advanced deep-learning best practices validation_sample self validation_data[ ][ : activations self activations_model predict(validation_samplef open('activations_at_epoch_str(epochnpz'' 'np savez(factivationsf close(obtains the first input sample of the validation data saves arrays to disk this is all you need to know about callbacks--the rest is technical detailswhich you can easily look up now you're equipped to perform any sort of logging or preprogrammed intervention on keras model during training introduction to tensorboardthe tensorflow visualization framework to do good research or develop good modelsyou need richfrequent feedback about what' going on inside your models during your experiments that' the point of running experimentsto get information about how well model performs--as much information as possible making progress is an iterative processor loopyou start with an idea and express it as an experimentattempting to validate or invalidate your idea you run this experiment and process the information it generates this inspires your next idea the more iterations of this loop you're able to runthe more refined and powerful your ideas become keras helps you go from idea to experiment in the least possible timeand fast gpus can help you get from experiment to result as quickly as possible but what about processing the experiment resultsthat' where tensorboard comes in idea visualization frameworktensorboard deep-learning frameworkkeras results experiment infrastructure figure the loop of progress this section introduces tensorboarda browser-based visualization tool that comes packaged with tensorflow note that it' only available for keras models when you're using keras with the tensorflow backend the key purpose of tensorboard is to help you visually monitor everything that goes on inside your model during training if you're monitoring more information than just the model' final lossyou can develop clearer vision of what the model does and doesn' doand you can make progress more quickly tensorboard gives you access to several neat featuresall in your browserlicensed to |
11,645 | visually monitoring metrics during training visualizing your model architecture visualizing histograms of activations and gradients exploring embeddings in let' demonstrate these features on simple example you'll train convnet on the imdb sentiment-analysis task the model is similar to the one you saw in the last section of you'll consider only the top , words in the imdb vocabularyto make visualizing word embeddings more tractable listing text -classificat ion model use wit tensorboard import keras from keras import layers from keras datasets import imdb from keras preprocessing import sequence number of words to consider as features max_features max_len cuts off texts after this number of words (among max_features most common words(x_trainy_train)(x_testy_testimdb load_data(num_words=max_featuresx_train sequence pad_sequences(x_trainmaxlen=max_lenx_test sequence pad_sequences(x_testmaxlen=max_lenmodel keras models sequential(model add(layers embedding(max_features input_length=max_lenname='embed')model add(layers conv ( activation='relu')model add(layers maxpooling ( )model add(layers conv ( activation='relu')model add(layers globalmaxpooling ()model add(layers dense( )model summary(model compile(optimizer='rmsprop'loss='binary_crossentropy'metrics=['acc']before you start using tensorboardyou need to create directory where you'll store the log files it generates listing creat ing direct ory for tensorboard log files mkdir my_log_dir let' launch the training with tensorboard callback instance this callback will write log events to disk at the specified location licensed to |
11,646 | listing advanced deep-learning best practices training he model wit tensorboard callback callbacks log files will be written keras callbacks tensorboardat this location log_dir='my_log_dir'histogram_freq= records activation histograms every epoch embeddings_freq= records embedding data every epoch history model fit(x_trainy_trainepochs= batch_size= validation_split= callbacks=callbacksat this pointyou can launch the tensorboard server from the command lineinstructing it to read the logs the callback is currently writing the tensorboard utility should have been automatically installed on your machine the moment you installed tensorflow (for examplevia pip)tensorboard --logdir=my_log_dir you can then browse to figure in addition to live graphs of the training and validation metricsyou get access to the histograms tabwhere you can find pretty visualizations of histograms of activation values taken by your layers (see figure figure tensorboardmet rics monitoring licensed to |
11,647 | figure tensorboardact ivat ion histograms the embeddings tab gives you way to inspect the embedding locations and spatial relationships of the , words in the input vocabularyas learned by the initial embedding layer because the embedding space is -dimensionaltensorboard automatically reduces it to or using dimensionality-reduction algorithm of your choiceeither principal component analysis (pcaor -distributed stochastic neighbor embedding ( -snein figure in the point cloudyou can clearly see two clusterswords with positive connotation and words with negative connotation the visualization makes it immediately obvious that embeddings trained jointly with specific objective result in models that are completely specific to the underlying task--that' the reason using pretrained generic word embeddings is rarely good idea licensed to |
11,648 | figure advanced deep-learning best practices tensorboardinteractive word-embedding visualizat ion the graphs tab shows an interactive visualization of the graph of low-level tensorflow operations underlying your keras model (see figure as you can seethere' lot more going on than you would expect the model you just built may look simple when defined in keras-- small stack of basic layers--but under the hoodyou need to construct fairly complex graph structure to make it work lot of it is related to the gradient-descent process this complexity differential between what you see and what you're manipulating is the key motivation for using keras as your way of building modelsinstead of working with raw tensorflow to define everything from scratch keras makes your workflow dramatically simpler licensed to |
11,649 | figure tensorboardtensorflow graph visualizat ion note that keras also provides anothercleaner way to plot models as graphs of layers rather than graphs of tensorflow operationsthe utility keras utils plot_model using it requires that you've installed the python pydot and pydot-ng libraries as well as the graphviz library let' take quick lookfrom keras utils import plot_model plot_model(modelto_file='model png'this creates the png image shown in figure licensed to |
11,650 | advanced deep-learning best practices figure model plot as graph of layersgenerated wit plot_model you also have the option of displaying shape information in the graph of layers this example visualizes model topology using plot_model and the show_shapes option (see figure )from keras utils import plot_model plot_model(modelshow_shapes=trueto_file='model png'licensed to |
11,651 | figure model plot with shape informat ion wrapping up keras callbacks provide simple way to monitor models during training and automatically take action based on the state of the model when you're using tensorflowtensorboard is great way to visualize model activity in your browser you can use it in keras models via the tensorboard callback licensed to |
11,652 | getting the most out of your models advanced deep-learning best practices trying out architectures blindly works well enough if you just need something that works okay in this sectionwe'll go beyond "works okayto "works great and wins machine-learning competitionsby offering you quick guide to set of must-know techniques for building state-of-the-art deep-learning models advanced architecture patterns we covered one important design pattern in detail in the previous sectionresidual connections there are two more design patterns you should know aboutnormalization and depthwise separable convolution these patterns are especially relevant when you're building high-performing deep convnetsbut they're commonly found in many other types of architectures as well batch normalization normalization is broad category of methods that seek to make different samples seen by machine-learning model more similar to each otherwhich helps the model learn and generalize well to new data the most common form of data normalization is one you've seen several times in this book alreadycentering the data on by subtracting the mean from the dataand giving the data unit standard deviation by dividing the data by its standard deviation in effectthis makes the assumption that the data follows normal (or gaussiandistribution and makes sure this distribution is centered and scaled to unit variancenormalized_data (data np mean(dataaxis)np std(dataaxisprevious examples normalized data before feeding it into models but data normalization should be concern after every transformation operated by the networkeven if the data entering dense or conv network has mean and unit variancethere' no reason to expect priori that this will be the case for the data coming out batch normalization is type of layer (batchnormalization in kerasintroduced in by ioffe and szegedy; it can adaptively normalize data even as the mean and variance change over time during training it works by internally maintaining an exponential moving average of the batch-wise mean and variance of the data seen during training the main effect of batch normalization is that it helps with gradient propagation--much like residual connections--and thus allows for deeper networks some very deep networks can only be trained if they include multiple batchnormalization layers for instancebatchnormalization is used liberally in many of the advanced convnet architectures that come packaged with kerassuch as resnet inception and xception sergey ioffe and christian szegedy"batch normalizationaccelerating deep network training by reducing internal covariate shift,proceedings of the nd international conference on machine learning ( )licensed to |
11,653 | getting the most out of your models the batchnormalization layer is typically used after convolutional or densely connected layerconv_model add(layers conv ( activation='relu')conv_model add(layers batchnormalization()dense_model add(layers dense( activation='relu')dense_model add(layers batchnormalization()after conv layer after dense layer the batchnormalization layer takes an axis argumentwhich specifies the feature axis that should be normalized this argument defaults to - the last axis in the input tensor this is the correct value when using dense layersconv layersrnn layersand conv layers with data_format set to "channels_lastbut in the niche use case of conv layers with data_format set to "channels_first"the features axis is axis the axis argument in batchnormalization should accordingly be set to batch renormalizat ion recent improvement over regular batch normalization is batch renormalizationintroduced by ioffe in it offers clears benefits over batch normalizationat no apparent cost at the time of writingit' too early to tell whether it will supplant batch normalization--but think it' likely even more recentlyklambauer et al introduced self-normalizing neural networks, which manage to keep data normalized after going through any dense layer by using specific activation function (seluand specific initializer (lecun_normalthis schemealthough highly interestingis limited to densely connected networks for nowand its usefulness hasn' yet been broadly replicated sergey ioffebatch renormalizationtowards reducing minibatch dependence in batchnormalized models( )https:arxiv orgabs gunter klambauer et al self-normalizing neural networks,conference on neural information processing systems ( )https:arxiv orgabs depthwise separable convolution what if told you that there' layer you can use as drop-in replacement for conv that will make your model lighter (fewer trainable weight parametersand faster (fewer floating-point operationsand cause it to perform few percentage points better on its taskthat is precisely what the depthwise separable convolution layer does (separableconv dthis layer performs spatial convolution on each channel of its inputindependentlybefore mixing output channels via pointwise convolution ( convolution)as shown in figure this is equivalent to separating the learning of spatial features and the learning of channel-wise featureswhich makes lot of sense if you assume that spatial locations in the input are highly correlatedbut different channels are fairly independent it requires significantly fewer parameters and involves fewer computationsthus resulting in smallerspeedier models and because it' more representationally efficient way to perform convolutionit tends to learn better representations using less dataresulting in better-performing models licensed to |
11,654 | advanced deep-learning best practices conv (pointwise convconcatenate conv conv conv depthwise convolutionindependent spatial convs per channel conv figure dept hwise separable convolut iona dept hwise convolut ion followed by pointwise convolution split channels these advantages become especially important when you're training small models from scratch on limited data for instancehere' how you can build lightweightdepthwise separable convnet for an image-classification task (softmax categorical classificationon small datasetfrom keras models import sequentialmodel from keras import layers height width channels num_classes model sequential(model add(layers separableconv ( activation='relu'input_shape=(heightwidthchannels,))model add(layers separableconv ( activation='relu')model add(layers maxpooling ( )model add(layers separableconv ( activation='relu')model add(layers separableconv ( activation='relu')model add(layers maxpooling ( )model add(layers separableconv ( activation='relu')model add(layers separableconv ( activation='relu')model add(layers globalaveragepooling ()model add(layers dense( activation='relu')model add(layers dense(num_classesactivation='softmax')model compile(optimizer='rmsprop'loss='categorical_crossentropy'when it comes to larger-scale modelsdepthwise separable convolutions are the basis of the xception architecturea high-performing convnet that comes packaged with keras you can read more about the theoretical grounding for depthwise separable licensed to |
11,655 | convolutions and xception in my paper "xceptiondeep learning with depthwise separable convolutions hyperparameter optimization when building deep-learning modelyou have to make many seemingly arbitrary decisionshow many layers should you stackhow many units or filters should go in each layershould you use relu as activationor different functionshould you use batchnormalization after given layerhow much dropout should you useand so on these architecture-level parameters are called hyperparameters to distinguish them from the parameters of modelwhich are trained via backpropagation in practiceexperienced machine-learning engineers and researchers build intuition over time as to what works and what doesn' when it comes to these choices-they develop hyperparameter-tuning skills but there are no formal rules if you want to get to the very limit of what can be achieved on given taskyou can' be content with arbitrary choices made by fallible human your initial decisions are almost always suboptimaleven if you have good intuition you can refine your choices by tweaking them by hand and retraining the model repeatedly--that' what machinelearning engineers and researchers spend most of their time doing but it shouldn' be your job as human to fiddle with hyperparameters all day--that is better left to machine thus you need to explore the space of possible decisions automaticallysystematicallyin principled way you need to search the architecture space and find the bestperforming ones empirically that' what the field of automatic hyperparameter optimization is aboutit' an entire field of researchand an important one the process of optimizing hyperparameters typically looks like this choose set of hyperparameters (automaticallybuild the corresponding model fit it to your training dataand measure the final performance on the validation data choose the next set of hyperparameters to try (automaticallyrepeat eventuallymeasure performance on your test data the key to this process is the algorithm that uses this history of validation performancegiven various sets of hyperparametersto choose the next set of hyperparameters to evaluate many different techniques are possiblebayesian optimizationgenetic algorithmssimple random searchand so on training the weights of model is relatively easyyou compute loss function on mini-batch of data and then use the backpropagation algorithm to move the weights see note above licensed to |
11,656 | advanced deep-learning best practices in the right direction updating hyperparameterson the other handis extremely challenging consider the followingcomputing the feedback signal (does this set of hyperparameters lead to high-performing model on this task?can be extremely expensiveit requires creating and training new model from scratch on your dataset the hyperparameter space is typically made of discrete decisions and thus isn' continuous or differentiable henceyou typically can' do gradient descent in hyperparameter space insteadyou must rely on gradient-free optimization techniqueswhich naturally are far less efficient than gradient descent because these challenges are difficult and the field is still youngwe currently only have access to very limited tools to optimize models oftenit turns out that random search (choosing hyperparameters to evaluate at randomrepeatedlyis the best solutiondespite being the most naive one but one tool have found reliably better than random search is hyperopt (library for hyperparameter optimization that internally uses trees of parzen estimators to predict sets of hyperparameters that are likely to work well another library called hyperas (with keras models do check it out one important issue to keep in mind when doing automatic hyperparameter optimization at scale is validation-set overfitting because you're updating hyperparameters based on signal that is computed using your validation datayou're effectively training them on the validation dataand thus they will quickly overfit to the validation data always keep this in mind note overallhyperparameter optimization is powerful technique that is an absolute requirement to get to state-of-the-art models on any task or to win machine-learning competitions think about itonce upon timepeople handcrafted the features that went into shallow machine-learning models that was very much suboptimal nowdeep learning automates the task of hierarchical feature engineering--features are learned using feedback signalnot hand-tunedand that' the way it should be in the same wayyou shouldn' handcraft your model architecturesyou should optimize them in principled way at the time of writingthe field of automatic hyperparameter optimization is very young and immatureas deep learning was some years agobut expect it to boom in the next few years model ensembling another powerful technique for obtaining the best possible results on task is model ensembling ensembling consists of pooling together the predictions of set of different modelsto produce better predictions if you look at machine-learning competitionsin particular on kaggleyou'll see that the winners use very large ensembles of models that inevitably beat any single modelno matter how good licensed to |
11,657 | getting the most out of your models ensembling relies on the assumption that different good models trained independently are likely to be good for different reasonseach model looks at slightly different aspects of the data to make its predictionsgetting part of the "truthbut not all of it you may be familiar with the ancient parable of the blind men and the elephanta group of blind men come across an elephant for the first time and try to understand what the elephant is by touching it each man touches different part of the elephant' body--just one partsuch as the trunk or leg then the men describe to each other what an elephant is"it' like snake,"like pillar or tree,and so on the blind men are essentially machine-learning models trying to understand the manifold of the training dataeach from its own perspectiveusing its own assumptions (provided by the unique architecture of the model and the unique random weight initializationeach of them gets part of the truth of the databut not the whole truth by pooling their perspectives togetheryou can get far more accurate description of the data the elephant is combination of partsnot any single blind man gets it quite rightbutinterviewed togetherthey can tell fairly accurate story let' use classification as an example the easiest way to pool the predictions of set of classifiers (to ensemble the classifiersis to average their predictions at inference timeuse four different models to compute initial predictions preds_a model_a predict(x_valpreds_b model_b predict(x_valpreds_c model_c predict(x_valpreds_d model_d predict(x_valthis new prediction array should be more accurate than any of the initial ones final_preds (preds_a preds_b preds_c preds_dthis will work only if the classifiers are more or less equally good if one of them is significantly worse than the othersthe final predictions may not be as good as the best classifier of the group smarter way to ensemble classifiers is to do weighted averagewhere the weights are learned on the validation data--typicallythe better classifiers are given higher weightand the worse classifiers are given lower weight to search for good set of ensembling weightsyou can use random search or simple optimization algorithm such as nelder-meadpreds_a model_a predict(x_valpreds_b model_b predict(x_valpreds_c model_c predict(x_valpreds_d model_d predict(x_valthese weights ( are assumed to be learned empirically final_preds preds_a preds_b preds_c preds_d there are many possible variantsyou can do an average of an exponential of the predictionsfor instance in generala simple weighted average with weights optimized on the validation data provides very strong baseline the key to making ensembling work is the diversity of the set of classifiers diversity is strength if all the blind men only touched the elephant' trunkthey would agree licensed to |
11,658 | advanced deep-learning best practices that elephants are like snakesand they would forever stay ignorant of the truth of the elephant diversity is what makes ensembling work in machine-learning termsif all of your models are biased in the same waythen your ensemble will retain this same bias if your models are biased in different waysthe biases will cancel each other outand the ensemble will be more robust and more accurate for this reasonyou should ensemble models that are as good as possible while being as different as possible this typically means using very different architectures or even different brands of machine-learning approaches one thing that is largely not worth doing is ensembling the same network trained several times independentlyfrom different random initializations if the only difference between your models is their random initialization and the order in which they were exposed to the training datathen your ensemble will be low-diversity and will provide only tiny improvement over any single model one thing have found to work well in practice--but that doesn' generalize to every problem domain--is the use of an ensemble of tree-based methods (such as random forests or gradient-boosted treesand deep neural networks in partner andrei kolev and took fourth place in the higgs boson decay detection challenge on kaggle (www kaggle com/ /higgs-bosonusing an ensemble of various tree models and deep neural networks remarkablyone of the models in the ensemble originated from different method than the others (it was regularized greedy forestand had significantly worse score than the others unsurprisinglyit was assigned small weight in the ensemble but to our surpriseit turned out to improve the overall ensemble by large factorbecause it was so different from every other modelit provided information that the other models didn' have access to that' precisely the point of ensembling it' not so much about how good your best model isit' about the diversity of your set of candidate models in recent timesone style of basic ensemble that has been very successful in practice is the wide and deep category of modelsblending deep learning with shallow learning such models consist of jointly training deep neural network with large linear model the joint training of family of diverse models is yet another option to achieve model ensembling wrapping up when building high-performing deep convnetsyou'll need to use residual connectionsbatch normalizationand depthwise separable convolutions in the futureit' likely that depthwise separable convolutions will completely replace regular convolutionswhether for dor applicationsdue to their higher representational efficiency building deep networks requires making many small hyperparameter and architecture choiceswhich together define how good your model will be rather than basing these choices on intuition or random chanceit' better to systematically search hyperparameter space to find optimal choices at this licensed to |
11,659 | timethe process is expensiveand the tools to do it aren' very good but the hyperopt and hyperas libraries may be able to help you when doing hyperparameter optimizationbe mindful of validation-set overfittingwinning machine-learning competitions or otherwise obtaining the best possible results on task can only be done with large ensembles of models ensembling via well-optimized weighted average is usually good enough rememberdiversity is strength it' largely pointless to ensemble very similar modelsthe best ensembles are sets of models that are as dissimilar as possible (while having as much predictive power as possiblenaturallylicensed to |
11,660 | advanced deep-learning best practices summary in this you learned the followinghow to build models as arbitrary graphs of layersreuse layers (layer weight sharing)and use models as python functions (model templatingyou can use keras callbacks to monitor your models during training and take action based on model state tensorboard allows you to visualize metricsactivation histogramsand even embedding spaces what batch normalizationdepthwise separable convolutionand residual connections are why you should use hyperparameter optimization and model ensembling with these new toolsyou're better equipped to use deep learning in the real world and start building highly competitive deep-learning models licensed to |
11,661 | this covers text generation with lstm implementing deepdream performing neural style transfer variational autoencoders understanding generative adversarial networks the potential of artificial intelligence to emulate human thought processes goes beyond passive tasks such as object recognition and mostly reactive tasks such as driving car it extends well into creative activities when first made the claim that in not-so-distant futuremost of the cultural content that we consume will be created with substantial help from aisi was met with utter disbeliefeven from longtime machine-learning practitioners that was in fast-forward three yearsand the disbelief has receded--at an incredible speed in the summer of we were entertained by google' deepdream algorithm turning an image into psychedelic mess of dog eyes and pareidolic artifactsin we used the prisma application to turn photos into paintings of various styles in the summer of an experimental short moviesunspringwas directed using script written by long short-term memory (lstmalgorithm--complete with dialogue maybe you've recently listened to music that was tentatively generated by neural network licensed to |
11,662 | generative deep learning grantedthe artistic productions we've seen from ai so far have been fairly low quality ai isn' anywhere close to rivaling human screenwriterspaintersand composers but replacing humans was always beside the pointartificial intelligence isn' about replacing our own intelligence with something elseit' about bringing into our lives and work more intelligence--intelligence of different kind in many fieldsbut especially in creative onesai will be used by humans as tool to augment their own capabilitiesmore augmented intelligence than artificial intelligence large part of artistic creation consists of simple pattern recognition and technical skill and that' precisely the part of the process that many find less attractive or even dispensable that' where ai comes in our perceptual modalitiesour languageand our artwork all have statistical structure learning this structure is what deep-learning algorithms excel at machine-learning models can learn the statistical latent space of imagesmusicand storiesand they can then sample from this spacecreating new artworks with characteristics similar to those the model has seen in its training data naturallysuch sampling is hardly an act of artistic creation in itself it' mere mathematical operationthe algorithm has no grounding in human lifehuman emotionsor our experience of the worldinsteadit learns from an experience that has little in common with ours it' only our interpretationas human spectatorsthat will give meaning to what the model generates but in the hands of skilled artistalgorithmic generation can be steered to become meaningful--and beautiful latent space sampling can become brush that empowers the artistaugments our creative affordancesand expands the space of what we can imagine what' moreit can make artistic creation more accessible by eliminating the need for technical skill and practice--setting up new medium of pure expressionfactoring art apart from craft iannis xenakisa visionary pioneer of electronic and algorithmic musicbeautifully expressed this same idea in the sin the context of the application of automation technology to music composition: freed from tedious calculationsthe composer is able to devote himself to the general problems that the new musical form poses and to explore the nooks and crannies of this form while modifying the values of the input data for examplehe may test all instrumental combinations from soloists to chamber orchestrasto large orchestras with the aid of electronic computers the composer becomes sort of pilothe presses the buttonsintroduces coordinatesand supervises the controls of cosmic vessel sailing in the space of soundacross sonic constellations and galaxies that he could formerly glimpse only as distant dream in this we'll explore from various angles the potential of deep learning to augment artistic creation we'll review sequence data generation (which can be used to generate text or music)deepdreamand image generation using both variational autoencoders and generative adversarial networks we'll get your computer to dream up content never seen beforeand maybe we'll get you to dreamtooabout the fantastic possibilities that lie at the intersection of technology and art let' get started iannis xenakis"musiques formellesnouveaux principes formels de composition musicale,special issue of la revue musicalenos - ( licensed to |
11,663 | text generation with lstm in this sectionwe'll explore how recurrent neural networks can be used to generate sequence data we'll use text generation as an examplebut the exact same techniques can be generalized to any kind of sequence datayou could apply it to sequences of musical notes in order to generate new musicto timeseries of brushstroke data (for examplerecorded while an artist paints on an ipadto generate paintings stroke by strokeand so on sequence data generation is in no way limited to artistic content generation it has been successfully applied to speech synthesis and to dialogue generation for chatbots the smart reply feature that google released in capable of automatically generating selection of quick replies to emails or text messagesis powered by similar techniques brief history of generative recurrent networks in late few people had ever seen the initials lstmeven in the machine-learning community successful applications of sequence data generation with recurrent networks only began to appear in the mainstream in but these techniques have fairly long historystarting with the development of the lstm algorithm in this new algorithm was used early on to generate text character by character in douglas eckthen at schmidhuber' lab in switzerlandapplied lstm to music generation for the first timewith promising results eck is now researcher at google brainand in he started new research group therecalled magentafocused on applying modern deep-learning techniques to produce engaging music sometimesgood ideas take years to get started in the late and early salex graves did important pioneering work on using recurrent networks for sequence data generation in particularhis work on applying recurrent mixture density networks to generate human-like handwriting using timeseries of pen positions is seen by some as turning point this specific application of neural networks at that specific moment in time captured for me the notion of machines that dream and was significant inspiration around the time started developing keras graves left similar commented-out remark hidden in latex file uploaded to the preprint server arxiv"generating sequential data is the closest computers get to dreaming several years laterwe take lot of these developments for grantedbut at the timeit was difficult to watch graves' demonstrations and not walk away awe-inspired by the possibilities since thenrecurrent neural networks have been successfully used for music generationdialogue generationimage generationspeech synthesisand molecule design they were even used to produce movie script that was then cast with live actors sepp hochreiter and jurgen schmidhuber"long short-term memory,neural computation no ( alex graves"generating sequences with recurrent neural networks,arxiv ( )abs/ licensed to |
11,664 | generative deep learning how do you generate sequence datathe universal way to generate sequence data in deep learning is to train network (usually an rnn or convnetto predict the next token or next few tokens in sequenceusing the previous tokens as input for instancegiven the input "the cat is on the ma,the network is trained to predict the target tthe next character as usual when working with text datatokens are typically words or charactersand any network that can model the probability of the next token given the previous ones is called language model language model captures the latent space of languageits statistical structure once you have such trained language modelyou can sample from it (generate new sequences)you feed it an initial string of text (called conditioning data)ask it to generate the next character or the next word (you can even generate several tokens at once)add the generated output back to the input dataand repeat the process many times (see figure this loop allows you to generate sequences of arbitrary length that reflect the structure of the data on which the model was trainedsequences that look almost like human-written sentences in the example we present in this sectionyou'll take lstm layerfeed it strings of characters extracted from text corpusand train it to predict character the output of the model will be softmax over all possible charactersa probability distribution for the next character this lstm is called character-level neural language model initial text probability distribution for the next character initial text sampled next character the cat sat on the language model sampling strategy the cat sat on the ma language model sampling strategy figure the process of character-by-character text generation using language model the importance of the sampling strategy when generating textthe way you choose the next character is crucially important naive approach is greedy samplingconsisting of always choosing the most likely next character but such an approach results in repetitivepredictable strings that don' look like coherent language more interesting approach makes slightly more surprising choicesit introduces randomness in the sampling processby sampling from the probability distribution for the next character this is called stochastic sampling (recall that stochasticity is what we call randomness in this fieldin such setupif has probability of being the next characteraccording to the modelyou'll choose it licensed to |
11,665 | text generation with lstm of the time note that greedy sampling can be also cast as sampling from probability distributionone where certain character has probability and all others have probability sampling probabilistically from the softmax output of the model is neatit allows even unlikely characters to be sampled some of the timegenerating more interestinglooking sentences and sometimes showing creativity by coming up with newrealisticsounding words that didn' occur in the training data but there' one issue with this strategyit doesn' offer way to control the amount of randomness in the sampling process why would you want more or less randomnessconsider an extreme casepure random samplingwhere you draw the next character from uniform probability distributionand every character is equally likely this scheme has maximum randomnessin other wordsthis probability distribution has maximum entropy naturallyit won' produce anything interesting at the other extremegreedy sampling doesn' produce anything interestingeitherand has no randomnessthe corresponding probability distribution has minimum entropy sampling from the "realprobability distribution--the distribution that is output by the model' softmax function--constitutes an intermediate point between these two extremes but there are many other intermediate points of higher or lower entropy that you may want to explore less entropy will give the generated sequences more predictable structure (and thus they will potentially be more realistic looking)whereas more entropy will result in more surprising and creative sequences when sampling from generative modelsit' always good to explore different amounts of randomness in the generation process because we--humans--are the ultimate judges of how interesting the generated data isinterestingness is highly subjectiveand there' no telling in advance where the point of optimal entropy lies in order to control the amount of stochasticity in the sampling processwe'll introduce parameter called the softmax temperature that characterizes the entropy of the probability distribution used for samplingit characterizes how surprising or predictable the choice of the next character will be given temperature valuea new probability distribution is computed from the original one (the softmax output of the modelby reweighting it in the following way listing reweight ing probability dist ribut ion different emperat ure import numpy as np def reweight_distribution(original_distributiontemperature= )distribution np log(original_distributiontemperature distribution np exp(distributionreturn distribution np sum(distributionoriginal_distribution is numpy array of probability values that must sum to temperature is factor quantifying the entropy of the output distribution licensed to returns reweighted version of the original distribution the sum of the distribution may no longer be so you divide it by its sum to obtain the new distribution |
11,666 | generative deep learning probability of sampling element higher temperatures result in sampling distributions of higher entropy that will generate more surprising and unstructured generated datawhereas lower temperature will result in less randomness and much more predictable generated data (see figure temperature temperature temperature temperature temperature discrete elements (characterstemperature figure different reweight ings of one probability dist ribut ion low temperature more deterministichigh emperat ure more random implementing character-level lstm text generation let' put these ideas into practice in keras implementation the first thing you need is lot of text data that you can use to learn language model you can use any sufficiently large text file or set of text files--wikipediathe lord of the ringsand so on in this exampleyou'll use some of the writings of nietzschethe late-nineteenth century german philosopher (translated into englishthe language model you'll learn will thus be specifically model of nietzsche' writing style and topics of choicerather than more generic model of the english language preparing the data let' start by downloading the corpus and converting it to lowercase listing downloading and parsing he init ial ext file import keras import numpy as np path keras utils get_file'nietzsche txt'origin='text open(pathread(lower(print('corpus length:'len(text)licensed to |
11,667 | text generation with lstm nextyou'll extract partially overlapping sequences of length maxlenone-hot encode themand pack them in numpy array of shape (sequencesmaxlenunique_characterssimultaneouslyyou'll prepare an array containing the corresponding targetsthe one-hot-encoded characters that come after each extracted sequence listing vect orizing sequences of charact ers you'll extract sequences of characters maxlen you'll sample new sequence every three characters step sentences [holds the extracted sequences next_chars [for in range( len(textmaxlenstep)sentences append(text[ii maxlen]next_chars append(text[ maxlen]holds the targets (the follow-up characterslist of unique characters in the corpus print('number of sequences:'len(sentences)chars sorted(list(set(text))print('unique characters:'len(chars)dictionary that maps unique characters to their index in the list charschar_indices dict((charchars index(char)for char in charsprint('vectorization ' np zeros((len(sentences)maxlenlen(chars))dtype=np booly np zeros((len(sentences)len(chars))dtype=np boolfor isentence in enumerate(sentences)for tchar in enumerate(sentence) [itchar_indices[char] one-hot encodes the characters into binary arrays [ichar_indices[next_chars[ ]] building the network this network is single lstm layer followed by dense classifier and softmax over all possible characters but note that recurrent neural networks aren' the only way to do sequence data generation convnets also have proven extremely successful at this task in recent times listing single-layer lstm model for next -charact er predict ion from keras import layers model keras models sequential(model add(layers lstm( input_shape=(maxlenlen(chars)))model add(layers dense(len(chars)activation='softmax')licensed to |
11,668 | generative deep learning because your targets are one-hot encodedyou'll use categorical_crossentropy as the loss to train the model listing model compilat ion configurat ion optimizer keras optimizers rmsprop(lr= model compile(loss='categorical_crossentropy'optimizer=optimizertraining the language model and sampling from it given trained model and seed text snippetyou can generate new text by doing the following repeatedly draw from the model probability distribution for the next charactergiven the generated text available so far reweight the distribution to certain temperature sample the next character at random according to the reweighted distribution add the new character at the end of the available text this is the code you use to reweight the original probability distribution coming out of the model and draw character index from it (the sampling functionlisting funct ion sample he next charact er given the model' predict ions def sample(predstemperature= )preds np asarray(predsastype('float 'preds np log(predstemperature exp_preds np exp(predspreds exp_preds np sum(exp_predsprobas np random multinomial( preds return np argmax(probasfinallythe following loop repeatedly trains and generates text you begin generating text using range of different temperatures after every epoch this allows you to see how the generated text evolves as the model begins to convergeas well as the impact of temperature in the sampling strategy listing import random import sys text -generation loop trains the model for epochs for epoch in range( )fits the model for one iteration print('epoch'epochon the data model fit(xybatch_size= epochs= selects text start_index random randint( len(textmaxlen seed at generated_text text[start_indexstart_index maxlenrandom print('--generating with seed"generated_text '"'for temperature in [ ]print(temperature:'temperaturesys stdout write(generated_textlicensed to tries range of different sampling temperatures |
11,669 | text generation with lstm generates charactersstarting from the seed text for in range( )sampled np zeros(( maxlenlen(chars))for tchar in enumerate(generated_text)sampled[ tchar_indices[char] preds model predict(sampledverbose= )[ next_index sample(predstemperaturenext_char chars[next_indexone-hot encodes the characters generated so far samples the next character generated_text +next_char generated_text generated_text[ :sys stdout write(next_charherewe used the random seed text "new facultyand the jubilation reached its climax when kant here' what you get at epoch long before the model has fully convergedwith temperature= new facultyand the jubilation reached its climax when kant and such man in the same time the spirit of the surely and the such the such as man is the sunligh and subject the present to the superiority of the special pain the most man and strange the subjection of the special conscience the special and nature and such men the subjection of the special menthe most surely the subjection of the special intellect of the subjection of the same things and here' the result with temperature= new facultyand the jubilation reached its climax when kant in the eterned and such man as it' also become himself the condition of the experience of off the basis the superiory and the special morty of the strengthin the langusas which the same time life and "even who discless the mankindwith subject and fact all you have to be the stand and lave no comes troveration of the man and surely the conscience the superiorityand when one must be and here' what you get with temperature= new facultyand the jubilation reached its climax when kantas periliting of manner to all definites and transpects it it so hicable and ont him artiar resull too such as if ever the proping to makes as cnecience to been judenall every could coldiciousnike hother aw passifethe plies like which might thiod was accountindifferent germinthat everythery certain destrutionintellect into the deteriorablen origin of moralianand lessority at epoch the model has mostly convergedand the text starts to look significantly more coherent here' the result with temperature= cheerfulnessfriendliness and kindness of heart are the sense of the spirit is man with the sense of the sense of the world of the self-end and self-concerning the subjection of the strengthorixes--the licensed to |
11,670 | generative deep learning subjection of the subjection of the subjection of the self-concerning the feelings in the superiority in the subjection of the subjection of the spirit isn' to be man of the sense of the subjection and said to the strength of the sense of the here' temperature= cheerfulnessfriendliness and kindness of heart are the part of the soul who have been the art of the philosophersand which the one won' saywhich is it the higher the and with religion of the frences the life of the spirit among the most continuess of the strengther of the sense the conscience of men of precisely before enough presumptionand can mankindand something the conceptionsthe subjection of the sense and suffering and the and here' temperature= cheerfulnessfriendliness and kindness of heart are spiritual by the ciuture for the entalled ishe astragedor errors to our you idstood--and it needsto think by spars to whole the amvives of the newoatlyprefectly raalsit was namefor example but voludd atu-especity"--or rank oneeor even all "solett increessic of the world and implussional tragedy experiencetransfor insiderar,--must hast if desires of the strubction is be stronges as you can seea low temperature value results in extremely repetitive and predictable textbut local structure is highly realisticin particularall words ( word being local pattern of charactersare real english words with higher temperaturesthe generated text becomes more interestingsurprisingeven creativeit sometimes invents completely new words that sound somewhat plausible (such as eterned and troverationwith high temperaturethe local structure starts to break downand most words look like semi-random strings of characters without doubt is the most interesting temperature for text generation in this specific setup always experiment with multiple sampling strategiesa clever balance between learned structure and randomness is what makes generation interesting note that by training bigger modellongeron more datayou can achieve generated samples that look much more coherent and realistic than this one butof coursedon' expect to ever generate any meaningful textother than by random chanceall you're doing is sampling data from statistical model of which characters come after which characters language is communication channeland there' distinction between what communications are about and the statistical structure of the messages in which communications are encoded to evidence this distinctionhere' thought experimentwhat if human language did better job of compressing communicationsmuch like computers do with most digital communicationslanguage would be no less meaningfulbut it would lack any intrinsic statistical structurethus making it impossible to learn language model as you just did licensed to |
11,671 | wrapping up you can generate discrete sequence data by training model to predict the next tokens( )given previous tokens in the case of textsuch model is called language model it can be based on either words or characters sampling the next token requires balance between adhering to what the model judges likelyand introducing randomness one way to handle this is the notion of softmax temperature always experiment with different temperatures to find the right one licensed to |
11,672 | generative deep learning deepdream deepdream is an artistic image-modification technique that uses the representations learned by convolutional neural networks it was first released by google in the summer of as an implementation written using the caffe deep-learning library (this was several months before the first public release of tensorflow it quickly became an internet sensation thanks to the trippy pictures it could generate (seefor examplefigure )full of algorithmic pareidolia artifactsbird feathersand dog eyes-- byproduct of the fact that the deepdream convnet was trained on imagenetwhere dog breeds and bird species are vastly overrepresented figure example of deepdream output image the deepdream algorithm is almost identical to the convnet filter-visualization technique introduced in consisting of running convnet in reversedoing gradient ascent on the input to the convnet in order to maximize the activation of specific filter in an upper layer of the convnet deepdream uses this same ideawith few simple differenceswith deepdreamyou try to maximize the activation of entire layers rather than that of specific filterthus mixing together visualizations of large numbers of features at once alexander mordvintsevchristopher olahand mike tyka"deepdreama code example for visualizing neural networks,google research blogjuly licensed to |
11,673 | deepdream you start not from blankslightly noisy inputbut rather from an existing image--thus the resulting effects latch on to preexisting visual patternsdistorting elements of the image in somewhat artistic fashion the input images are processed at different scales (called octaves)which improves the quality of the visualizations let' make some deepdreams implementing deepdream in keras you'll start from convnet pretrained on imagenet in kerasmany such convnets are availablevgg vgg xceptionresnet and so on you can implement deepdream with any of thembut your convnet of choice will naturally affect your visualizationsbecause different convnet architectures result in different learned features the convnet used in the original deepdream release was an inception modeland in practice inception is known to produce nice-looking deepdreamsso you'll use the inception model that comes with keras listing loading he pret rained incept ion model from keras applications import inception_v from keras import backend as set_learning_phase( you won' be training the modelso this command disables all trainingspecific operations model inception_v inceptionv (weights='imagenet'include_top=falsebuilds the inception networkwithout its convolutional base the model will be loaded with pretrained imagenet weights nextyou'll compute the lossthe quantity you'll seek to maximize during the gradient-ascent process in for filter visualizationyou tried to maximize the value of specific filter in specific layer hereyou'll simultaneously maximize the activation of all filters in number of layers specificallyyou'll maximize weighted sum of the norm of the activations of set of high-level layers the exact set of layers you choose (as well as their contribution to the final losshas major influence on the visuals you'll be able to produceso you want to make these parameters easily configurable lower layers result in geometric patternswhereas higher layers result in visuals in which you can recognize some classes from imagenet (for examplebirds or dogsyou'll start from somewhat arbitrary configuration involving four layers--but you'll definitely want to explore many different configurations later listing set ing up he deepdream configurat ion layer_contributions 'mixed ' 'mixed ' 'mixed ' 'mixed ' dictionary mapping layer names to coefficient quantifying how much the layer' activation contributes to the loss you'll seek to maximize note that the layer names are hardcoded in the built-in inception application you can list all layer names using model summary(licensed to |
11,674 | generative deep learning nowlet' define tensor that contains the lossthe weighted sum of the norm of the activations of the layers in listing listing defining he loss be maximized creates dictionary that maps layer names to layer instances layer_dict dict([(layer namelayerfor layer in model layers]loss variable( for layer_name in layer_contributionscoeff layer_contributions[layer_nameactivation layer_dict[layer_nameoutput you'll define the loss by adding layer contributions to this scalar variable scaling prod( cast( shape(activation)'float ')loss +coeff sum( square(activation[: - - :])scaling adds the norm of the features of layer to the loss you avoid border artifacts by only involving nonborder pixels in the loss retrieves the layer' output nextyou can set up the gradient-ascent process listing gradient -ascent process this tensor holds the generated imagethe dream computes the gradients of the dream with regard to the loss dream model input grads gradients(lossdream)[ grads / maximum( mean( abs(grads)) - normalizes the gradients (important trickoutputs [lossgradsfetch_loss_and_grads function([dream]outputsdef eval_loss_and_grads( )outs fetch_loss_and_grads([ ]loss_value outs[ grad_values outs[ return loss_valuegrad_values def gradient_ascent(xiterationsstepmax_loss=none)for in range(iterations)loss_valuegrad_values eval_loss_and_grads(xif max_loss is not none and loss_value max_lossbreak print(loss value at' ':'loss_valuex +step grad_values return sets up keras function to retrieve the value of the loss and gradientsgiven an input image this function runs gradient ascent for number of iterations finallythe actual deepdream algorithm firstyou define list of scales (also called octavesat which to process the images each successive scale is larger than the previous one by factor of (it' larger)you start by processing small image and then increasingly scale it up (see figure licensed to |
11,675 | deepdream detail reinjection detail reinjection dream upscale octave dream upscale dream octave octave figure the deepdream processsuccessive scales of spatial processing (octavesand det ail reinjection upon upscaling for each successive scalefrom the smallest to the largestyou run gradient ascent to maximize the loss you previously definedat that scale after each gradient ascent runyou upscale the resulting image by to avoid losing lot of image detail after each successive scale-up (resulting in increasingly blurry or pixelated images)you can use simple trickafter each scaleupyou'll reinject the lost details back into the imagewhich is possible because you know what the original image should look like at the larger scale given small image size and larger image size lyou can compute the difference between the original image resized to size and the original resized to size --this difference quantifies the details lost when going from to listing running gradient ascent over different successive scales playing with these hyperparameters will let you achieve new effects import numpy as np step num_octave octave_scale iterations gradient ascent step size number of scales at which to run gradient ascent size ratio between scales number of ascent steps to run at each scale if the loss grows larger than you'll interrupt the gradient-ascent process to avoid ugly artifacts max_loss base_image_path fill this with the path to the image you want to use img preprocess_image(base_image_pathlicensed to loads the base image into numpy array (function is defined in listing |
11,676 | generative deep learning original_shape img shape[ : successive_shapes [original_shapefor in range( num_octave)shape tuple([int(dim (octave_scale * )for dim in original_shape]successive_shapes append(shapesuccessive_shapes successive_shapes[::- scales up the dream image prepares list of shape tuples defining the different scales at which to run gradient ascent reverses the list of shapes so they're in increasing order original_img np copy(imgshrunk_original_img resize_img(imgsuccessive_shapes[ ]resizes the numpy for shape in successive_shapesarray of the image print('processing image shape'shapeto the smallest scale img resize_img(imgshapeimg gradient_ascent(imgscales up the smaller iterations=iterationsruns gradient version of the original step=stepascentaltering imageit will be pixellated max_loss=max_lossthe dream upscaled_shrunk_original_img resize_img(shrunk_original_imgshapesame_size_original resize_img(original_imgshapelost_detail same_size_original upscaled_shrunk_original_img img +lost_detail shrunk_original_img resize_img(original_imgshapesave_img(imgfname='dream_at_scale_str(shapepng'save_img(imgfname='final_dream png'reinjects lost detail into the dream computes the high-quality version of the original image at this size the difference between the two is the detail that was lost when scaling up note that this code uses the following straightforward auxiliary numpy functionswhich all do as their names suggest they require that you have scipy installed listing auxiliary funct ions import scipy from keras preprocessing import image def resize_img(imgsize)img np copy(imgfactors ( float(size[ ]img shape[ ]float(size[ ]img shape[ ] return scipy ndimage zoom(imgfactorsorder= def save_img(imgfname)pil_img deprocess_image(np copy(img)scipy misc imsave(fnamepil_imgdef preprocess_image(image_path)img image load_img(image_pathimg image img_to_array(imglicensed to util function to openresizeand format pictures into tensors that inception can process |
11,677 | deepdream img np expand_dims(imgaxis= img inception_v preprocess_input(imgreturn img def deprocess_image( )if image_data_format(='channels_first' reshape(( shape[ ] shape[ ]) transpose(( )elsex reshape(( shape[ ] shape[ ] ) / + * np clip( astype('uint 'return util function to convert tensor into valid image undoes preprocessing that was performed by inception_v preprocess_ input because the original inception network was trained to recognize concepts in images of size and given that the process involves scaling the images down by reasonable factorthe deepdream implementation produces much better results on images that are somewhere between and regardlessyou can run the same code on images of any size and any ratio note starting from photograph taken in the small hills between san francisco bay and the google campuswe obtained the deepdream shown in figure figure running he deepdream code on an example image we strongly suggest that you explore what you can do by adjusting which layers you use in your loss layers that are lower in the network contain more-localless-abstract representations and lead to dream patterns that look more geometric layers that are higher up lead to more-recognizable visual patterns based on the most common objects found in imagenetsuch as dog eyesbird feathersand so on you can use licensed to |
11,678 | generative deep learning random generation of the parameters in the layer_contributions dictionary to quickly explore many different layer combinations figure shows range of results obtained using different layer configurationsfrom an image of delicious homemade pastry figure trying range of deepdream configurat ions on an example image wrapping up deepdream consists of running convnet in reverse to generate inputs based on the representations learned by the network the results produced are fun and somewhat similar to the visual artifacts induced in humans by the disruption of the visual cortex via psychedelics note that the process isn' specific to image models or even to convnets it can be done for speechmusicand more licensed to |
11,679 | neural style transfer neural style transfer in addition to deepdreamanother major development in deep-learning-driven image modification is neural style transferintroduced by leon gatys et al in the summer of the neural style transfer algorithm has undergone many refinements and spawned many variations since its original introductionand it has made its way into many smartphone photo apps for simplicitythis section focuses on the formulation described in the original paper neural style transfer consists of applying the style of reference image to target image while conserving the content of the target image figure shows an example content target figure style reference combination image st yle ransfer example in this contextstyle essentially means texturescolorsand visual patterns in the imageat various spatial scalesand the content is the higher-level macrostructure of the image for instanceblue-and-yellow circular brushstrokes are considered to be the style in figure (using starry night by vincent van gogh)and the buildings in the tubingen photograph are considered to be the content the idea of style transferwhich is tightly related to that of texture generationhas had long history in the image-processing community prior to the development of neural style transfer in but as it turns outthe deep-learning-based implementations of style transfer offer results unparalleled by what had been previously achieved with classical computer-vision techniquesand they triggered an amazing renaissance in creative applications of computer vision the key notion behind implementing style transfer is the same idea that' central to all deep-learning algorithmsyou define loss function to specify what you want to achieveand you minimize this loss you know what you want to achieveconserving the content of the original image while adopting the style of the reference image if we were able to mathematically define content and stylethen an appropriate loss function to minimize would be the followingloss distance(style(reference_imagestyle(generated_image)distance(content(original_imagecontent(generated_image) leon gatysalexander eckerand matthias bethge" neural algorithm of artistic style,arxiv ( )licensed to |
11,680 | generative deep learning heredistance is norm function such as the normcontent is function that takes an image and computes representation of its contentand style is function that takes an image and computes representation of its style minimizing this loss causes style(generated_imageto be close to style(reference_image)and content(generated_imageis close to content(generated_image)thus achieving style transfer as we defined it fundamental observation made by gatys et al was that deep convolutional neural networks offer way to mathematically define the style and content functions let' see how the content loss as you already knowactivations from earlier layers in network contain local information about the imagewhereas activations from higher layers contain increasingly globalabstract information formulated in different waythe activations of the different layers of convnet provide decomposition of the contents of an image over different spatial scales thereforeyou' expect the content of an imagewhich is more global and abstractto be captured by the representations of the upper layers in convnet good candidate for content loss is thus the norm between the activations of an upper layer in pretrained convnetcomputed over the target imageand the activations of the same layer computed over the generated image this guarantees thatas seen from the upper layerthe generated image will look similar to the original target image assuming that what the upper layers of convnet see is really the content of their input imagesthen this works as way to preserve image content the style loss the content loss only uses single upper layerbut the style loss as defined by gatys et al uses multiple layers of convnetyou try to capture the appearance of the stylereference image at all spatial scales extracted by the convnetnot just single scale for the style lossgatys et al use the gram matrix of layer' activationsthe inner product of the feature maps of given layer this inner product can be understood as representing map of the correlations between the layer' features these feature correlations capture the statistics of the patterns of particular spatial scalewhich empirically correspond to the appearance of the textures found at this scale hencethe style loss aims to preserve similar internal correlations within the activations of different layersacross the style-reference image and the generated image in turnthis guarantees that the textures found at different spatial scales look similar across the style-reference image and the generated image in shortyou can use pretrained convnet to define loss that will do the followingpreserve content by maintaining similar high-level layer activations between the target content image and the generated image the convnet should "seeboth the target image and the generated image as containing the same things licensed to |
11,681 | neural style transfer preserve style by maintaining similar correlations within activations for both lowlevel layers and high-level layers feature correlations capture textures the generated image and the style-reference image should share the same textures at different spatial scales nowlet' look at keras implementation of the original neural style transfer algorithm as you'll seeit shares many similarities with the deepdream implementation developed in the previous section neural style transfer in keras neural style transfer can be implemented using any pretrained convnet hereyou'll use the vgg network used by gatys et al vgg is simple variant of the vgg network introduced in with three more convolutional layers this is the general process set up network that computes vgg layer activations for the style-reference imagethe target imageand the generated image at the same time use the layer activations computed over these three images to define the loss function described earlierwhich you'll minimize in order to achieve style transfer set up gradient-descent process to minimize this loss function let' start by defining the paths to the style-reference image and the target image to make sure that the processed images are similar size (widely different sizes make style transfer more difficult)you'll later resize them all to shared height of px listing defining initial variables from keras preprocessing image import load_imgimg_to_array target_image_path 'img/portrait jpgstyle_reference_image_path 'img/transfer_style_reference jpgwidthheight load_img(target_image_pathsize img_height img_width int(width img_height heightpath to the image you want to transform path to the style image dimensions of the generated picture you need some auxiliary functions for loadingpreprocessingand postprocessing the images that go in and out of the vgg convnet listing auxiliary funct ions import numpy as np from keras applications import vgg def preprocess_image(image_path)img load_img(image_pathtarget_size=(img_heightimg_width)img img_to_array(imgimg np expand_dims(imgaxis= img vgg preprocess_input(imgreturn img licensed to |
11,682 | generative deep learning def deprocess_image( ) [:: + zero-centering by removing the mean pixel value [:: + from imagenet this reverses transformation done by vgg preprocess_input [:: + [::::- np clip( astype('uint 'converts images from 'bgrto 'rgbthis is also part of the reversal of return vgg preprocess_input let' set up the vgg network it takes as input batch of three imagesthe stylereference imagethe target imageand placeholder that will contain the generated image placeholder is symbolic tensorthe values of which are provided externally via numpy arrays the style-reference and target image are static and thus defined using constantwhereas the values contained in the placeholder of the generated image will change over time listing loading he pret rained vgg net work and applying it he hree images placeholder that will contain the generated image from keras import backend as target_image constant(preprocess_image(target_image_path)style_reference_image constant(preprocess_image(style_reference_image_path)combination_image placeholder(( img_heightimg_width )input_tensor concatenate([target_imagestyle_reference_imagecombination_image]axis= model vgg vgg (input_tensor=input_tensorweights='imagenet'include_top=falseprint('model loaded 'combines the three images in single batch builds the vgg network with the batch of three images as input the model will be loaded with pretrained imagenet weights let' define the content losswhich will make sure the top layer of the vgg convnet has similar view of the target image and the generated image listing cont ent loss def content_loss(basecombination)return sum( square(combination base)next is the style loss it uses an auxiliary function to compute the gram matrix of an input matrixa map of the correlations found in the original feature matrix listing st yle loss def gram_matrix( )features batch_flatten( permute_dimensions( ( ))gram dot(featuresk transpose(features)return gram licensed to |
11,683 | def style_loss(stylecombination) gram_matrix(stylec gram_matrix(combinationchannels size img_height img_width return sum( square( )( (channels * (size * )to these two loss componentsyou add thirdthe total variation losswhich operates on the pixels of the generated combination image it encourages spatial continuity in the generated imagethus avoiding overly pixelated results you can interpret it as regularization loss listing tot al variation loss def total_variation_loss( ) squarex[::img_height :img_width : [: ::img_width :] squarex[::img_height :img_width : [::img_height ::]return sum( pow( )the loss that you minimize is weighted average of these three losses to compute the content lossyou use only one upper layer--the block _conv layer--whereas for the style lossyou use list of layers than spans both low-level and high-level layers you add the total variation loss at the end depending on the style-reference image and content image you're usingyou'll likely want to tune the content_weight coefficient (the contribution of the content loss to the total lossa higher content_weight means the target content will be more recognizable in the generated image listing defining he final loss hat you'll minimize dictionary that maps layer names to activation tensors outputs_dict dict([(layer namelayer outputfor layer in model layers]content_layer 'block _conv style_layers ['block _conv 'layer used for content loss 'block _conv ''block _conv 'layers used for style loss 'block _conv ''block _conv 'total_variation_weight - weights in the weighted average style_weight of the loss components content_weight licensed to |
11,684 | adds the content loss adds the total variation loss generative deep learning loss variable( you'll define the loss by layer_features outputs_dict[content_layeradding all components to target_image_features layer_features[ :::this scalar variable combination_features layer_features[ :::loss +content_weight content_loss(target_image_featurescombination_featuresfor layer_name in style_layersadds style loss layer_features outputs_dict[layer_namecomponent for style_reference_features layer_features[ :::each target layer combination_features layer_features[ :::sl style_loss(style_reference_featurescombination_featuresloss +(style_weight len(style_layers)sl loss +total_variation_weight total_variation_loss(combination_imagefinallyyou'll set up the gradient-descent process in the original gatys et al paperoptimization is performed using the -bfgs algorithmso that' what you'll use here this is key difference from the deepdream example in section the -bfgs algorithm comes packaged with scipybut there are two slight limitations with the scipy implementationit requires that you pass the value of the loss function and the value of the gradients as two separate functions it can only be applied to flat vectorswhereas you have image array it would be inefficient to compute the value of the loss function and the value of the gradients independentlybecause doing so would lead to lot of redundant computation between the twothe process would be almost twice as slow as computing them jointly to bypass thisyou'll set up python class named evaluator that computes both the loss value and the gradients value at oncereturns the loss value when called the first timeand caches the gradients for the next call listing gets the gradients of the generated image with regard to the loss set ing up the gradient -descent process grads gradients(losscombination_image)[ fetch_loss_and_grads function([combination_image][lossgrads]class evaluator(object)def __init__(self)self loss_value none self grads_values none def loss(selfx)assert self loss_value is none reshape(( img_heightimg_width )outs fetch_loss_and_grads([ ]this class wraps fetch_loss_and_grads in way that lets you retrieve the losses and gradients via two separate method callswhich is required by the scipy optimizer you'll use licensed to function to fetch the values of the current loss and the current gradients |
11,685 | neural style transfer loss_value outs[ grad_values outs[ flatten(astype('float 'self loss_value loss_value self grad_values grad_values return self loss_value def grads(selfx)assert self loss_value is not none grad_values np copy(self grad_valuesself loss_value none self grad_values none return grad_values evaluator evaluator(finallyyou can run the gradient-ascent process using scipy' -bfgs algorithmsaving the current generated image at each iteration of the algorithm (herea single iteration represents steps of gradient ascentlisting st yle- ransfer loop from scipy optimize import fmin_l_bfgs_b from scipy misc import imsave import time result_prefix 'my_resultiterations this is the initial statethe target image you flatten the image because scipy optimize fmin_l_bfgs_b can only process flat vectors preprocess_image(target_image_pathruns -bfgsoptimization flatten(over the pixels of the for in range(iterations)generated image to print('start of iteration'iminimize the neural style start_time time time(loss note that you have xmin_valinfo fmin_l_bfgs_b(evaluator lossto pass the function that xcomputes the loss and the fprime=evaluator gradsfunction that computes maxfun= the gradients as two print('current loss value:'min_valseparate arguments img copy(reshape((img_heightimg_width )img deprocess_image(imgfname result_prefix '_at_iteration_% pngi saves the current imsave(fnameimggenerated image print('image saved as'fnameend_time time time(print('iteration % completed in %ds(iend_time start_time)figure shows what you get keep in mind that what this technique achieves is merely form of image retexturingor texture transfer it works best with stylereference images that are strongly textured and highly self-similarand with content targets that don' require high levels of detail in order to be recognizable it typically can' achieve fairly abstract feats such as transferring the style of one portrait to another the algorithm is closer to classical signal processing than to aiso don' expect it to work like magiclicensed to |
11,686 | generative deep learning figure some example results licensed to |
11,687 | additionallynote that running this style-transfer algorithm is slow but the transformation operated by the setup is simple enough that it can be learned by smallfast feedforward convnet as well--as long as you have appropriate training data available fast style transfer can thus be achieved by first spending lot of compute cycles to generate input-output training examples for fixed style-reference imageusing the method outlined hereand then training simple convnet to learn this style-specific transformation once that' donestylizing given image is instantaneousit' just forward pass of this small convnet wrapping up style transfer consists of creating new image that preserves the contents of target image while also capturing the style of reference image content can be captured by the high-level activations of convnet style can be captured by the internal correlations of the activations of different layers of convnet hencedeep learning allows style transfer to be formulated as an optimization process using loss defined with pretrained convnet starting from this basic ideamany variants and refinements are possible licensed to |
11,688 | generative deep learning generating images with variational autoencoders sampling from latent space of images to create entirely new images or edit existing ones is currently the most popular and successful application of creative ai in this section and the nextwe'll review some high-level concepts pertaining to image generationalongside implementations details relative to the two main techniques in this domainvariational autoencoders (vaesand generative adversarial networks (gansthe techniques we present here aren' specific to images--you could develop latent spaces of soundmusicor even textusing gans and vaes--but in practicethe most interesting results have been obtained with picturesand that' what we focus on here sampling from latent spaces of images the key idea of image generation is to develop low-dimensional latent space of representations (which naturally is vector spacewhere any point can be mapped to realistic-looking image the module capable of realizing this mappingtaking as input latent point and outputting an image ( grid of pixels)is called generator (in the case of gansor decoder (in the case of vaesonce such latent space has been developedyou can sample points from iteither deliberately or at randomandby mapping them to image spacegenerate images that have never been seen before (see figure training data learning process generator decoder latent space of images ( vector spacefigure artificial image vector from the latent space learning lat ent vector space of imagesand using it sample new images gans and vaes are two different strategies for learning such latent spaces of image representationseach with its own characteristics vaes are great for learning latent spaces that are well structuredwhere specific directions encode meaningful axis of variation in the data gans generate images that can potentially be highly realisticbut the latent space they come from may not have as much structure and continuity licensed to |
11,689 | figure cont inuous space of faces generat ed by tom whit using vaes concept vectors for image editing we already hinted at the idea of concept vector when we covered word embeddings in the idea is still the samegiven latent space of representationsor an embedding spacecertain directions in the space may encode interesting axes of variation in the original data in latent space of images of facesfor instancethere may be smile vector ssuch that if latent point is the embedded representation of certain facethen latent point is the embedded representation of the same facesmiling once you've identified such vectorit then becomes possible to edit images by projecting them into the latent spacemoving their representation in meaningful wayand then decoding them back to image space there are concept vectors for essentially any independent dimension of variation in image space--in the case of facesyou may discover vectors for adding sunglasses to faceremoving glassesturning male face into as female faceand so on figure is an example of smile vectora concept vector discovered by tom white from the victoria university school of design in new zealandusing vaes trained on dataset of faces of celebrities (the celeba datasetlicensed to |
11,690 | figure generative deep learning the smile vect or variational autoencoders variational autoencoderssimultaneously discovered by kingma and welling in december and rezendemohamedand wierstra in january , are kind of generative model that' especially appropriate for the task of image editing via concept vectors they're modern take on autoencoders-- type of network that aims to encode an input to low-dimensional latent space and then decode it back--that mixes ideas from deep learning with bayesian inference classical image autoencoder takes an imagemaps it to latent vector space via an encoder moduleand then decodes it back to an output with the same dimensions as the original imagevia decoder module (see figure it' then trained by using as target data the same images as the input imagesmeaning the autoencoder learns to reconstruct the original inputs by imposing various constraints on the code (the output of the encoder)you can get the autoencoder to learn more-or-less interesting latent representations of the data most commonlyyou'll constrain the code to be low-dimensional and sparse (mostly zeros)in which case the encoder acts as way to compress the input data into fewer bits of information diederik kingma and max welling"auto-encoding variational bayesarxiv ( )abs/ danilo jimenez rezendeshakir mohamedand daan wierstra"stochastic backpropagation and approximate inference in deep generative models,arxiv ( )licensed to |
11,691 | generating images with variational autoencoders encoder original input decoder compressed representation reconstructed input figure an autoencodermapping an input compressed represent ation and then decoding it back as xin practicesuch classical autoencoders don' lead to particularly useful or nicely structured latent spaces they're not much good at compressioneither for these reasonsthey have largely fallen out of fashion vaeshoweveraugment autoencoders with little bit of statistical magic that forces them to learn continuoushighly structured latent spaces they have turned out to be powerful tool for image generation vaeinstead of compressing its input image into fixed code in the latent spaceturns the image into the parameters of statistical distributiona mean and variance essentiallythis means you're assuming the input image has been generated by statistical processand that the randomness of this process should be taken into accounting during encoding and decoding the vae then uses the mean and variance parameters to randomly sample one element of the distributionand decodes that element back to the original input (see figure the stochasticity of this process improves robustness and forces the latent space to encode meaningful representations everywhereevery point sampled in the latent space is decoded to valid output distribution over latent space defined by z_mean and z_log_var input image encoder reconstructed image decoder point randomly sampled from the distribution figure vae maps an image to wo vect orsz_mean and z_log_sigmawhich define probability distribut ion over the latent spaceused to sample lat ent point to decode licensed to |
11,692 | generative deep learning in technical termshere' how vae works an encoder module turns the input samples input_img into two parameters in latent space of representationsz_mean and z_log_variance you randomly sample point from the latent normal distribution that' assumed to generate the input imagevia z_mean exp(z_log_varianceepsilonwhere epsilon is random tensor of small values decoder module maps this point in the latent space back to the original input image because epsilon is randomthe process ensures that every point that' close to the latent location where you encoded input_img ( -meancan be decoded to something similar to input_imgthus forcing the latent space to be continuously meaningful any two close points in the latent space will decode to highly similar images continuitycombined with the low dimensionality of the latent spaceforces every direction in the latent space to encode meaningful axis of variation of the datamaking the latent space very structured and thus highly suitable to manipulation via concept vectors the parameters of vae are trained via two loss functionsa reconstruction loss that forces the decoded samples to match the initial inputsand regularization loss that helps learn well-formed latent spaces and reduce overfitting to the training data let' quickly go over keras implementation of vae schematicallyit looks like thisz_meanz_log_variance encoder(input_imgencodes the input into mean and variance parameter z_mean exp(z_log_varianceepsilon decodes back to an image draws latent point using small random epsilon reconstructed_img decoder(zmodel model(input_imgreconstructed_imginstantiates the autoencoder modelwhich maps an input image to its reconstruction you can then train the model using the reconstruction loss and the regularization loss the following listing shows the encoder network you'll usemapping images to the parameters of probability distribution over the latent space it' simple convnet that maps the input image to two vectorsz_mean and z_log_var listing vae encoder net work import keras from keras import layers from keras import backend as from keras models import model import numpy as np img_shape ( batch_size latent_dim dimensionality of the latent spacea plane input_img keras input(shape=img_shapelicensed to |
11,693 | generating images with variational autoencoders layers conv ( padding='same'activation='relu')(input_imgx layers conv ( padding='same'activation='relu'strides=( ))(xx layers conv ( padding='same'activation='relu')(xx layers conv ( padding='same'activation='relu')(xshape_before_flattening int_shape(xx layers flatten()(xx layers dense( activation='relu')(xz_mean layers dense(latent_dim)(xz_log_var layers dense(latent_dim)(xthe input image ends up being encoded into these two parameters next is the code for using z_mean and z_log_varthe parameters of the statistical distribution assumed to have produced input_imgto generate latent space point hereyou wrap some arbitrary code (built on top of keras backend primitivesinto lambda layer in keraseverything needs to be layerso code that isn' part of builtin layer should be wrapped in lambda (or in custom layerlisting lat ent -space-sampling funct ion def sampling(args)z_meanz_log_var args epsilon random_normal(shape=( shape(z_mean)[ ]latent_dim)mean= stddev= return z_mean exp(z_log_varepsilon layers lambda(sampling)([z_meanz_log_var]the following listing shows the decoder implementation you reshape the vector to the dimensions of an image and then use few convolution layers to obtain final image output that has the same dimensions as the original input_img listing vae decoder net workmapping lat ent space point images decoder_input layers input( int_shape( )[ :]input where you'll feed layers dense(np prod(shape_before_flattening[ :])activation='relu')(decoder_inputupsamples the input layers reshape(shape_before_flattening[ :])(xx layers conv dtranspose( padding='same'activation='relu'strides=( ))(xx layers conv ( padding='same'activation='sigmoid')(xreshapes into feature map of the same shape as the feature map just before the last flatten layer in the encoder model licensed to uses conv dtranspose layer and conv layer to decode into feature map the same size as the original image input |
11,694 | generative deep learning decoder model(decoder_inputxz_decoded decoder(zapplies it to to recover the decoded instantiates the decoder modelwhich turns decoder_inputinto the decoded image the dual loss of vae doesn' fit the traditional expectation of sample-wise function of the form loss(inputtargetthusyou'll set up the loss by writing custom layer that internally uses the built-in add_loss layer method to create an arbitrary loss listing cust om layer used comput he vae loss class customvariationallayer(keras layers layer)def vae_loss(selfxz_decoded) flatten(xz_decoded flatten(z_decodedxent_loss keras metrics binary_crossentropy(xz_decodedkl_loss - - mean z_log_var square(z_meank exp(z_log_var)axis=- return mean(xent_loss kl_lossyou don' use this outputbut the layer must return something def call(selfinputs)you implement custom layers inputs[ by writing call method z_decoded inputs[ loss self vae_loss(xz_decodedcalls the custom layer on self add_loss(lossinputs=inputsthe input and the return customvariationallayer()([input_imgz_decoded]decoded output to obtain the final model output finallyyou're ready to instantiate and train the model because the loss is taken care of in the custom layeryou don' specify an external loss at compile time (loss=none)which in turn means you won' pass target data during training (as you can seeyou only pass x_train to the model in fitlisting training he vae from keras datasets import mnist vae model(input_imgyvae compile(optimizer='rmsprop'loss=nonevae summary((x_train_)(x_testy_testmnist load_data(x_train x_train astype('float ' x_train x_train reshape(x_train shape ( ,)x_test x_test astype('float ' x_test x_test reshape(x_test shape ( ,)vae fit( =x_trainy=noneshuffle=trueepochs= batch_size=batch_sizevalidation_data=(x_testnone)licensed to |
11,695 | generating images with variational autoencoders once such model is trained--on mnistin this case--you can use the decoder network to turn arbitrary latent space vectors into images listing sampling grid of points from the latent space and decoding them to images import matplotlib pyplot as plt from scipy stats import norm you'll display grid of digits ( digits totaln transforms linearly spaced digit_size coordinates using the scipy ppf figure np zeros((digit_size ndigit_size )function to produce values of the grid_x norm ppf(np linspace( )latent variable (because the prior grid_y norm ppf(np linspace( )of the latent space is gaussianfor iyi in enumerate(grid_x)repeats multiple times to for jxi in enumerate(grid_y)form complete batch z_sample np array([[xiyi]]z_sample np tile(z_samplebatch_sizereshape(batch_size x_decoded decoder predict(z_samplebatch_size=batch_sizedigit x_decoded[ reshape(digit_sizedigit_sizefigure[ digit_size( digit_sizej digit_size( digit_sizedigit plt figure(figsize=( )plt imshow(figurecmap='greys_r'plt show(reshapes the first digit in the batch from to decodes the batch into digit images the grid of sampled digits (see figure shows completely continuous distribution of the different digit classeswith one digit morphing into another as you follow path through latent space specific directions in this space have meaningfor examplethere' direction for "four-ness,"one-ness,and so on in the next sectionwe'll cover in detail the other major tool for generating artificial imagesgenerative adversarial networks (gansfigure space licensed to grid of digit decoded from he latent |
11,696 | generative deep learning wrapping up image generation with deep learning is done by learning latent spaces that capture statistical information about dataset of images by sampling and decoding points from the latent spaceyou can generate never-before-seen images there are two major tools to do thisvaes and gans vaes result in highly structuredcontinuous latent representations for this reasonthey work well for doing all sorts of image editing in latent spaceface swappingturning frowning face into smiling faceand so on they also work nicely for doing latent-space-based animationssuch as animating walk along cross section of the latent spaceshowing starting image slowly morphing into different images in continuous way gans enable the generation of realistic single-frame images but may not induce latent spaces with solid structure and high continuity most successful practical applications have seen with images rely on vaesbut gans are extremely popular in the world of academic research--at leastcirca - you'll find out how they work and how to implement one in the next section to play further with image generationi suggest working with the largescale celeb faces attributes (celebadataset it' free-to-download image dataset containing more than , celebrity portraits it' great for experimenting with concept vectors in particular--it definitely beats mnist tip licensed to |
11,697 | introduction to generative adversarial networks generative adversarial networks (gans)introduced in by goodfellow et al , are an alternative to vaes for learning latent spaces of images they enable the generation of fairly realistic synthetic images by forcing the generated images to be statistically almost indistinguishable from real ones an intuitive way to understand gans is to imagine forger trying to create fake picasso painting at firstthe forger is pretty bad at the task he mixes some of his fakes with authentic picassos and shows them all to an art dealer the art dealer makes an authenticity assessment for each painting and gives the forger feedback about what makes picasso look like picasso the forger goes back to his studio to prepare some new fakes as times goes onthe forger becomes increasingly competent at imitating the style of picassoand the art dealer becomes increasingly expert at spotting fakes in the endthey have on their hands some excellent fake picassos that' what gan isa forger network and an expert networkeach being trained to best the other as sucha gan is made of two partsgenerator network--takes as input random vector ( random point in the latent space)and decodes it into synthetic image discriminator network (or adversary)--takes as input an image (real or synthetic)and predicts whether the image came from the training set or was created by the generator network the generator network is trained to be able to fool the discriminator networkand thus it evolves toward generating increasingly realistic images as training goes onartificial images that look indistinguishable from real onesto the extent that it' impossible for the discriminator network to tell the two apart (see figure meanwhilethe discriminator is constantly adapting to the gradually improving capabilities of the generatorsetting high bar of realism for the generated images once training is overthe generator is capable of turning any point in its input space into believable image unlike vaesthis latent space has fewer explicit guarantees of meaningful structurein particularit isn' continuous ian goodfellow et al "generative adversarial networks,arxiv ( )licensed to |
11,698 | generative deep learning random vector from the latent space generated (decodedimage generator (decoderdiscriminator training feedback "real,"fakemix of real and fake images figure generat or ransforms random lat ent vect ors int imagesand discriminator seeks to ell real images from generated ones the generat or is trained fool he discriminat or remarkablya gan is system where the optimization minimum isn' fixedunlike in any other training setup you've encountered in this book normallygradient descent consists of rolling down hills in static loss landscape but with ganevery step taken down the hill changes the entire landscape little it' dynamic system where the optimization process is seeking not minimumbut an equilibrium between two forces for this reasongans are notoriously difficult to train--getting gan to work requires lots of careful tuning of the model architecture and training parameters figure lat ent space dwellers images generat ed by mike tyka using multistaged gan trained on dat aset of faces (www miket yka comlicensed to |
11,699 | schematic gan implementation in this sectionwe'll explain how to implement gan in kerasin its barest form-because gans are advanceddiving deeply into the technical details would be out of scope for this book the specific implementation is deep convolutional gan (dcgan) gan where the generator and discriminator are deep convnets in particularit uses conv dtranspose layer for image upsampling in the generator you'll train the gan on images from cifar dataset of , rgb images belonging to classes ( , images per classto make things easieryou'll only use images belonging to the class "frog schematicallythe gan looks like this generator network maps vectors of shape (latent_dim,to images of shape ( discriminator network maps images of shape ( to binary score estimating the probability that the image is real gan network chains the generator and the discriminator togethergan(xdiscriminator(generator( )thus this gan network maps latent space vectors to the discriminator' assessment of the realism of these latent vectors as decoded by the generator you train the discriminator using examples of real and fake images along with "real"/"fakelabelsjust as you train any regular image-classification model to train the generatoryou use the gradients of the generator' weights with regard to the loss of the gan model this meansat every stepyou move the weights of the generator in direction that makes the discriminator more likely to classify as "realthe images decoded by the generator in other wordsyou train the generator to fool the discriminator bag of tricks the process of training gans and tuning gan implementations is notoriously difficult there are number of known tricks you should keep in mind like most things in deep learningit' more alchemy than sciencethese tricks are heuristicsnot theory-backed guidelines they're supported by level of intuitive understanding of the phenomenon at handand they're known to work well empiricallyalthough not necessarily in every context here are few of the tricks used in the implementation of the gan generator and discriminator in this section it isn' an exhaustive list of gan-related tipsyou'll find many more across the gan literaturewe use tanh as the last activation in the generatorinstead of sigmoidwhich is more commonly found in other types of models we sample points from the latent space using normal distribution (gaussian distribution)not uniform distribution licensed to |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.