├── QuantumPerceptron.pptx ├── qsharp-quick-reference.pdf ├── QuantumPerceptron ├── QuantumPerceptron.csproj ├── QuantumPerceptron.sln ├── ClassicalDriver.cs ├── QuantumClassifier_Easy.qs └── QuantumClassifier.qs ├── LICENSE ├── README.md └── .gitignore /QuantumPerceptron.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/MLADS2018-QuantumML/HEAD/QuantumPerceptron.pptx -------------------------------------------------------------------------------- /qsharp-quick-reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/MLADS2018-QuantumML/HEAD/qsharp-quick-reference.pdf -------------------------------------------------------------------------------- /QuantumPerceptron/QuantumPerceptron.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | Exe 4 | netcoreapp2.1 5 | x64 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /QuantumPerceptron/QuantumPerceptron.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27130.2036 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuantumPerceptron", "QuantumPerceptron.csproj", "{8D1D7634-1578-4A53-AAF1-B0FAE6C4B446}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8D1D7634-1578-4A53-AAF1-B0FAE6C4B446}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8D1D7634-1578-4A53-AAF1-B0FAE6C4B446}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8D1D7634-1578-4A53-AAF1-B0FAE6C4B446}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8D1D7634-1578-4A53-AAF1-B0FAE6C4B446}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C73A1598-2A3E-4A2E-9EDC-B4CE8B3CDB2F} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ***This repository has been archived. Please refer to [the tutorial on quantum classification with Q#](https://github.com/microsoft/QuantumKatas/tree/main/tutorials/QuantumClassification) for the latest version of the tutorial.*** 2 | 3 | # Welcome! 4 | 5 | This repository contains the materials for the "Introduction to Quantum Machine Learning" workshop. 6 | 7 | In this workshop the participants will get hands-on experience implementing the simplest quantum machine learning algorithm - a quantum perceptron. 8 | 9 | ## Installing and Getting Started 10 | 11 | To work on this tutorial, you'll need to install the [Quantum Development Kit](https://docs.microsoft.com/quantum), available for Windows 10, macOS, and for Linux. 12 | Please see the [install guide for the Quantum Development Kit](https://docs.microsoft.com/quantum/install-guide/) for the detailed instructions. We recommend that you use Visual Studio 2017 or Visual Studio Code. 13 | 14 | If you have Git installed, go on and clone the Microsoft/MLADS2018-QuantumML repository. From your favorite command line: 15 | 16 | ```bash 17 | git clone https://github.com/Microsoft/MLADS2018-QuantumML.git 18 | ``` 19 | 20 | > **TIP**: Both Visual Studio 2017 and Visual Studio Code make it easy to clone repositories from within your development environment. 21 | > See the [Visual Studio 2017](https://docs.microsoft.com/en-us/vsts/git/tutorial/clone?view=vsts&tabs=visual-studio#clone-from-another-git-provider) and [Visual Studio Code](https://code.visualstudio.com/docs/editor/versioncontrol#_cloning-a-repository) documentation for details. 22 | 23 | If you don't have Git installed, you can manually download a [standalone copy of the tutorials](https://github.com/Microsoft/MLADS2018-QuantumML/archive/master.zip). 24 | 25 | ## Tutorial Structure 26 | 27 | The tutorial contains the template of the algorithm which you will work on and the classical harness used for running your code. The project is laid out as below. 28 | 29 | ``` 30 | README.md # Tutorial instructions 31 | QuantumPerceptron/ 32 | QuantumPerceptron.sln # Visual Studio 2017 solution file. 33 | QuantumPerceptron.csproj # Project file used to build both classical and quantum code. 34 | 35 | QuantumClassifier.qs # Q# source code containing the template of the quantum perceptron. 36 | QuantumClassifier_Easy.qs # Q# source code containing the implementations of the quantum perceptron. 37 | ClassicalDriver.cs # C# source code used to load the data, invoke the Q# code and do classical processing. 38 | ``` 39 | 40 | To open the tutorial in Visual Studio 2017, open the `QuantumPerceptron.sln` solution file. 41 | 42 | To open the tutorial in Visual Studio Code, open the `QuantumPerceptron/` folder. 43 | Press Ctrl + Shift + P / ⌘ + Shift + P to open the Command Palette and type "Open Folder" on Windows 10 or Linux or "Open" on macOS. 44 | 45 | > **TIP**: Almost all commands available in Visual Studio Code can be found in the Command Palette. 46 | > If you ever get stuck, press Ctrl + Shfit + P / ⌘ + Shift + P and type some letters to search through all available commands. 47 | 48 | > **TIP**: You can also launch Visual Studio Code from the command line if you prefer: 49 | > ```bash 50 | > code QuantumPerceptron/ 51 | > ``` 52 | 53 | ## Working on the Tutorial 54 | 55 | Once you have the project open, you can build it and run it (`F5` in Visual Studio, `dotnet run` in Visual Studio Code terminal or command line). 56 | 57 | Initially the quantum code does nothing and always reports classification success rate of -1. 58 | Once you fill in the correct code in `QuantumClassifier.qs` file, the code will learn the model parameter which provides the best separation of the given classes. 59 | If you get stuck or run out of time and just want to see the model train, 60 | `QuantumClassifier_Easy.qs` file contains the full code for model training. You can look up the place in which you got stuck or switch to running the code in that file. 61 | 62 | As a stretch goal, try to implement the classical harness and the quantum classification circuit to generate new data and classify it using your trained model. 63 | 64 | ## Useful Links 65 | 66 | * You can find Q# language quick reference [here](./qsharp-quick-reference.pdf). 67 | 68 | 69 | * To improve your experience in the workshop, we suggest you to go through the BasicGates kata from the [Quantum Katas](https://github.com/Microsoft/QuantumKatas) project. 70 | It teaches you the basic gates used in quantum computing and helps you get more comfortable with Q#. 71 | Superposition and Measurement katas are the next best follow-up topics. 72 | 73 | * You can find the slides used in the introductory part of the workshop [here](./QuantumPerceptron.pptx). 74 | 75 | --- 76 | 77 | ## Contributing 78 | 79 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 80 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 81 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 82 | 83 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 84 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 85 | provided by the bot. You will only need to do this once across all repos using our CLA. 86 | 87 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 88 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 89 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 90 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /QuantumPerceptron/ClassicalDriver.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | //////////////////////////////////////////////////////////////////////////// 5 | // This file contains the classical code of the quantum perceptron 6 | // which loads the data, calls quantum classification routines 7 | // and performs search for model parameters. 8 | //////////////////////////////////////////////////////////////////////////// 9 | 10 | using Microsoft.Quantum.Simulation.Core; 11 | using Microsoft.Quantum.Simulation.Simulators; 12 | using System; 13 | 14 | namespace Microsoft.Quantum.MachineLearning 15 | { 16 | class ClassicalDriver 17 | { 18 | // Call quantum classification on the given training data for the given model parameter 19 | // and return its success rate. 20 | static double GetClassificationSuccessRate(double[] data, long[] labels, double angle) 21 | { 22 | double s = 0; 23 | using (var qsim = new QuantumSimulator(true, 123)) 24 | { 25 | // Change the following line to call QuantumClassifier_SuccessRate_Easy.Run to run pre-written model training code 26 | s = QuantumClassifier_SuccessRate.Run(qsim, angle, new QArray(data), new QArray(labels)).Result; 27 | } 28 | return s; 29 | } 30 | 31 | static void SaveAsCsv(double[] data, long[] labels) 32 | { 33 | string fileContents = "Label,Data" + Environment.NewLine; 34 | for (int i = 0; i < data.Length; ++i) 35 | { 36 | fileContents += labels[i] + "," + data[i].ToString("F4") + Environment.NewLine; 37 | } 38 | System.IO.File.WriteAllText("trainingData.csv", fileContents); 39 | } 40 | 41 | /// 42 | /// Create a data set in the range [0, 2π] with a gap of the given size at the given central angle 43 | /// and a symmetrical gap at the angle π + the given central angle. 44 | /// 45 | /// Number of random data points 46 | /// Where to create the gap 47 | /// Width of gap 48 | /// 49 | static double[] CreateSeparableDataset(int size, double center, double gap) 50 | { 51 | double[] data = new double[size]; 52 | Random rnd = new Random(123); 53 | 54 | double max = Math.PI; 55 | 56 | // These variables are used to create the gap 57 | double lowerMax = center - gap / 2.0; 58 | double upperScale = (max - center - gap / 2.0) / (max - center); 59 | 60 | for (int i = 0; i < size; i++) 61 | { 62 | // 1. Generate a random number without taking the gap into account 63 | data[i] = rnd.NextDouble() * max; 64 | 65 | // 2. Shift it to create the gap 66 | if (data[i] <= center) 67 | { 68 | // This is the simple case, just re-scale proportionally (3-simple rule) 69 | data[i] *= lowerMax / center; 70 | } 71 | else 72 | { 73 | // Slightly more complicated: invert, 3-simple rule to rescale, invert again 74 | data[i] = max - data[i]; 75 | data[i] *= upperScale; 76 | data[i] = max - data[i]; 77 | } 78 | 79 | // 3. Spread to the full circle (2π) -- we'll have two gaps 80 | if (rnd.Next(2) == 1) 81 | { 82 | data[i] += Math.PI; 83 | } 84 | } 85 | 86 | return data; 87 | } 88 | 89 | static void Main(string[] args) 90 | { 91 | // Larger dataset size gives more precise training result but slower training process 92 | int datasetSize = 200; 93 | 94 | // Prepare a perfectly separable training dataset 95 | double separationAngle = 2.0; 96 | double correctAngle = separationAngle - Math.PI / 2; 97 | double margin = 0.1; 98 | 99 | double[] data = CreateSeparableDataset(datasetSize, separationAngle, margin); 100 | 101 | // Assign labels to training data 102 | long[] labels = new long[datasetSize]; 103 | for (int i = 0; i < datasetSize; ++i) 104 | { 105 | labels[i] = (data[i] > separationAngle && data[i] < separationAngle + Math.PI ? 1 : 0); 106 | } 107 | 108 | // Save the training data to file 109 | // SaveAsCsv(data, labels); 110 | 111 | // Check classification success rate on the angle that we know to be correct 112 | Console.Out.WriteLine($"For correct angle {correctAngle.ToString("F3")} success rate = " + 113 | GetClassificationSuccessRate(data, labels, correctAngle)); 114 | 115 | long msStart = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; 116 | // Do a ternary search on the classification angle (we know that the angle is between 0 and 2*PI). 117 | // Normally we would apply a better technique, like gradient search, but a demo which runs fast enough lacks precision for those techniques. 118 | double l = 0.0, r = 2 * Math.PI; 119 | int iter = 0; 120 | while (Math.Abs(l-r) > margin) // stop when the length of the search interval is smaller than the margin 121 | { 122 | iter++; 123 | double m1 = l + (r - l) / 3; 124 | double m2 = r - (r - l) / 3; 125 | double s1 = GetClassificationSuccessRate(data, labels, m1); 126 | double s2 = GetClassificationSuccessRate(data, labels, m2); 127 | if (s1 <= s2) 128 | { 129 | l = m1; 130 | } else 131 | { 132 | r = m2; 133 | } 134 | Console.Out.WriteLine($"Iteration {iter}: angle {m1.ToString("F3")} -> {s1}, angle {m2.ToString("F3")} -> {s2}, narrowing search to [{l.ToString("F3")}, {r.ToString("F3")}]"); 135 | } 136 | 137 | // Report training results (learned model parameter and classification success rate for it) 138 | double s = GetClassificationSuccessRate(data, labels, (l+r)/2); 139 | Console.Out.WriteLine($"Training result: angle {((l+r)/2).ToString("F3")} -> {s}"); 140 | long msEnd = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; 141 | Console.Out.WriteLine("Training time " + (msEnd - msStart) / 1000.0); 142 | 143 | Console.WriteLine("Press any key to continue..."); 144 | Console.ReadKey(); 145 | 146 | //////////////////////////////////////////////////////////////////////// 147 | // Stretch goal: Write your own classifier! 148 | // 149 | // Now that you've trained your model, it's time to see how it performs on new data. 150 | // Generate new data following the same process as for the training data. 151 | // Write classification circuit QuantumClassifier following the suggestions in QuantumClassifier.qs. 152 | // Run it and compare classification results to the labels you assign when generating the data. 153 | //////////////////////////////////////////////////////////////////////// 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /QuantumPerceptron/QuantumClassifier_Easy.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | //////////////////////////////////////////////////////////////////////////// 5 | // This file contains the easy version of the workshop. 6 | // All the quantum code is already written, and you can run the program to see how it works. 7 | // To switch to this version, replace QuantumClassifier_SuccessRate in ClassicalDriver.cs 8 | // with QuantumClassifier_SuccessRate_Easy. 9 | // 10 | // We recommend you to try the harder version (QuantumClassifier.qs file), 11 | // where you have to write Q# model training code following prompts in the comments, 12 | // and eventually write the classifier code on your own. 13 | //////////////////////////////////////////////////////////////////////////// 14 | 15 | namespace Microsoft.Quantum.MachineLearning { 16 | 17 | open Microsoft.Quantum.Primitive; 18 | open Microsoft.Quantum.Canon; 19 | open Microsoft.Quantum.Extensions.Convert; 20 | 21 | 22 | //////////////////////////////////////////////////////////////////////// 23 | // Encoding circuit 24 | // 25 | // # Summary 26 | // Prepares two qubits in a state which represents a point in the training dataset. 27 | // # Inputs 28 | // data : The input vector (single floating-point number) 29 | // label : The input label (0 or 1) 30 | // dataQubit : The qubit to be prepared in a state which represents input vector 31 | // labelQubit : The qubit to be prepared in a state which represents the label 32 | // (|0⟩ or |1⟩ for labels 0 or 1, respectively) 33 | //////////////////////////////////////////////////////////////////////// 34 | operation EncodeDataInQubits_Easy ( 35 | data : Double, 36 | label : Int, 37 | dataQubit : Qubit, 38 | labelQubit : Qubit) : Unit { 39 | 40 | // Make sure both qubits start in |0⟩ state (you can use library operation Reset) 41 | Reset(dataQubit); 42 | Reset(labelQubit); 43 | 44 | // Encode the input vector in dataQubit state using Ry rotation gate. 45 | // Note that the rotation angle has to be exactly "data" to be consistent with the labels generation in Driver.cs 46 | Ry(data, dataQubit); 47 | 48 | // Encode the label in labelQubit state: |0⟩ or |1⟩ for labels 0 or 1 (you can use X gate to change qubit state |0⟩ to |1⟩) 49 | if (label == 1) { 50 | X(labelQubit); 51 | } 52 | } 53 | 54 | 55 | //////////////////////////////////////////////////////////////////////// 56 | // Single-shot single-point validation circuit 57 | // 58 | // # Summary 59 | // Classifies a data point encoded as a qubit and validates the result against the expected label. 60 | // # Inputs 61 | // alpha : The model parameter used for classification 62 | // dataQubit : The qubit which represents the input state 63 | // labelQubit : The qubit which represents the expected label of the input state 64 | // # Result 65 | // True if the data point has been classified correctly, 66 | // false if it has been misclassified. 67 | // 68 | // In classification scenario, the circuit will be the same, but the label qubit will always start in |0⟩ state, 69 | // and to get the classification result you'll measure it. 70 | //////////////////////////////////////////////////////////////////////// 71 | operation Validate_Easy ( 72 | alpha : Double, 73 | dataQubit : Qubit, 74 | labelQubit : Qubit) : Bool { 75 | 76 | // Rotate the state of the data qubit by -alpha; 77 | // this will get it close to the |0⟩ state if the data point belonged to class 0, 78 | // and to the |1⟩ state if the data point belonged to class 1 79 | Ry(-alpha, dataQubit); 80 | 81 | // Apply CNOT with data qubit as control and label qubit as target 82 | // to compute XOR of the expected label and the computed label on labelQubit 83 | CNOT(dataQubit, labelQubit); 84 | 85 | // Measure the label qubit in computational basis 86 | 87 | // If the measurement result is |0⟩, XOR of the expected label and the computed label is 0, 88 | // which means that the labels are the same and classification was correct. 89 | // Return the classification success 90 | return M(labelQubit) == Zero; 91 | } 92 | 93 | 94 | //////////////////////////////////////////////////////////////////////// 95 | // Full validation routine 96 | // 97 | // # Summary 98 | // Given the value of the model parameter (average rotation angle of the data points in class 0), 99 | // # Inputs 100 | // alpha : The model parameter used for classification 101 | // dataPoints : An array of training vectors (individual floating-point numbers) 102 | // labels : An array of training labels (0 or 1) 103 | // # Result 104 | // The success rate of classification for the given model parameter. 105 | //////////////////////////////////////////////////////////////////////// 106 | operation QuantumClassifier_SuccessRate_Easy ( 107 | alpha : Double, 108 | dataPoints : Double[], 109 | labels : Int[]) : Double { 110 | 111 | let N = Length(dataPoints); 112 | // The number of times each point is classified; larger values give higher accuracy but longer run time 113 | let nSamples = 201; 114 | // Define a mutable variable to store the number of correctly classified points in the dataset 115 | mutable nCorrectPoints = 0; 116 | 117 | // Allocate two qubits to be used in the classification 118 | using ((dataQubit, labelQubit) = (Qubit(), Qubit())) { 119 | 120 | // Iterate over all points of the dataset 121 | for (i in 0 .. N - 1) { 122 | 123 | // Define a mutable variable to store the number of successful classification runs 124 | mutable nCorrectClassificationRuns = 0; 125 | 126 | // Classify i-th data point by running classification circuit nSamples times 127 | for (j in 1 .. nSamples) { 128 | // Prepare data qubit and label qubit in a state which encodes the j-th data point 129 | EncodeDataInQubits_Easy(dataPoints[i], labels[i], dataQubit, labelQubit); 130 | 131 | // Run classification on the prepared qubits and count the runs when it succeeded 132 | if (Validate_Easy(alpha, dataQubit, labelQubit)) { 133 | set nCorrectClassificationRuns = nCorrectClassificationRuns + 1; 134 | } 135 | } 136 | 137 | // The point in the dataset has been classified correctly if 138 | // the share of runs on which classification succeeded is greater than 50%. 139 | if (nCorrectClassificationRuns * 2 > nSamples) { 140 | set nCorrectPoints = nCorrectPoints + 1; 141 | } 142 | } 143 | 144 | // Clean up both qubits before deallocating them using library operation Reset. 145 | Reset(dataQubit); 146 | Reset(labelQubit); 147 | } 148 | 149 | // Return the success rate of the classification (the percentage of points that have been classified correctly) 150 | // Note that you need ToDouble library function to convert integer numbers to doubles explicitly 151 | return ToDouble(nCorrectPoints) / ToDouble(N); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /QuantumPerceptron/QuantumClassifier.qs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. All rights reserved. 2 | // Licensed under the MIT license. 3 | 4 | //////////////////////////////////////////////////////////////////////////// 5 | // This file contains the main version of the workshop. 6 | // You have to write Q# model training code following prompts in the comments, 7 | // and eventually write the classifier code on your own. 8 | // 9 | // If you get stuck on some syntax or run out of time and just want to see the model train, 10 | // take a look at the QuantumClassifier_Easy.qs file - it contains the full code 11 | // for model training. 12 | //////////////////////////////////////////////////////////////////////////// 13 | 14 | namespace Microsoft.Quantum.MachineLearning { 15 | 16 | open Microsoft.Quantum.Primitive; 17 | open Microsoft.Quantum.Canon; 18 | open Microsoft.Quantum.Extensions.Convert; 19 | 20 | 21 | //////////////////////////////////////////////////////////////////////// 22 | // Encoding circuit 23 | // 24 | // # Summary 25 | // Prepares two qubits in a state which represents a point in the training dataset. 26 | // # Inputs 27 | // data : The input vector (single floating-point number) 28 | // label : The input label (0 or 1) 29 | // dataQubit : The qubit to be prepared in a state which represents input vector 30 | // labelQubit : The qubit to be prepared in a state which represents the label 31 | // (|0⟩ or |1⟩ for labels 0 or 1, respectively) 32 | //////////////////////////////////////////////////////////////////////// 33 | operation EncodeDataInQubits ( 34 | data : Double, 35 | label : Int, 36 | dataQubit : Qubit, 37 | labelQubit : Qubit) : Unit { 38 | 39 | // Make sure both qubits start in |0⟩ state (you can use library operation Reset) 40 | // ... 41 | 42 | // Encode the input vector in dataQubit state using Ry rotation gate. 43 | // Note that the rotation angle has to be exactly "data" to be consistent with the labels generation in Driver.cs 44 | // ... 45 | 46 | // Encode the label in labelQubit state: |0⟩ or |1⟩ for labels 0 or 1 (you can use X gate to change qubit state |0⟩ to |1⟩) 47 | // ... 48 | } 49 | 50 | 51 | //////////////////////////////////////////////////////////////////////// 52 | // Single-shot single-point validation circuit 53 | // 54 | // # Summary 55 | // Classifies a data point encoded as a qubit and validates the result against the expected label. 56 | // # Inputs 57 | // alpha : The model parameter used for classification 58 | // dataQubit : The qubit which represents the input state 59 | // labelQubit : The qubit which represents the expected label of the input state 60 | // # Result 61 | // True if the data point has been classified correctly, 62 | // false if it has been misclassified. 63 | // 64 | // In classification scenario, the circuit will be the same, but the label qubit will always start in |0⟩ state, 65 | // and to get the classification result you'll measure it. 66 | //////////////////////////////////////////////////////////////////////// 67 | operation Validate ( 68 | alpha : Double, 69 | dataQubit : Qubit, 70 | labelQubit : Qubit) : Bool { 71 | 72 | // Rotate the state of the data qubit by -alpha; 73 | // this will get it close to the |0⟩ state if the data point belonged to class 0, 74 | // and to the |1⟩ state if the data point belonged to class 1 75 | // ... 76 | 77 | // Apply CNOT with data qubit as control and label qubit as target 78 | // to compute XOR of the expected label and the computed label on labelQubit 79 | // ... 80 | 81 | // Measure the label qubit in computational basis 82 | // ... 83 | 84 | // If the measurement result is |0⟩, XOR of the expected label and the computed label is 0, 85 | // which means that the labels are the same and classification was correct. 86 | // Return the classification success 87 | return false; 88 | } 89 | 90 | 91 | //////////////////////////////////////////////////////////////////////// 92 | // Full validation routine 93 | // 94 | // # Summary 95 | // Given the value of the model parameter (average rotation angle of the data points in class 0), 96 | // # Inputs 97 | // alpha : The model parameter used for classification 98 | // dataPoints : An array of training vectors (individual floating-point numbers) 99 | // labels : An array of training labels (0 or 1) 100 | // # Result 101 | // The success rate of classification for the given model parameter. 102 | //////////////////////////////////////////////////////////////////////// 103 | operation QuantumClassifier_SuccessRate ( 104 | alpha : Double, 105 | dataPoints : Double[], 106 | labels : Int[]) : Double { 107 | 108 | let N = Length(dataPoints); 109 | // The number of times each point is classified; larger values give higher accuracy but longer run time 110 | let nSamples = 201; 111 | // Define a mutable variable to store the number of correctly classified points in the dataset 112 | // ... 113 | 114 | // Allocate two qubits to be used in the classification 115 | using ((dataQubit, labelQubit) = (Qubit(), Qubit())) { 116 | 117 | // Iterate over all points of the dataset 118 | for (i in 0 .. N - 1) { 119 | 120 | // Define a mutable variable to store the number of successful classification runs 121 | // ... 122 | 123 | // Classify i-th data point by running classification circuit nSamples times 124 | for (j in 1 .. nSamples) { 125 | // Prepare data qubit and label qubit in a state which encodes the j-th data point 126 | // ... 127 | 128 | // Run classification on the prepared qubits and count the runs when it succeeded 129 | // ... 130 | } 131 | 132 | // The point in the dataset has been classified correctly if 133 | // the share of runs on which classification succeeded is greater than 50%. 134 | // ... 135 | } 136 | 137 | // Clean up both qubits before deallocating them using library operation Reset. 138 | // ... 139 | } 140 | 141 | // Return the success rate of the classification (the percentage of points that have been classified correctly) 142 | // Note that you need ToDouble library function to convert integer numbers to doubles explicitly 143 | return -1.0; 144 | } 145 | 146 | //////////////////////////////////////////////////////////////////////// 147 | // Stretch goal: Write your own classifier! 148 | // 149 | // The classification logic is similar to the validation one: 150 | // to classify a point in a dataset, you encode it in a data qubit, 151 | // run classification circuit on it with label qubit in |0⟩ state and measure the label qubit; 152 | // repeat this enough times and return the classification outcome which you get more frequently. 153 | //////////////////////////////////////////////////////////////////////// 154 | operation QuantumClassifier ( 155 | alpha : Double, 156 | dataPoints : Double[]) : Int[] { 157 | 158 | // ... 159 | return new Int[0]; 160 | } 161 | } 162 | 163 | 164 | --------------------------------------------------------------------------------