forked from microsoft/QuantumKatas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backend.qs
80 lines (71 loc) · 2.94 KB
/
Backend.qs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//////////////////////////////////////////////////////////////////////
// This file contains implementations of training and classification routines
// used in part 1 of the tutorial ("Exploring Quantum Classification Library").
// You should not modify anything in this file.
//////////////////////////////////////////////////////////////////////
namespace Microsoft.Quantum.Kata.QuantumClassification {
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.MachineLearning;
open Microsoft.Quantum.Math;
function DefaultSchedule(samples : Double[][]) : SamplingSchedule {
return SamplingSchedule([
0..Length(samples) - 1
]);
}
// The definition of classifier structure for the case when the data is linearly separable and fits into 1 qubit
function ClassifierStructure() : ControlledRotation[] {
return [
ControlledRotation((0, new Int[0]), PauliY, 0)
];
}
// Entry point for training a model; takes the data as the input and uses hard-coded classifier structure.
operation TrainLinearlySeparableModel(
trainingVectors : Double[][],
trainingLabels : Int[],
initialParameters : Double[][]
) : (Double[], Double) {
// convert training data and labels into a single data structure
let samples = Mapped(
LabeledSample,
Zip(trainingVectors, trainingLabels)
);
let (optimizedModel, nMisses) = TrainSequentialClassifier(
Mapped(
SequentialModel(ClassifierStructure(), _, 0.0),
initialParameters
),
samples,
DefaultTrainingOptions()
w/ LearningRate <- 2.0
w/ Tolerance <- 0.0005,
DefaultSchedule(trainingVectors),
DefaultSchedule(trainingVectors)
);
Message($"Training complete, found optimal parameters: {optimizedModel::Parameters}, {optimizedModel::Bias} with {nMisses} misses");
return (optimizedModel::Parameters, optimizedModel::Bias);
}
// Entry point for using the model to classify the data; takes validation data and model parameters as inputs and uses hard-coded classifier structure.
operation ClassifyLinearlySeparableModel(
samples : Double[][],
parameters : Double[],
bias : Double,
tolerance : Double,
nMeasurements : Int
)
: Int[] {
let model = Default<SequentialModel>()
w/ Structure <- ClassifierStructure()
w/ Parameters <- parameters
w/ Bias <- bias;
let probabilities = EstimateClassificationProbabilities(
tolerance, model,
samples, nMeasurements
);
return InferredLabels(model::Bias, probabilities);
}
}