PennyLane 量子神经网络QNN预测sin函数

以sin函数为例,使用QNN预测时间序列数据

https://pennylane.ai/qml/demos/quantum_neural_net.html#sphx-glr-demos-quantum-neural-net-py

安装

pip install pennylane
pip install pennylane-sf

代码

import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import AdamOptimizer

import matplotlib.pyplot as plt
import numpy as np

noise = np.random.normal(0,0.1,100)
X = np.arange(-5, 5, 0.1)
Y = np.sin(X)+noise

# plt.plot(X[0:200], Y[0:200])
# plt.show()

dev = qml.device("strawberryfields.fock", wires=1, cutoff_dim=10)

def layer(v):
    qml.Rotation(v[0], wires=0)
    qml.Squeezing(v[1], 0.0, wires=0)
    qml.Rotation(v[2], wires=0)
    qml.Displacement(v[3], 0.0, wires=0)
    qml.Kerr(v[4], wires=0)

@qml.qnode(dev)
def quantum_neural_net(var, x=None):
    qml.Displacement(x, 0.0, wires=0)
    for v in var:
        layer(v)
    return qml.expval(qml.X(0))

def square_loss(labels, predictions):
    loss = 0
    for l, p in zip(labels, predictions):
        loss = loss + (l - p) ** 2
    loss = loss / len(labels)
    return loss

def cost(var, features, labels):
    preds = [quantum_neural_net(var, x) for x in features]
    return square_loss(labels, preds)

num_layers = 4
var = 0.05 * np.random.randn(num_layers, 5)
opt = AdamOptimizer(0.01, beta1=0.9, beta2=0.999)

for it in range(10):
    var = opt.step(lambda v: cost(v, X, Y), var)
    print("Iter: {:5d} | Cost: {:0.7f} ".format(it + 1, cost(var, X, Y)))

predictions = [quantum_neural_net(var, x=x_) for x_ in X]

plt.figure()
plt.plot(X, Y)
plt.plot(X, predictions, color="red")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.show()

效果

在这里插入图片描述
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值