| 138 | } |
| 139 | |
| 140 | void Train(int num_epoch, string data_dir) { |
| 141 | Cifar10 data(data_dir); |
| 142 | Tensor train_x, train_y, test_x, test_y; |
| 143 | { |
| 144 | auto train = data.ReadTrainData(); |
| 145 | size_t nsamples = train.first.shape(0); |
| 146 | auto mtrain = |
| 147 | Reshape(train.first, Shape{nsamples, train.first.Size() / nsamples}); |
| 148 | const Tensor& mean = Average(mtrain, 0); |
| 149 | SubRow(mean, &mtrain); |
| 150 | train_x = Reshape(mtrain, train.first.shape()); |
| 151 | train_y = train.second; |
| 152 | auto test = data.ReadTestData(); |
| 153 | nsamples = test.first.shape(0); |
| 154 | auto mtest = |
| 155 | Reshape(test.first, Shape{nsamples, test.first.Size() / nsamples}); |
| 156 | SubRow(mean, &mtest); |
| 157 | test_x = Reshape(mtest, test.first.shape()); |
| 158 | test_y = test.second; |
| 159 | } |
| 160 | CHECK_EQ(train_x.shape(0), train_y.shape(0)); |
| 161 | CHECK_EQ(test_x.shape(0), test_y.shape(0)); |
| 162 | LOG(INFO) << "Training samples = " << train_y.shape(0) |
| 163 | << ", Test samples = " << test_y.shape(0); |
| 164 | auto net = CreateNet(); |
| 165 | SGD sgd; |
| 166 | OptimizerConf opt_conf; |
| 167 | opt_conf.set_momentum(0.9); |
| 168 | auto reg = opt_conf.mutable_regularizer(); |
| 169 | reg->set_coefficient(0.004); |
| 170 | sgd.Setup(opt_conf); |
| 171 | sgd.SetLearningRateGenerator([](int step) { |
| 172 | if (step <= 120) |
| 173 | return 0.001; |
| 174 | else if (step <= 130) |
| 175 | return 0.0001; |
| 176 | else |
| 177 | return 0.00001; |
| 178 | }); |
| 179 | |
| 180 | SoftmaxCrossEntropy loss; |
| 181 | Accuracy acc; |
| 182 | net.Compile(true, &sgd, &loss, &acc); |
| 183 | #ifdef USE_CUDNN |
| 184 | auto dev = std::make_shared<CudaGPU>(); |
| 185 | net.ToDevice(dev); |
| 186 | train_x.ToDevice(dev); |
| 187 | train_y.ToDevice(dev); |
| 188 | test_x.ToDevice(dev); |
| 189 | test_y.ToDevice(dev); |
| 190 | #endif // USE_CUDNN |
| 191 | net.Train(100, num_epoch, train_x, train_y, test_x, test_y); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | int main(int argc, char **argv) { |
no test coverage detected