forked from microsoft/Quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTraining.qs
95 lines (86 loc) · 3.14 KB
/
Training.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Microsoft.Quantum.Samples {
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 WithProductKernel(scale : Double, sample : Double[]) : Double[] {
return sample + [scale * Fold(TimesD, 1.0, sample)];
}
function Preprocessed(samples : Double[][]) : Double[][] {
let scale = 1.0;
return Mapped(
WithProductKernel(scale, _),
samples
);
}
function DefaultSchedule(samples : Double[][]) : SamplingSchedule {
return SamplingSchedule([
0..Length(samples) - 1
]);
}
function ClassifierStructure() : ControlledRotation[] {
return [
ControlledRotation((0, new Int[0]), PauliX, 4),
ControlledRotation((0, new Int[0]), PauliZ, 5),
ControlledRotation((1, new Int[0]), PauliX, 6),
ControlledRotation((1, new Int[0]), PauliZ, 7),
ControlledRotation((0, [1]), PauliX, 0),
ControlledRotation((1, [0]), PauliX, 1),
ControlledRotation((1, new Int[0]), PauliZ, 2),
ControlledRotation((1, new Int[0]), PauliX, 3)
];
}
operation TrainHalfMoonModelAtStartPoint(
trainingVectors : Double[][],
trainingLabels : Int[],
startPoint : Double[]
) : (Double[], Double, Int) {
let samples = Mapped(
LabeledSample,
Zipped(Preprocessed(trainingVectors), trainingLabels)
);
let options = DefaultTrainingOptions()
w/ LearningRate <- 0.1
w/ MinibatchSize <- 15
w/ Tolerance <- 0.005
w/ NMeasurements <- 10000
w/ MaxEpochs <- 2
w/ VerboseMessage <- Message;
Message("Ready to train.");
// Train at the given start point, and get back an
// optimized model.
let (optimizedModel, nMisses) = TrainSequentialClassifierAtModel(
SequentialModel(ClassifierStructure(), startPoint, 0.0),
samples,
options,
DefaultSchedule(trainingVectors),
DefaultSchedule(trainingVectors)
);
return (optimizedModel::Parameters, optimizedModel::Bias, nMisses);
}
operation ValidateHalfMoonModel(
validationVectors : Double[][],
validationLabels : Int[],
parameters : Double[],
bias : Double
) : Double {
let samples = Mapped(
LabeledSample,
Zipped(Preprocessed(validationVectors), validationLabels)
);
let tolerance = 0.005;
let nMeasurements = 10000;
let results = ValidateSequentialClassifier(
SequentialModel(ClassifierStructure(), parameters, bias),
samples,
tolerance,
nMeasurements,
DefaultSchedule(validationVectors)
);
return IntAsDouble(results::NMisclassifications) / IntAsDouble(Length(samples));
}
}