ebook img

Hands-On Quantum Machine Learning With Python Volume 1: Get Started PDF

435 Pages·2021·5.201 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Hands-On Quantum Machine Learning With Python Volume 1: Get Started

Hands-On Quantum Machine Learning With Python Volume 1: Get Started Dr. Frank Zickert PyQML Copyright©2021Dr. FrankZickert PUBLISHEDBYPYQML www.pyqml.com Thecontentsofthisbook, unlessotherwiseindicated, areCopyright©2021 Dr. FrankZickert,pyqml.com. Allrightsreserved. Bookslikethisaremade possible by the time invested by the authors. If you received this book and didnotpurchaseit,pleaseconsidermakingfuturebookspossiblebybuying acopyathttps://www.pyqml.comtoday. Release1.0,May2021 Contents 1 Introduction ............................................... 7 1.1 WhoThisBookIsFor ........................................... 7 1.2 BookOrganization .............................................. 9 1.3 WhyShouldIBotherWithQuantumMachineLearning? ......... 10 1.4 QuantumMachineLearning‐BeyondTheHype ................. 11 1.4.1 WhatisMachineLearning? ....................................... 11 1.4.2 WhatisQuantumComputing? .................................... 13 1.4.3 HowDoesMachineLearningWork? ................................ 15 1.4.4 WhatTasksAreQuantumComputersGoodAt? ...................... 16 1.4.5 TheCaseForQuantumMachineLearning .......................... 18 1.5 QuantumMachineLearningInTheNISQEra .................... 19 1.6 IlearnedQuantumMachineLearningTheHardWay ............. 21 1.7 QuantumMachineLearningIsTaughtTheWrongWay .......... 24 1.8 ConfiguringYourQuantumMachineLearningWorkstation ...... 26 1.8.1 Python ........................................................ 27 1.8.2 Jupyter ........................................................ 27 1.8.3 LibrariesandPackages .......................................... 27 1.8.4 VirtualEnvironment ............................................ 28 1.8.5 ConfiguringUbuntuForQuantumMachineLearningwithPython ...... 28 1.8.6 HowToSetupJupyterLabForQuantumComputing‐‐‐OnWindows ..... 30 2 Binary Classification .................................... 33 2.1 PredictingSurvivalOnTheTitanic ............................ 33 2.2 GettheDataset ............................................... 34 2.3 Lookatthedata .............................................. 35 2.4 DataPreparationandCleaning ................................ 38 2.4.1 MissingValues .................................................. 38 2.4.2 Identifiers ...................................................... 40 2.4.3 HandlingTextandCategoricalAttributes ........................... 42 2.4.4 FeatureScaling ................................................. 43 2.4.5 TrainingandTesting ............................................ 45 2.5 Baseline ..................................................... 46 2.6 ClassifierEvaluationandMeasures ............................ 49 2.7 UnmasktheHypocriteClassifier ............................... 53 3 Qubit and Quantum States ............................. 62 3.1 ExploringtheQuantumStates ................................. 62 3.2 VisualExplorationOfTheQubitState .......................... 72 3.3 BypassingTheNormalization .................................. 74 3.4 ExploringTheObserverEffect ................................. 79 3.5 ParameterizedQuantumCircuit ............................... 84 3.6 VariationalHybridQuantum‐ClassicalAlgorithm ............... 89 4 Probabilistic Binary Classifier ........................ 100 4.1 TowardsNaïveBayes ......................................... 101 4.2 Bayes'Theorem ............................................. 105 4.3 GaussianNaïveBayes ........................................ 109 5 Working with Qubits ................................... 113 5.1 YouDon'tNeedToBeAMathematician ....................... 113 5.2 QuantumicMath‐AreYouReadyForTheRedPill? ............ 124 5.3 IfYouWantToGambleWithQuantumComputing… ............ 134 6 Working With Multiple Qubits ......................... 147 6.1 Hands‐OnIntroductionToQuantumEntanglement ............ 147 6.2 TheEquationEinsteinCouldNotBelieve ...................... 159 6.2.1 SingleQubitSuperposition ...................................... 160 6.2.2 QuantumTransformationMatrices ............................... 161 6.2.3 TransformingSingleQubits ...................................... 162 6.2.4 Two‐QubitStates ............................................... 162 6.2.5 Two‐QubitTransformations ..................................... 164 6.2.6 Entanglement ................................................. 167 6.3 QuantumProgrammingForNon‐mathematicians .............. 173 6.3.1 Representingamarginalprobability .............................. 176 6.3.2 Calculatethejointprobability .................................... 178 6.3.3 Calculatetheconditionalprobability .............................. 186 7 Quantum Naïve Bayes ................................. 204 7.1 Pre‐processing .............................................. 206 7.2 PQC ......................................................... 209 7.3 Post‐Processing ............................................. 222 8 Quantum Computing Is Different ..................... 225 8.1 TheNo‐CloningTheorem ..................................... 225 8.2 HowToSolveAProblemWithQuantumComputing ............ 231 8.3 TheQuantumOracleDemystified ............................. 244 9 Quantum Bayesian Networks ......................... 253 9.1 BayesianNetworks .......................................... 255 9.2 ComposingQuantumComputingControls ..................... 259 9.3 Circuitimplementation ...................................... 274 10 Bayesian Inference .................................... 281 10.1 LearningHiddenVariables ................................... 282 10.2 EstimatingASingleDataPoint ............................... 283 10.3 EstimatingAVariable ....................................... 294 10.4 PredictSurvival ............................................. 316 11 The World Is Not A Disk ............................... 320 11.1 TheQubitPhase ............................................. 320 6 11.2 VisualizeTheInvisibleQubitPhase ........................... 333 11.2.1 TheZ‐gate .................................................... 334 11.2.2 Multi‐QubitPhase .............................................. 343 11.2.3 ControlledZ‐gate ............................................... 349 11.3 PhaseKickback ............................................. 351 11.4 QuantumAmplitudesandProbabilities ....................... 364 12 Working With The Qubit Phase ........................ 371 12.1 TheIntuitionOfGrover'sAlgorithm .......................... 372 12.2 BasicAmplitudeAmplification ............................... 377 12.3 Two‐QubitAmplification ..................................... 385 13 Search For The Relatives .............................. 397 13.1 TurningtheProblemintoaCircuit ............................ 400 13.2 MultipleResults ............................................. 416 14 Sampling ................................................ 420 14.1 ForwardSampling ........................................... 420 14.2 BayesianRejectionSampling ................................. 422 14.3 QuantumRejectionSampling ................................. 427 15 What's Next? ........................................... 434 1. Introduction WelcometoHands-OnQuantumMachineLearningWithPython.Thisbook isyourcomprehensiveguidetogetstartedwith“QuantumMachineLearning” – the use of quantumcomputing for the computation of machinelearning algorithms. Hands-On Quantum Machine Learning With Python strives to be the per- fect balance between theory taught in a textbook and the actual hands-on knowledgeyou’llneedtoimplementreal-worldsolutions. Inside this book, you will learn the basics of quantum computing and ma- chinelearninginapracticalandappliedmanner. Andyouwilllearntouse state-of-the-artquantummachinelearningalgorithms. By the time you finish this book, you’ll be well equipped to apply quantum machinelearningtoyourprojects. Then,youwillbeinthepolepositionto becomea“QuantumMachineLearningEngineer”–thejobtobecomethesexi- estjobofthe2020s. 1.1 Who This Book Is For Thisbookisfordevelopers,programmers,students,andresearcherswho haveatleastsome programmingexperienceand wanttobecomeproficient inquantummachinelearning. Don’tworryifyou’rejustgettingstartedwithquantumcomputingandma- chine learning. We will begin with the basics, and we don’t assume prior 8 Chapter1.Introduction knowledgeofmachinelearningorquantumcomputing. Soyouwillnotget leftbehind. If you have experience in machine learning or quantum computing, the re- spective parts may repeat concepts you’re already familiar with. However, this may make learning the corresponding new topic easier and provide a slightlydifferentangletotheknown. This book offers a practical, hands-on exploration of quantum machine learning. Ratherthanworkingthroughtonsoftheory,wewillbuildupprac- ticalintuitionaboutthecoreconcepts. Wewillacquiretheexactknowledge weneedtosolvepracticalexampleswithlotsofcode. Stepbystep, youwill extendyourknowledgeandlearnhowtosolvenewproblems. Of course, we will do some math. Of course, we will cover a little physics. But I don’t expect you to hold a degree in any of these two fields. We will go through all the concepts we need. While this includes some mathemati- calnotationandformulae,wekeepitattheminimumrequiredtosolveour practicalproblems. The theoretical foundation of quantum machine learning may appear over- whelmingatfirstsight. But,beassuredthatitisnotharderthanlearninga newprogramminglanguagewhenputintothepropercontextandexplained conceptually. Andthisiswhat’sinsideHands-OnQuantumMachineLearn- ingWithPython. Of course, we will write code. A lot of code. Do you know a little Python? Great! If you don’t know Python but another language, such as Java, Javascript, or PHP, you’ll be fine, too. If you know programming concepts (suchasif-thenelse-constructsandloops),thenlearningthesyntaxisapiece ofcake. Ifyou’refamiliarwithfunctionalprogrammingconstructs,suchas map,filter,andreduce,you’realreadywellequipped. Ifnot,don’tworry. We willgetyoustartedwiththeseconstructs,too. Wedon’texpectyoutobease- niorsoftwaredeveloper. Wewillgothroughallthesourcecode—linebyline. By the time you finish the first few chapters of this book, you will be profi- cientwithdoingthemath,understandingthephysics,andwritingthecode youneedtograduatetothemoreadvancedcontent. Thisbookisnotjustforbeginners. Thereisalotofadvancedcontentinhere, too. Manychaptersof Hands-OnQuantumMachineLearningWithPython cover, explain, andapplyquantummachinelearningalgorithmsdeveloped inthelasttwoyears. Youcandirectlyapplytheinsightsthisbookprovides in your job and research. The time you save by reading through Hands-On QuantumMachineLearningWithPythonwillmorethanpayforitself. 1.2 BookOrganization 9 1.2 Book Organization Machinelearningandquantumcomputingrelyonmath,statistics,physics, andcomputerscience. Thisisalotoftheory. Coveringitallupfrontwould beprettyexhaustiveandfillatleastonebookwithoutanypracticalinsight. However, without understanding the underlying theoretical concepts, the code examples on their own do not provide many practical insights, either. Whilelibrariesfreeyoufromtediousimplementationdetails,thecode,even thoughshort,doesnotexplainthecoreconcepts. Thisbookprovidesthetheoryneededtounderstandthecodewe’rewriting tosolveaproblem. Foronething, wecoverthetheorywhenitapplies, and weneedittounderstandthebackgroundofwhatwearedoing. Secondly,we willembedthetheoryintosolvingapracticalproblemanddirectlyseeitin action. As a result, the theory spreads among all the chapters, from simple to com- plex. You may skip individual examples if you like. But you should have a lookatthetheoreticalconceptsdiscussedineachchapter. We start with a Variational Hybrid Quantum-Classical Algorithm to solve a binary classification task. First, we have a detailed look at binary classifica- tion in chapter 2. Then, in chapter 3, we introduce the basic concept of the quantumbit,thequantumstate,andhowmeasurementaffectsit. Basedon theseconcepts,webuildourfirstParameterizedQuantumCircuitanduseit tosolveourbinaryclassificationtask. Suchahybridalgorithmcombinesthe quantumstatepreparationandmeasurementwithclassicaloptimization. Then, we learn how to work with single qubits (chapter 5) and with multi- plequbits(chapter6). Andweexploretheastonishingphenomenonofquan- tum entanglement. This serves as our basis to develop a Quantum Naïve Bayesclassifier(chapter7). Inchapter8,wedivedeepintothespecificitiesof howquantumcomputingisdifferentfromclassicalcomputingandhowwe solveproblemsthequantumway. Itenablesustocreateandtrainaquantum Bayesiannetwork(chapter9). By now, you’ll be experienced in dealing with the probabilistic nature of qubits. It’s time to take it one step further. We learn about the qubit phase (chapter 11) and how we can use it to tap the potential of quantum systems (chapter12). WeuseittosearchtherelativesofapassengeronboardtheTi- tanic(chapter13)andapproximateavariable’sdistributioninourquantum Bayesiannetwork. (chapter14). YoucanfindthecompletesourcecodeofthisbookthisGithubrepository. 10 Chapter1.Introduction 1.3 Why Should I Bother With Quantum Machine Learning? In the recent past, we have witnessed how algorithms learned to drive cars and beat world champions in chess and Go. Machine learning is being ap- pliedtovirtuallyeveryimaginablesector, frommilitarytoaerospace, from agriculturetomanufacturing,andfromfinancetohealthcare. Butthesealgorithmsbecomeincreasinglyhardtotrainbecausetheyconsist of billions of parameters. Quantum computers promise to solve such prob- lemsintractablewithcurrentcomputingtechnologies. Moreover,theirabil- ity to compute multiple states simultaneously enables them to perform an indefinite number of superposed tasks in parallel. An ability that promises toimproveandtoexpeditemachinelearningtechniques. Unlike classical computers based on sequential information processing, quantumcomputingusesthepropertiesofquantumphysics: superposition, entanglement, and interference. But rather than increasing the available computingcapacity,itreducesthecapacityneededtosolveaproblem. Butquantumcomputingrequiresustochangethewaywethinkaboutcom- puters. It requires a whole new set of algorithms. Algorithms that encode andusequantuminformation. Thisincludesmachinelearningalgorithms. Anditrequiresanewsetofdevelopers. Developerswhounderstandmachine learning and quantum computing. Developers capable of solving practical problems that have not been solved before. A rare type of developer. The ability to solve quantum machine learning problems already sets you apart fromalltheothers. Quantummachinelearningpromisestobedisruptive. Althoughthismerger ofmachinelearningandquantumcomputing,bothareasofactiveresearch, islargelyintheconceptualdomain,therearealreadysomeexampleswhereit isbeingappliedtosolvereal-lifeproblems. Google,Amazon,IBM,Microsoft, andawholefleetofhigh-techstartupsstrivetobethefirsttobuildandsell quantummachinelearningsystems. The opportunity to study a technology right when it is about to prove its supremacyisauniqueopportunity. Don’tmissit.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.