-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPracticeModels.cpp
More file actions
68 lines (61 loc) · 2.28 KB
/
Copy pathPracticeModels.cpp
File metadata and controls
68 lines (61 loc) · 2.28 KB
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
/*
* @File : PracticeModels.cpp
* @Time : 2022/07/13
* @Author : Han Hui
* @Contact : clearhanhui@gmail.com
*/
#include "include/Lenet5.h"
#include <iostream>
int main() {
/// 下面是 LibTorch 的官方注释,另外需要注意运行的目录
/// c++我还没有找到一种能优雅的够获取当前绝对路径的方法
/// The supplied `root` path should contain the *content* of the unzipped
/// MNIST dataset, available from http://yann.lecun.com/exdb/mnist.
auto train_dataset =
torch::data::datasets::MNIST("../data/MNIST/raw",
torch::data::datasets::MNIST::Mode::kTrain)
.map(torch::data::transforms::Stack<>());
auto test_dataset =
torch::data::datasets::MNIST("../data/MNIST/raw",
torch::data::datasets::MNIST::Mode::kTest)
.map(torch::data::transforms::Stack<>());
auto train_loader =
torch::data::make_data_loader<torch::data::samplers::RandomSampler>(
std::move(train_dataset), 128);
auto test_loader =
torch::data::make_data_loader<torch::data::samplers::SequentialSampler>(
std::move(test_dataset), 128);
Lenet5 lenet5;
torch::optim::Adam adam(lenet5.parameters(), 0.001);
torch::nn::CrossEntropyLoss cross_entropy;
for (int i = 0; i < 5; i++) {
float total_loss = 0.0;
for (auto &batch : *train_loader) {
torch::Tensor x = batch.data;
torch::Tensor y = batch.target;
torch::Tensor y_prob = lenet5.forward(x);
torch::Tensor loss = cross_entropy(y_prob, y);
total_loss += loss.item<float>();
adam.zero_grad();
loss.backward();
adam.step();
}
std::cout << "Epoch " << i << " total_loss = " << total_loss << std::endl;
}
// torch::serialize::OutputArchive output_archive;
// lenet5.save(output_archive);
// output_archive.save_to("lenet5.pt");
lenet5.eval();
int correct = 0;
int total = 0;
for (auto &batch : *test_loader) {
torch::Tensor x = batch.data;
torch::Tensor y = batch.target;
torch::Tensor y_prob = lenet5.forward(x);
correct += y_prob.argmax(1).eq(y).sum().item<int>();
total += y.size(0);
}
std::cout << "Test Accuracy = " << (float)correct / (float)total * 100 << " %"
<< std::endl;
return 0;
}