text stringlengths 20 3.06k |
|---|
Jason Brownlee Deep Learning With Python Develop Deep Learning Models On Theano And Tensor Flow Using Keras |
i Deep Learning With Python Copyright 2016 Jason Brownlee. All Rights Reserved. Edition: v1. 7 |
Contents Prefaceiii I Introduction11 Welcome21. 1 Deep Learning The Wrong Way........................... 21. 2 Deep Learning With Python............................. 31. 3 Book Organization..................................31. 4 Requirements For This Book............................. 61. 5 Your Outcomes From Reading Th... |
iii4. 4 Build Deep Learning Models with Keras......................214. 5 Summary....................................... 225 Project: Develop Large Models on GPUs Cheaply In the Cloud235. 1 Project Overview................................... 235. 2 Setup Your AWS Account..............................245. 3 Launch Your ... |
iv10 Project: Multiclass Classification Of Flower Species6210. 1 Iris Flowers Classification Dataset..........................6210. 2 Import Classes and Functions............................6310. 3 Initialize Random Number Generator........................6310. 4 Load The Dataset................................... 6410. ... |
v16 Reduce Overfitting With Dropout Regularization10216. 1 Dropout Regularization For Neural Networks....................10216. 2 Dropout Regularization in Keras..........................10316. 3 Using Dropout on the Visible Layer......................... 10416. 4 Using Dropout on Hidden Layers............................. |
vi20. 10Summary....................................... 14721 Project Object Recognition in Photographs14821. 1 Photograph Object Recognition Dataset......................14821. 2 Loading The CIFAR-10 Dataset in Keras......................14921. 3 Simple CNN for CIFAR-10..............................15021. 4 Larger CNN ... |
vii27 Understanding Stateful LSTM Recurrent Neural Networks20927. 1 Problem Description: Learn the Alphabet..................... 20927. 2 LSTM for Learning One-Char to One-Char Mapping............... 21127. 3 LSTM for a Feature Window to One-Char Mapping................21427. 4 LSTM for a Time Step Window to One-Char M... |
Preface Deep learning is a fascinating field. Artificial neural networks have been around for a long time,but something special has happened in recent years. The mixture of new faster hardware, newtechniques and highly optimized open source libraries allow very large networks to be createdwith frightening ease. This new ... |
Part IIntroduction 1 |
Chapter 1Welcome Welcome to Deep Learning With Python. This book is your guide to deep learning in Python. You will discover the Keras Python library for deep learning and how to use it to develop andevaluate deep learning models. In this book you will discover the techniques, recipes and skillsin deep learning that yo... |
1. 2. Deep Learning With Python31. 2 Deep Learning With Python The approach taken with this book and with all of Machine Learning Mastery is to flip thetraditional approach. If you are interested in deep learning, start by developing and evaluatingdeep learning models. Then if you discover you really like it or have a k... |
1. 3. Book Organization4 Convolutional Neural Networks. Recurrent Neural Networks. 1. 3. 2 Part 2: Background In this part you will learn about the Theano, Tensor Flow and Keras libraries that lay thefoundation for your deep learning journey and about how you can leverage very cheap Amazon Web Service computing in orde... |
1. 3. Book Organization51. 3. 4 Part 4: Advanced Multilayer Perceptrons In this part you will learn about some of the more finer points of the Keras library and API forpractical machine learning projects and some of the more important developments in appliedneural networks that you need to know in order to deliver world... |
1. 4. Requirements For This Book61. 3. 6 Part 6: Recurrent Neural Networks In this part you will receive a crash course in the dominant model for data with a sequence ortime component and how you can best exploit the capabilities of the Keras API for your ownprojects. This part of the book includes the following lesson... |
1. 5. Your Outcomes From Reading This Book7environment available. This may be on your workstation or laptop, it may be in a VM or a Docker instance that you run, or it may be a server instance that you can configure in the cloudas taught in Part II of this book. Technical Requirements: The technical requirements for the... |
1. 6. What This Book is Not8 How to develop and evaluate neural network models end-to-end. How to use more advanced techniques required for developing state-of-the-art deep learningmodels. How to build larger models for image and text data. How to use advanced image augmentation techniques in order to lift model perfor... |
1. 7. Summary91. 7 Summary It is a special time right now. The tools for applied deep learning have never been so good. The pace of change with neural networks and deep learning feels like it has never been so fast,spurred by the amazing results that the methods are showing in such a broad range of fields. This is the s... |
Part IIBackground 10 |
Chapter 2Introduction to Theano Theano is a Python library for fast numerical computation that can be run on the CPU or GPU. It is a key foundational library for deep learning in Python that you can use directly to createdeep learning models. After completing this lesson, you will know: About the Theano library for Pyt... |
2. 2. How to Install Theano122. 2 How to Install Theano Theano provides extensive installation instructions for the major operating systems: Windows,OS X and Linux. Read the Installing Theano guide for your platform3. Theano assumes aworking Python 2 or Python 3 environment with Sci Py. There are ways to make the insta... |
2. 4. Extensions and Wrappers for Theano13#createasimplesymbolicexpressionc=a+b#converttheexpressionintoacallableobjectthattakes(a,b)andcomputescf = theano. function([a,b], c)#bind1. 5to a,2. 5to b,andevaluate c result = f(1. 5, 2. 5)print(result)Listing 2. 4: Example of Symbolic Arithmetic with Theano. Running the exa... |
2. 6. Summary142. 6 Summary In this lesson you discovered the Theano Python library for e cient numerical computation. You learned: Theano is a foundation library used for deep learning research and development. Deep learning models can be developed directly in Theano if desired. The development and evaluation of deep ... |
Chapter 3Introduction to Tensor Flow Tensor Flow is a Python library for fast numerical computing created and released by Google. It is a foundation library that can be used to create deep learning models directly or by usingwrapper libraries that simplify the process built on top of Tensor Flow. After completing thisl... |
3. 3. Your First Examples in Tensor Flow16environment, it is relatively straightforward to install Tensor Flow using pip There are a numberof di↵erent distributions of Tensor Flow, customized for di↵erent environments, therefore toinstall Tensor Flow you can follow the Download and Setup instructions3on the Tensor Flow... |
3. 5. More Deep Learning Models17Running the example prints the output 4, which matches our expectation that 1. 5+2. 5=4. 0. This is a useful example as it gives you a flavor for how a symbolic expression can be defined,compiled and used. Although we have only performed a basic introduction of adding 2 and 2,you can see ... |
3. 6. Summary183. 6. 1 Next You now know about the Theano and Tensor Flow libraries for e cient numerical computationin Python. In the next lesson you will discover the Keras library that wraps both libraries andgives you a clean and simple API for developing and evaluating deep learning models. |
Chapter 4Introduction to Keras Two of the top numerical platforms in Python that provide the basis for deep learning researchand development are Theano and Tensor Flow. Both are very powerful libraries, but both canbe di cult to use directly for creating deep learning models. In this lesson you will discoverthe Keras P... |
4. 2. How to Install Keras204. 2 How to Install Keras Keras is relatively straightforward to install if you already have a working Python and Sci Pyenvironment. You must also have an installation of Theano or Tensor Flow on your system. Keras can be installed easily using pip, as follows:sudo pip install keras Listing ... |
4. 4. Build Deep Learning Models with Keras21python-c"fromkerasimportbackend;print(backend. _BACKEND)"Listing 4. 7: Script to Print the Configured Keras Backend. Running this with default configuration you will see:Using Tensor Flow backend. tensorflow Listing 4. 8: Sample Output of Script to Print the Configured Keras Ba... |
4. 5. Summary224. 5 Summary In this lesson you discovered the Keras Python library for deep learning research and development. You learned: Keras wraps both the Tensor Flow and Theano libraries, abstracting their capabilities andhiding their complexity. Keras is designed for minimalism and modularity allowing you to ve... |
Chapter 5Project: Develop Large Models on GPUs Cheaply In the Cloud Large deep learning models require a lot of compute time to run. You can run them on your CPU but it can take hours or days to get a result. If you have access to a GPU on your desktop,you can drastically speed up the training time of your deep learnin... |
5. 2. Setup Your AWS Account245. 2 Setup Your AWS Account You need an account on Amazon Web Services1. 1. You can create account by the Amazon Web Services portal and click Sign in to the Console. From there you can sign in using an existing Amazon account or create a newaccount. Figure 5. 1: AWS Sign-in Button 2. You ... |
5. 3. Launch Your Server Instance25 Figure 5. 2: AWS Sign-In Form Once you have an account you can log into the Amazon Web Services console. You will seear a n g eo fd i↵erent services that you can access. 5. 3 Launch Your Server Instance Now that you have an AWS account, you want to launch an EC2 virtual server instan... |
5. 3. Launch Your Server Instance26 Figure 5. 3: AWS Console 2. Click on EC2 for launching a new virtual server. 3. Select N. Californiafrom the drop-down in the top right hand corner. This is importantotherwise you will not be able to find the image we plan to use. Figure 5. 4: Select North California 4. Click the Laun... |
5. 3. Launch Your Server Instance27 Figure 5. 5: Community AMIs 6. Enterami-125b2c72in the Search community AMIssearch box and press enter. Youshould be presented with a single result. Figure 5. 6: Select a Specific AMI 7. Click Selectto choose the AMI in the search result. 8. Now you need to select the hardware on whic... |
5. 3. Launch Your Server Instance28pair, select the option Create a new key pairand enter a Key pair namesuch as keras-keypair. Click the Download Key Pairbutton. Figure 5. 8: Select Your Key Pair 12. Open a Terminal and change directory to where you downloaded your key pair. 13. If you have not already done so, restri... |
5. 4. Login, Configure and Run29 Figure 5. 9: Review Your Running Instance Your server is now running and ready for you to log in. 5. 4 Login, Configure and Run Now that you have launched your server instance, it is time to log in and start using it. 1. Click View Instancesin your Amazon EC2 console if you have not done ... |
5. 4. Login, Configure and Run30 Figure 5. 10: Log in Screen for Your AWS Server We need to make two small changes before we can start using Keras. This will just take aminute. You will have to do these changes each time you start the instance. 5. 4. 1 Update Keras Update to a specific version of Keras known to work on t... |
5. 5. Build and Run Models on AWS31This configures Theano to use the GPU instead of the CPU. Among some other minorconfiguration it ensures that not all GPU memory is used by Theano, avoiding memory errors ifyou start using larger datasets like CIFAR-10. We're done. You can confirm that Theano isworking correctly by typin... |
5. 6. Close Your EC2 Instance325. 5. 2 Run Models on AWSYou can run your scripts on your AWS instance as per normal:python filename. py Listing 5. 11: Example of Running a Python script on AWS. You are using AWS to create large neural network models that may take hours or days totrain. As such, it is a better idea to r... |
5. 6. Close Your EC2 Instance33 Figure 5. 11: Review Your List of Running Instances 5. Select your running instance from the list (it may already be selected if you only haveone running instance). Figure 5. 12: Select Your Running AWS Instance 6. Click the Actionsbutton and select Instance Stateand choose Terminate. Co... |
5. 7. Tips and Tricks for Using Keras on AWS345. 7 Tips and Tricks for Using Keras on AWSBelow are some tips and tricks for getting the most out of using Keras on AWS instances. Design a suite of experiments to run beforehand. Experiments can take a longtime to run and you are paying for the time you use. Make time to ... |
5. 9. Summary355. 9. 1 Next This concludes Part II and gives you the capability to install, configure and use the Pythondeep learning libraries on your workstation or in the cloud, leveraging GPU hardware. Next in Part III you will learn how to use the Keras API and develop your own neural network models. |
Part IIIMultilayer Perceptrons 36 |
Chapter 6Crash Course In Multilayer Perceptrons Artificial neural networks are a fascinating area of study, although they can be intimidatingwhen just getting started. There is a lot of specialized terminology used when describing thedata structures and algorithms used in the field. In this lesson you will get a crash co... |
6. 2. Multilayer Perceptrons386. 2 Multilayer Perceptrons The field of artificial neural networks is often just called Neural Networksor Multilayer Percep-tronsafter perhaps the most useful type of neural network. A Perceptron is a single neuronmodel that was a precursor to larger neural networks. It is a field of study t... |
6. 4. Networks of Neurons396. 3. 1 Neuron Weights You may be familiar with linear regression, in which case the weights on the inputs are verymuch like the coe cients used in a regression equation. Like linear regression, each neuron alsohas a bias which can be thought of as an input that always has the value 1. 0 and ... |
6. 4. Networks of Neurons40 Figure 6. 2: Model of a Simple Network6. 4. 1 Input or Visible Layers The bottom layer that takes input from your dataset is called the visible layer, because it isthe exposed part of the network. Often a neural network is drawn with a visible layer with oneneuron per input value or column i... |
6. 5. Training Networks41 A multiclass classification problem may have multiple neurons in the output layer, one foreach class (e. g. three neurons for the three classes in the famous iris flowers classificationproblem). In this case a softmax activation function may be used to output a probabilityof the network predictin... |
6. 6. Summary42Alternatively, the errors can be saved up across all of the training examples and the networkcan be updated at the end. This is called batch learning and is often more stable. Because datasets are so large and because of computational e ciencies, the size of thebatch, the number of examples the network i... |
Chapter 7Develop Your First Neural Network With Keras Keras is a powerful and easy-to-use Python library for developing and evaluating deep learningmodels. It wraps the e cient numerical computation libraries Theano and Tensor Flow andallows you to define and train neural network models in a few short lines of code. In ... |
7. 2. Pima Indians Onset of Diabetes Dataset447. 2 Pima Indians Onset of Diabetes Dataset In this tutorial we are going to use the Pima Indians onset of diabetes dataset. This is astandard machine learning dataset available for free download from the UCI Machine Learningrepository. It describes patient medical record d... |
7. 3. Load Data45The baseline accuracy if all predictions are made asno onset of diabetesis 65. 1%. Topresults on the dataset are in the range of 77. 7% accuracy using 10-fold cross validation2. Y o ucan learn more about the dataset on the dataset home page on the UCI Machine Learning Repository3. 7. 3 Load Data Whenev... |
7. 4. Define Model46to capture the structure of the problem if that helps at all. In this example we will use afully-connected network structure with three layers. Fully connected layers are defined using the Denseclass. We can specify the number ofneurons in the layer as the first argument, the initialization method as t... |
7. 5. Compile Model47 Figure 7. 1: Visualization of Neural Network Structure. 7. 5 Compile Model Now that the model is defined, we can compile it. Compiling the model uses the e cientnumerical libraries under the covers (the so-called backend) such as Theano or Tensor Flow. The backend automatically chooses the best way... |
7. 6. Fit Model487. 6 Fit Model We have defined our model and compiled it ready for e cient computation. Now it is time toexecute the model on some data. We can train or fit our model on our loaded data by callingthefit()function on the model. The training process will run for a fixed number of iterations through the data... |
7. 9. Summary49dataset = numpy. loadtxt("pima-indians-diabetes. csv", delimiter=",")#splitintoinput(X)andoutput(Y)variables X = dataset[:,0:8]Y = dataset[:,8]#createmodelmodel = Sequential()model. add(Dense(12, input_dim=8, init= uniform, activation= relu ))model. add(Dense(8, init= uniform, activation= relu ))model. a... |
7. 9. Summary50 How to train a model on data. How to evaluate a model on data. 7. 9. 1 Next You now know how to develop a Multilayer Perceptron model in Keras. In the next section youwill discover di↵erent ways that you can evaluate your models and estimate their performanceon unseen data. |
Chapter 8Evaluate The Performance of Deep Learning Models There are a lot of decisions to make when designing and configuring your deep learning models. Most of these decisions must be resolved empirically through trial and error and evaluatingthem on real data. As such, it is critically important to have a robust way t... |
8. 2. Data Splitting52and validation datasets. Keras provides two convenient ways of evaluating your deep learningalgorithms this way:1. Use an automatic verification dataset. 2. Use a manual verification dataset. 8. 2. 1 Use a Automatic Verification Dataset Keras can separate a portion of your training data into a valida... |
8. 2. Data Splitting53Epoch 149/150514/514 [==============================]-0s-loss: 0. 4863-acc: 0. 7724-val_loss:0. 5074-val_acc: 0. 7717Epoch 150/150514/514 [==============================]-0s-loss: 0. 4884-acc: 0. 7724-val_loss:0. 5462-val_acc: 0. 7205Listing 8. 2: Output of Evaluating A Neural Network Using an Aut... |
8. 3. Manualk-Fold Cross Validation54Epoch 147/150514/514 [==============================]-0s-loss: 0. 4936-acc: 0. 7685-val_loss:0. 5426-val_acc: 0. 7283Epoch 148/150514/514 [==============================]-0s-loss: 0. 4957-acc: 0. 7685-val_loss:0. 5430-val_acc: 0. 7362Epoch 149/150514/514 [===========================... |
8. 4. Summary55#splitintoinput(X)andoutput(Y)variables X = dataset[:,0:8]Y = dataset[:,8]#define10-foldcrossvalidationtestharnesskfold = Stratified KFold(n_splits=10, shuffle=True, random_state=seed)cvscores = []fortrain, testinkfold. split(X, Y):#createmodelmodel = Sequential()model. add(Dense(12, input_dim=8, init= u... |
8. 4. Summary568. 4. 1 Next You now know how to evaluate your models and estimate their performance. In the next lessonyou will discover how you can best integrate your Keras models with the scikit-learn machinelearning library. |
Chapter 9Use Keras Models With Scikit-Learn For General Machine Learning The scikit-learn library is the most popular library for general machine learning in Python. In this lesson you will discover how you can use deep learning models from Keras with thescikit-learn library in Python. After completing this lesson you ... |
9. 2. Evaluate Models with Cross Validation589. 2 Evaluate Models with Cross Validation The Keras Classifierand Keras Regressorclasses in Keras take an argumentbuildfnwhichis the name of the function to call to create your model. You must define a function calledwhatever you like that defines your model, compiles it and ... |
9. 3. Grid Search Deep Learning Model Parameters590. 731715653237Listing 9. 2: Output of Evaluate A Neural Network Using scikit-learn. You can see that when the Keras model is wrapped that estimating model accuracy can begreatly streamlined, compared to the manual enumeration of cross validation folds performed inthe p... |
9. 3. Grid Search Deep Learning Model Parameters60importnumpy#Functiontocreatemodel,requiredfor Keras Classifierdefcreate_model(optimizer= rmsprop, init= glorot_uniform ):#createmodelmodel = Sequential()model. add(Dense(12, input_dim=8, init=init, activation= relu ))model. add(Dense(8, init=init, activation= relu ))mod... |
9. 4. Summary61 batch_size : 5}... Listing 9. 4: Output of Grid Search Neural Network Parameters Using scikit-learn. 9. 4 Summary In this lesson you discovered how you can wrap your Keras deep learning models and use themin the scikit-learn general machine learning library. You learned: Specifically how to wrap Keras mo... |
Chapter 10Project: Multiclass Classification Of Flower Species In this project tutorial you will discover how you can use Keras to develop and evaluate neuralnetwork models for multiclass classification problems. After completing this step-by-step tutorial,you will know: How to load data from CSV and make it available to... |
10. 2. Import Classes and Functions635. 1,3. 5,1. 4,0. 2,Iris-setosa4. 9,3. 0,1. 4,0. 2,Iris-setosa4. 7,3. 2,1. 3,0. 2,Iris-setosa4. 6,3. 1,1. 5,0. 2,Iris-setosa5. 0,3. 6,1. 4,0. 2,Iris-setosa Listing 10. 1: Sample of the Iris Flowers Dataset. The iris flower dataset is a well studied problem and a such we can expect to... |
10. 4. Load The Dataset6410. 4 Load The Dataset The dataset can be loaded directly. Because the output variable contains strings, it is easiest toload the data using pandas. We can then split the attributes (columns) into input variables (X)and output variables (Y). #loaddatasetdataframe = pandas. read_csv("iris. csv",... |
10. 6. Define The Neural Network Model6510. 6 Define The Neural Network Model The Keras library provides wrapper classes to allow you to use neural network models developedwith Keras in scikit-learn as we saw in the previous lesson. There is a Keras Classifierclassin Keras that can be used as an Estimator in scikit-learn... |
10. 7. Evaluate The Model withk-Fold Cross Validation66evaluation procedure. Here, we set the number of folds to be 10 (an excellent default) and toshu✏et h ed a t ab e f o r ep a r t i t i o n i n gi t. kfold = KFold(n_splits=10, shuffle=True, random_state=seed)Listing 10. 11: Prepare Cross Validation. Now we can eval... |
10. 8. Summary67Listing 10. 13: Multilayer Perceptron Model for Iris Flowers Problem. The results are summarized as both the mean and standard deviation of the model accuracyon the dataset. This is a reasonable estimation of the performance of the model on unseen data. It is also within the realm of known top results f... |
Chapter 11Project: Binary Classification Of Sonar Returns In this project tutorial you will discover how to e↵ectively use the Keras library in your machinelearning project by working through a binary classification project step-by-step. After completingthis step-by-step tutorial, you will know: How to load training data... |
11. 2. Baseline Neural Network Model Performance69for custom models at around 88%2. You can learn more about this dataset on the UCI Machine Learning repository3. 11. 2 Baseline Neural Network Model Performance Let's create a baseline model and result for this problem. We will start o↵by importing all ofthe classes and... |
11. 2. Baseline Neural Network Model Performance70encoded_Y = encoder. transform(Y)Listing 11. 4: Label Encode Output Variable. We are now ready to create our neural network model using Keras. We are going to usescikit-learn to evaluate the model using stratifiedk-fold cross validation. This is a resamplingtechnique tha... |
11. 3. Improve Performance With Data Preparation71fromsklearn. preprocessingimport Label Encoderfromsklearn. model_selectionimport Stratified KFoldfromsklearn. preprocessingimport Standard Scalerfromsklearn. pipelineimport Pipeline#fixrandomseedforreproducibilityseed = 7numpy. random. seed(seed)#loaddatasetdataframe = ... |
11. 3. Improve Performance With Data Preparation72cross validation run and to use the trained standardization instance to prepare the unseen testfold. This makes standardization a step in model preparation in the cross validation processand it prevents the algorithm having knowledge of unseen data during evaluation, kn... |
11. 4. Tuning Layers and Neurons in The Model73mean accuracy. Standardized: 84. 07% (6. 23%)Listing 11. 10: Sample Output From Update Using Data Standardization. 11. 4 Tuning Layers and Neurons in The Model There are many things to tune on a neural network, such as the weight initialization, activationfunctions, optimi... |
11. 4. Tuning Layers and Neurons in The Model74#createmodelmodel = Sequential()model. add(Dense(30, input_dim=60, init= normal, activation= relu ))model. add(Dense(1, init= normal, activation= sigmoid ))#Compilemodelmodel. compile(loss= binary_crossentropy, optimizer= adam, metrics=[ accuracy ])returnmodelnumpy. random... |
11. 5. Summary75fromsklearn. model_selectionimport Stratified KFoldfromsklearn. preprocessingimport Standard Scalerfromsklearn. pipelineimport Pipeline#fixrandomseedforreproducibilityseed = 7numpy. random. seed(seed)#loaddatasetdataframe = pandas. read_csv("sonar. csv", header=None)dataset = dataframe. values#splitinto... |
11. 5. Summary76 How to create a baseline neural network model. How to evaluate a Keras model using scikit-learn and stratifiedk-fold cross validation. How data preparation schemes can lift the performance of your models. How experiments adjusting the network topology can lift model performance. 11. 5. 1 Next You now kn... |
Chapter 12Project: Regression Of Boston House Prices In this project tutorial you will discover how to develop and evaluate neural network modelsusing Keras for a regression problem. After completing this step-by-step tutorial, you will know: How to load a CSV dataset and make it available to Keras. How to create a neu... |
12. 2. Develop a Baseline Neural Network Model787. AGE: proportion of owner-occupied units built prior to 1940. 8. DIS: weighted distances to five Boston employment centers. 9. RAD: index of accessibility to radial highways. 10. TAX: full-value property-tax rate per 10,000. 11. PTRATIO: pupil-teacher ratio by town. 12. ... |
12. 2. Develop a Baseline Neural Network Model79We can now load our dataset from a file in the local directory. The dataset is in fact not in CSV format on the UCI Machine Learning Repository, the attributes are instead separated bywhitespace. We can load this easily using the Pandas library. We can then split the input... |
12. 2. Develop a Baseline Neural Network Model80#evaluatemodelwithstandardizeddatasetestimator = Keras Regressor(build_fn=baseline_model, nb_epoch=100, batch_size=5, verbose=0)Listing 12. 5: Initialize Random Number Generator and Prepare Model Wrapper for scikit-learn. The final step is to evaluate this baseline model. ... |
12. 3. Lift Performance By Standardizing The Dataset81Listing 12. 8: Sample Output From Evaluating the Baseline Model. 12. 3 Lift Performance By Standardizing The Dataset An important concern with the Boston house price dataset is that the input attributes all varyin their scales because they measure di↵erent quantitie... |
12. 4. Tune The Neural Network Topology82kfold = KFold(n_splits=10, random_state=seed)results = cross_val_score(pipeline, X, Y, cv=kfold)print("Standardized:%. 2f(%. 2f)MSE"% (results. mean(), results. std()))Listing 12. 9: Update To Use a Standardized Dataset. Running the example provides an improved performance over ... |
12. 4. Tune The Neural Network Topology83dataset = dataframe. values#splitintoinput(X)andoutput(Y)variables X = dataset[:,0:13]Y = dataset[:,13]#definethemodeldeflarger_model():#createmodelmodel = Sequential()model. add(Dense(13, input_dim=13, init= normal, activation= relu ))model. add(Dense(6, init= normal, activatio... |
12. 5. Summary84fromkeras. layersimport Densefromkeras. wrappers. scikit_learnimport Keras Regressorfromsklearn. model_selectionimportcross_val_scorefromsklearn. model_selectionimport KFoldfromsklearn. preprocessingimport Standard Scalerfromsklearn. pipelineimport Pipeline#loaddatasetdataframe = pandas. read_csv("housi... |
12. 5. Summary85 How to design and evaluate networks with di↵erent varying topologies on a problem. 12. 5. 1 Next This concludes Part III of the book and leaves you with the skills to develop neural networkmodels on standard machine learning datasets. Next in Part IV you will learn how to get morefrom your neural netwo... |
Part IVAdvanced Multilayer Perceptrons and Keras 86 |
Chapter 13Save Your Models For Later With Serialization Given that deep learning models can take hours, days and even weeks to train, it is importantto know how to save and load them from disk. In this lesson you will discover how you can saveyour Keras models to file and load them up again to make predictions. After co... |
13. 2. Save Your Neural Network Model to JSON8813. 2 Save Your Neural Network Model to JSONJSON is a simple file format for describing data hierarchically. Keras provides the ability todescribe any model using JSON format with atojson()function. This can be saved to fileand later loaded via themodelfromjson()function tha... |
13. 2. Save Your Neural Network Model to JSON89json_file =open( model. json, r )loaded_model_json = json_file. read()json_file. close()loaded_model = model_from_json(loaded_model_json)#loadweightsintonewmodelloaded_model. load_weights("model. h5")print("Loadedmodelfromdisk")#evaluateloadedmodelontestdataloaded_model. c... |
13. 3. Save Your Neural Network Model to YAML90"name":"dense_2","activity_regularizer":null,"trainable":true,"init":"uniform","input_dim":null,"b_regularizer":null,"W_regularizer":null,"activation":"relu","output_dim":8}},{"class_name":"Dense","config":{"W_constraint":null,"b_constraint":null,"name":"dense_3","activity... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 10