以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()
效果