## AWS Quantum Technologies Blog

# Quantum Machine Learning on QC Ware Forge built on Amazon Braket

*By Fabio Sanches, Quantum Computing Services Lead, QC Ware*

In this post, I introduce you to QC Ware Forge, which is built on Amazon Braket. It provides turnkey quantum algorithms, so you can speed up research into applying quantum computing to hard data science problems. I also walk you through an example of using Forge with Amazon Braket to solve a quantum machine learning classification problem.

**The Quantum Computing Opportunity**

Theoretical work on quantum algorithms suggests they will eventually be significantly faster than their classical counterparts. However, quantum computing has yet to demonstrate a practical advantage for enterprise applications, and it will likely take a few more iterations in quantum computing hardware until it does.

So why should you care about quantum computing software before quantum hardware matures? Despite the fact that the technology is still early in its lifecycle, enterprises are aware of the potential quantum computing has. Many corporations and researchers want to prepare, engage, and learn about quantum computing, and have also recognized the challenges that come with it.

It’s likely that the early advantages provided by quantum computing will require careful formulation of use cases, clever tricks in algorithm design, as well as effective hardware implementations. Finding the right use case, building the (internal) knowledge base, and converting existing processes into ones that leverage the results of quantum computing takes time, even with in-house expertise.

Customers often need help in developing or adapting existing quantum algorithms for their specific use cases such as portfolio optimization, scheduling, classification and clustering for images and fraud detection, derivative pricing, drug discovery, and material design. Having access to the right algorithms is a critical part of understanding the expected performance of quantum hardware, helping guide business units on how to invest in the technology effectively. Motivated by these challenges, the team at QC Ware built Forge.

**QC Ware Forge**

QC Ware Forge is a SaaS quantum computing software platform that provides turnkey quantum algorithm implementations. You can think of Forge as a platform for data science powered by quantum computers, and use Forge’s collection of algorithms in business applications. Forge also provides an on-demand environment for quantum computing experts to access the quantum computing stack.

This application stack is in many ways similar to a classical computing stack. Applications that interface with business users sit on top, which are powered by algorithms written in one of many languages. These are eventually compiled to machine language.

Customers work with Forge’s algorithms for binary optimization, linear algebra, and machine learning to power applications in industries such as financial services, automotive, energy, pharmaceuticals, and manufacturing. You can also optionally use QC Ware middleware for editing quantum circuits and translating between different quantum computing libraries.

**QC Ware and AWS**

Negotiating access to quantum computers, connecting to them, and managing different interfaces can be quite burdensome. In addition customers typically want to avoid long contracts. By using Forge with Amazon Braket, you can use quantum computing hardware and cloud-based simulators with a consistent on-demand pricing model for these resources. In addition to integrating with Amazon Braket, QC Ware also uses AWS to host Forge’s classical computing infrastructure including Forge’s CPU and GPU simulators and classical algorithms.

**Solving a classification problem using a quantum machine learning algorithm in Forge with Amazon Braket**

Now, let’s walk through an example that demonstrates Forge’s quantum machine learning (QML) functionality and show some of the features of Amazon Braket that Forge uses.

You may have regression, classification, and clustering data science problems, such as a need to classify customers across different groups to provide recommendations, classify certain events as fraudulent, or medical imaging classification. The `fit_and_predict`

function in Forge can be useful for applications of this form*. *It leverages Forge’s QML distance estimation capabilities shown in the stack depicted in Figure 1.

We built `fit_and_predict`

to mirror the functionality provided by scikit-learn, a popular machine learning library. While the interface is similar, the underlying algorithm powering the classifiers (along with regression and clustering procedures) leverages quantum circuits for certain important computations in the fitting or classification steps.

In many cases, linear algebra computations can be done in fewer steps on a quantum computer. In this case, `fit_and_predict`

leverages the quantum distance estimation algorithm, which estimates distances with a number of steps that scales logarithmically with the dimensionality of the vectors, compared to scaling linearly with classical systems. This means that for classification tasks with vectors of a sufficiently high dimension, quantum computers could in time perform the classification task faster, when they have enough high-quality qubits.

The extra element powering `fit_and_predict`

are Data Loaders developed by QC Ware. These loaders allow us to effectively encode the classical information into the quantum state, a step needed prior to the quantum distance estimation. This step will be very important across many quantum machine learning applications such as image recognition, recommendation systems, fraud detection.

**Prerequisites**

To do this exercise, you will need a QC Ware Forge account. Anyone can sign up for a free trial, which comes with 1 minute of Forge credits. This is enough to try out this feature using simulators inside of Forge. Quantum hardware runs may require a subscription, depending on the size of the problem.

**To get started with Forge**

- Sign into Forge on qcware.com. All of the following procedures and steps happen inside Forge.
- Once inside Forge, select the Jupyter Notebooks section from the menu on the left. All Forge accounts, including trials, have access to a collection of our demo Notebooks.

Now, to see this in action, you can run a classification task.

**To run a classification task with the fit_and_predict function**

- In Forge, create a new notebook (File -> New -> Notebook).
- Import the
`fit_and_predict`

function from the qcware qml library. - Set the API key.

Enter the code below to accomplish this:

```
import qcware
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestCentroid
qcware.config.set_api_key('Paste your key here')
```

**To generate data**

For this demo, I generate some random 2-dimensional points for simplicity, shown below in Figure 4. In this case, the x coordinates will have different means so the clusters are more nicely separated. The first variable is the coordinates of the points, the second variable is the labels, and the third variable is the coordinates of the unlabeled points I’d like to classify. You’re welcome to try it out with similar data you have, or import a data set, from Kaggle for instance.

Enter the following commands to generate data.

```
# Data generation
coordinates = 0.25 * np.random.randn(15, 2) + \
[[i // 5 - 1, 0] for i in range(15)]
labels = np.array([i // 5 for i in range(15)])
unclassified_coordinates = np.random.randn(10, 2)
```

You now have everything you need to test out your classifier powered by a quantum algorithm!

**To test the classifier**

Call `fit_and_predict` and pass the data:

```
quantum_result = qcware.qml.fit_and_predict(
coordinates,
y=labels,
T=unclassified_coordinates,
model='QNearestCentroid',
backend='qcware/cpu_simulator')
```

The first two parameters correspond to the coordinates and the labels for the dataset used to determine the centroid. The T parameter corresponds to the unlabeled data you are classifying. The `model`

parameter lets you select the classification algorithm you are using. Here `"QNearestCentroid"`

is simply the Nearest Centroid algorithm, which outputs the label of the centroid (i.e. mean coordinates of each group in the training data) closest to the point being classified. In addition to finding the Nearest Centroid, `fit_and_predict`

also currently supports quantum versions of k-Nearest Neighbors (regressor and classifier) as well as k-means for unsupervised learning. The QML demo notebooks in Forge show examples of these.

The backend parameter corresponds to the hardware that will run the quantum circuits powering the algorithm. I’ll discuss backend parameters shortly.

Now, let’s visualize the assigned labels.

**To visualize the assigned labels**

Enter the commands below to plot the original data along with the classification results.

```
plt.scatter(unclassified_coordinates[:,0],
unclassified_coordinates[:,1],
c = quantum_result,
label='Classified by QNearestCentroid')
plt.scatter(coordinates[:,0],
coordinates[:,1], c = labels,
marker='x', label='Data used in fitting')
plt.legend()
plt.axis('tight')
plt.title('QNearestCentroid Result')
plt.tight_layout()
plt.show()
```

**Backends on Forge**

The backend parameter in the `fit_and_predict`

Forge call noted above corresponds to the hardware that will run the quantum circuits powering the algorithm. In this case, I set it to `"qcware/cpu_simulator"`

, which means that I am simulating the quantum circuit using a regular CPU for the simulation. Circuit simulation is very valuable in designing quantum algorithms and testing code. It doesn’t consume time on quantum hardware, and it does not suffer from noise (unless you want to simulate noise, of course).

Forge also leverages Amazon Braket to provide on-demand access to a collection of quantum computers including D-Wave, IonQ, and Rigetti, and managed simulators.

**(Optional) To view Backends available on Forge **

- Click on the Backends button on the left menu to see the Backends that are available on Forge.

**(Optional) Change Backend to use IonQ hardware**

You can easily change the backend parameter to submit the task to another simulator or quantum computer. Note that if you use Forge to submit tasks to Amazon Braket’s quantum computer backends, you will be charged for your usage based on Forge’s pricing. Let’s try the IonQ hardware. The IonQ hardware is only available during certain windows. For tasks submitted outside the availability windows, Forge automatically schedules your task for the next available slot, and provides a key to retrieve the result when ready.

- Make the
`fit-and-predict`

call again, as shown below. This is the same as what you did above, but you need a different backend parameter:`"awsbraket/ionq"`

```
qcware.config.set_scheduling_mode("next_available")
ionq_result = qcware.qml.fit_and_predict(
coordinates,y=labels,T=unclassified_coordinates,
model='QNearestCentroid',backend='awsbraket/ionq',
parameters={'num_measurements':100}
)
```

2. Plot the results and original labels.

`# plot IonQ result plt.scatter(unclassified_coordinates[:,0], unclassified_coordinates[:,1], c = ionq_result,`

`label='QNearestCentroid on IonQ') plt.scatter(coordinates[:,0], coordinates[:,1], c = labels, marker='x', label='Data used in fitting') plt.legend() plt.axis('tight') plt.title('QNearestCentroid Result on IonQ') plt.tight_layout() plt.show()`

## Conclusion

In this post, I showed how you can use QC Ware Forge for a quantum machine learning ‘fit-and-predict’ problem with Amazon Braket. QC Ware designed Forge to provide users with performant quantum algorithms across relevant domains. In addition to the QML functionality, Forge currently provides core capabilities in optimization and linear algebra. It also provides quantum circuit simulation features for users already familiar with building quantum circuits or who want to learn more about quantum algorithm design.

You can sign up for a free trial of Forge at forge.qcware.com. Please review the pricing details of the trial, as use of hardware backends may exceed the credits available in the Forge trial. Look through the demo notebooks for more examples of the QML functionality that I’ve demonstrated, along with notebooks for QC Ware optimization and circuit simulation capabilities, including examples of applications such as portfolio optimization and job shop scheduling.

*The content and opinions in this post are those of the third-party author and AWS is not responsible for the content or accuracy of this post.*