parent
c852b91647
commit
bc563c642c
@ -0,0 +1,97 @@
|
|||||||
|
Global:
|
||||||
|
use_gpu: true
|
||||||
|
epoch_num: 100
|
||||||
|
log_smooth_window: 20
|
||||||
|
print_batch_step: 10
|
||||||
|
save_model_dir: ./output/cls/mv3/
|
||||||
|
save_epoch_step: 3
|
||||||
|
# evaluation is run every 5000 iterations after the 4000th iteration
|
||||||
|
eval_batch_step: [0, 1000]
|
||||||
|
# if pretrained_model is saved in static mode, load_static_weights must set to True
|
||||||
|
load_static_weights: True
|
||||||
|
cal_metric_during_train: True
|
||||||
|
pretrained_model:
|
||||||
|
checkpoints:
|
||||||
|
save_inference_dir:
|
||||||
|
use_visualdl: False
|
||||||
|
infer_img: doc/imgs_words_en/word_10.png
|
||||||
|
label_list: ['0','180']
|
||||||
|
|
||||||
|
Architecture:
|
||||||
|
model_type: cls
|
||||||
|
algorithm: CLS
|
||||||
|
Transform:
|
||||||
|
Backbone:
|
||||||
|
name: MobileNetV3
|
||||||
|
scale: 0.35
|
||||||
|
model_name: small
|
||||||
|
Neck:
|
||||||
|
Head:
|
||||||
|
name: ClsHead
|
||||||
|
class_dim: 2
|
||||||
|
|
||||||
|
Loss:
|
||||||
|
name: ClsLoss
|
||||||
|
|
||||||
|
Optimizer:
|
||||||
|
name: Adam
|
||||||
|
beta1: 0.9
|
||||||
|
beta2: 0.999
|
||||||
|
lr:
|
||||||
|
name: Cosine
|
||||||
|
learning_rate: 0.001
|
||||||
|
regularizer:
|
||||||
|
name: 'L2'
|
||||||
|
factor: 0
|
||||||
|
|
||||||
|
PostProcess:
|
||||||
|
name: ClsPostProcess
|
||||||
|
|
||||||
|
Metric:
|
||||||
|
name: ClsMetric
|
||||||
|
main_indicator: acc
|
||||||
|
|
||||||
|
Train:
|
||||||
|
dataset:
|
||||||
|
name: SimpleDataSet
|
||||||
|
data_dir: ./train_data/cls
|
||||||
|
label_file_list:
|
||||||
|
- ./train_data/cls/train.txt
|
||||||
|
transforms:
|
||||||
|
- DecodeImage: # load image
|
||||||
|
img_mode: BGR
|
||||||
|
channel_first: False
|
||||||
|
- ClsLabelEncode: # Class handling label
|
||||||
|
- RecAug:
|
||||||
|
use_tia: False
|
||||||
|
- RandAugment:
|
||||||
|
- ClsResizeImg:
|
||||||
|
image_shape: [3, 48, 192]
|
||||||
|
- KeepKeys:
|
||||||
|
keep_keys: ['image', 'label'] # dataloader will return list in this order
|
||||||
|
loader:
|
||||||
|
shuffle: True
|
||||||
|
batch_size_per_card: 512
|
||||||
|
drop_last: True
|
||||||
|
num_workers: 8
|
||||||
|
|
||||||
|
Eval:
|
||||||
|
dataset:
|
||||||
|
name: SimpleDataSet
|
||||||
|
data_dir: ./train_data/cls
|
||||||
|
label_file_list:
|
||||||
|
- ./train_data/cls/test.txt
|
||||||
|
transforms:
|
||||||
|
- DecodeImage: # load image
|
||||||
|
img_mode: BGR
|
||||||
|
channel_first: False
|
||||||
|
- ClsLabelEncode: # Class handling label
|
||||||
|
- ClsResizeImg:
|
||||||
|
image_shape: [3, 48, 192]
|
||||||
|
- KeepKeys:
|
||||||
|
keep_keys: ['image', 'label'] # dataloader will return list in this order
|
||||||
|
loader:
|
||||||
|
shuffle: False
|
||||||
|
drop_last: False
|
||||||
|
batch_size_per_card: 512
|
||||||
|
num_workers: 4
|
@ -0,0 +1,96 @@
|
|||||||
|
Global:
|
||||||
|
use_gpu: true
|
||||||
|
epoch_num: 72
|
||||||
|
log_smooth_window: 20
|
||||||
|
print_batch_step: 10
|
||||||
|
save_model_dir: ./output/rec/r34_vd_none_bilstm_ctc/
|
||||||
|
save_epoch_step: 3
|
||||||
|
# evaluation is run every 5000 iterations after the 4000th iteration
|
||||||
|
eval_batch_step: [0, 2000]
|
||||||
|
# if pretrained_model is saved in static mode, load_static_weights must set to True
|
||||||
|
cal_metric_during_train: True
|
||||||
|
pretrained_model:
|
||||||
|
checkpoints:
|
||||||
|
save_inference_dir:
|
||||||
|
use_visualdl: False
|
||||||
|
infer_img: doc/imgs_words/ch/word_1.jpg
|
||||||
|
# for data or label process
|
||||||
|
character_dict_path:
|
||||||
|
character_type: en
|
||||||
|
max_text_length: 25
|
||||||
|
infer_mode: False
|
||||||
|
use_space_char: False
|
||||||
|
|
||||||
|
|
||||||
|
Optimizer:
|
||||||
|
name: Adam
|
||||||
|
beta1: 0.9
|
||||||
|
beta2: 0.999
|
||||||
|
lr:
|
||||||
|
learning_rate: 0.0005
|
||||||
|
regularizer:
|
||||||
|
name: 'L2'
|
||||||
|
factor: 0
|
||||||
|
|
||||||
|
Architecture:
|
||||||
|
model_type: rec
|
||||||
|
algorithm: CRNN
|
||||||
|
Transform:
|
||||||
|
Backbone:
|
||||||
|
name: ResNet
|
||||||
|
layers: 34
|
||||||
|
Neck:
|
||||||
|
name: SequenceEncoder
|
||||||
|
encoder_type: rnn
|
||||||
|
hidden_size: 256
|
||||||
|
Head:
|
||||||
|
name: CTCHead
|
||||||
|
fc_decay: 0
|
||||||
|
|
||||||
|
Loss:
|
||||||
|
name: CTCLoss
|
||||||
|
|
||||||
|
PostProcess:
|
||||||
|
name: CTCLabelDecode
|
||||||
|
|
||||||
|
Metric:
|
||||||
|
name: RecMetric
|
||||||
|
main_indicator: acc
|
||||||
|
|
||||||
|
Train:
|
||||||
|
dataset:
|
||||||
|
name: LMDBDateSet
|
||||||
|
data_dir: ./train_data/data_lmdb_release/training/
|
||||||
|
transforms:
|
||||||
|
- DecodeImage: # load image
|
||||||
|
img_mode: BGR
|
||||||
|
channel_first: False
|
||||||
|
- CTCLabelEncode: # Class handling label
|
||||||
|
- RecResizeImg:
|
||||||
|
image_shape: [3, 32, 100]
|
||||||
|
- KeepKeys:
|
||||||
|
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
|
||||||
|
loader:
|
||||||
|
shuffle: False
|
||||||
|
batch_size_per_card: 256
|
||||||
|
drop_last: True
|
||||||
|
num_workers: 8
|
||||||
|
|
||||||
|
Eval:
|
||||||
|
dataset:
|
||||||
|
name: LMDBDateSet
|
||||||
|
data_dir: ./train_data/data_lmdb_release/validation/
|
||||||
|
transforms:
|
||||||
|
- DecodeImage: # load image
|
||||||
|
img_mode: BGR
|
||||||
|
channel_first: False
|
||||||
|
- CTCLabelEncode: # Class handling label
|
||||||
|
- RecResizeImg:
|
||||||
|
image_shape: [3, 32, 100]
|
||||||
|
- KeepKeys:
|
||||||
|
keep_keys: ['image', 'label', 'length'] # dataloader will return list in this order
|
||||||
|
loader:
|
||||||
|
shuffle: False
|
||||||
|
drop_last: False
|
||||||
|
batch_size_per_card: 256
|
||||||
|
num_workers: 4
|
@ -0,0 +1,81 @@
|
|||||||
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
#include "opencv2/core.hpp"
|
||||||
|
#include "opencv2/imgcodecs.hpp"
|
||||||
|
#include "opencv2/imgproc.hpp"
|
||||||
|
#include "paddle_api.h"
|
||||||
|
#include "paddle_inference_api.h"
|
||||||
|
#include <chrono>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <ostream>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <fstream>
|
||||||
|
#include <numeric>
|
||||||
|
|
||||||
|
#include <include/preprocess_op.h>
|
||||||
|
#include <include/utility.h>
|
||||||
|
|
||||||
|
namespace PaddleOCR {
|
||||||
|
|
||||||
|
class Classifier {
|
||||||
|
public:
|
||||||
|
explicit Classifier(const std::string &model_dir, const bool &use_gpu,
|
||||||
|
const int &gpu_id, const int &gpu_mem,
|
||||||
|
const int &cpu_math_library_num_threads,
|
||||||
|
const bool &use_mkldnn, const bool &use_zero_copy_run,
|
||||||
|
const double &cls_thresh) {
|
||||||
|
this->use_gpu_ = use_gpu;
|
||||||
|
this->gpu_id_ = gpu_id;
|
||||||
|
this->gpu_mem_ = gpu_mem;
|
||||||
|
this->cpu_math_library_num_threads_ = cpu_math_library_num_threads;
|
||||||
|
this->use_mkldnn_ = use_mkldnn;
|
||||||
|
this->use_zero_copy_run_ = use_zero_copy_run;
|
||||||
|
|
||||||
|
this->cls_thresh = cls_thresh;
|
||||||
|
|
||||||
|
LoadModel(model_dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load Paddle inference model
|
||||||
|
void LoadModel(const std::string &model_dir);
|
||||||
|
|
||||||
|
cv::Mat Run(cv::Mat &img);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::shared_ptr<PaddlePredictor> predictor_;
|
||||||
|
|
||||||
|
bool use_gpu_ = false;
|
||||||
|
int gpu_id_ = 0;
|
||||||
|
int gpu_mem_ = 4000;
|
||||||
|
int cpu_math_library_num_threads_ = 4;
|
||||||
|
bool use_mkldnn_ = false;
|
||||||
|
bool use_zero_copy_run_ = false;
|
||||||
|
double cls_thresh = 0.5;
|
||||||
|
|
||||||
|
std::vector<float> mean_ = {0.5f, 0.5f, 0.5f};
|
||||||
|
std::vector<float> scale_ = {1 / 0.5f, 1 / 0.5f, 1 / 0.5f};
|
||||||
|
bool is_scale_ = true;
|
||||||
|
|
||||||
|
// pre-process
|
||||||
|
ClsResizeImg resize_op_;
|
||||||
|
Normalize normalize_op_;
|
||||||
|
Permute permute_op_;
|
||||||
|
|
||||||
|
}; // class Classifier
|
||||||
|
|
||||||
|
} // namespace PaddleOCR
|
@ -0,0 +1,108 @@
|
|||||||
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
#include <include/ocr_cls.h>
|
||||||
|
|
||||||
|
namespace PaddleOCR {
|
||||||
|
|
||||||
|
cv::Mat Classifier::Run(cv::Mat &img) {
|
||||||
|
cv::Mat src_img;
|
||||||
|
img.copyTo(src_img);
|
||||||
|
cv::Mat resize_img;
|
||||||
|
|
||||||
|
std::vector<int> cls_image_shape = {3, 48, 192};
|
||||||
|
int index = 0;
|
||||||
|
float wh_ratio = float(img.cols) / float(img.rows);
|
||||||
|
|
||||||
|
this->resize_op_.Run(img, resize_img, cls_image_shape);
|
||||||
|
|
||||||
|
this->normalize_op_.Run(&resize_img, this->mean_, this->scale_,
|
||||||
|
this->is_scale_);
|
||||||
|
|
||||||
|
std::vector<float> input(1 * 3 * resize_img.rows * resize_img.cols, 0.0f);
|
||||||
|
|
||||||
|
this->permute_op_.Run(&resize_img, input.data());
|
||||||
|
|
||||||
|
// Inference.
|
||||||
|
if (this->use_zero_copy_run_) {
|
||||||
|
auto input_names = this->predictor_->GetInputNames();
|
||||||
|
auto input_t = this->predictor_->GetInputTensor(input_names[0]);
|
||||||
|
input_t->Reshape({1, 3, resize_img.rows, resize_img.cols});
|
||||||
|
input_t->copy_from_cpu(input.data());
|
||||||
|
this->predictor_->ZeroCopyRun();
|
||||||
|
} else {
|
||||||
|
paddle::PaddleTensor input_t;
|
||||||
|
input_t.shape = {1, 3, resize_img.rows, resize_img.cols};
|
||||||
|
input_t.data =
|
||||||
|
paddle::PaddleBuf(input.data(), input.size() * sizeof(float));
|
||||||
|
input_t.dtype = PaddleDType::FLOAT32;
|
||||||
|
std::vector<paddle::PaddleTensor> outputs;
|
||||||
|
this->predictor_->Run({input_t}, &outputs, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<float> softmax_out;
|
||||||
|
std::vector<int64_t> label_out;
|
||||||
|
auto output_names = this->predictor_->GetOutputNames();
|
||||||
|
auto softmax_out_t = this->predictor_->GetOutputTensor(output_names[0]);
|
||||||
|
auto softmax_shape_out = softmax_out_t->shape();
|
||||||
|
|
||||||
|
int softmax_out_num =
|
||||||
|
std::accumulate(softmax_shape_out.begin(), softmax_shape_out.end(), 1,
|
||||||
|
std::multiplies<int>());
|
||||||
|
|
||||||
|
softmax_out.resize(softmax_out_num);
|
||||||
|
|
||||||
|
softmax_out_t->copy_to_cpu(softmax_out.data());
|
||||||
|
|
||||||
|
float score = 0;
|
||||||
|
int label = 0;
|
||||||
|
for (int i = 0; i < softmax_out_num; i++) {
|
||||||
|
if (softmax_out[i] > score) {
|
||||||
|
score = softmax_out[i];
|
||||||
|
label = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (label % 2 == 1 && score > this->cls_thresh) {
|
||||||
|
cv::rotate(src_img, src_img, 1);
|
||||||
|
}
|
||||||
|
return src_img;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Classifier::LoadModel(const std::string &model_dir) {
|
||||||
|
AnalysisConfig config;
|
||||||
|
config.SetModel(model_dir + "/model", model_dir + "/params");
|
||||||
|
|
||||||
|
if (this->use_gpu_) {
|
||||||
|
config.EnableUseGpu(this->gpu_mem_, this->gpu_id_);
|
||||||
|
} else {
|
||||||
|
config.DisableGpu();
|
||||||
|
if (this->use_mkldnn_) {
|
||||||
|
config.EnableMKLDNN();
|
||||||
|
}
|
||||||
|
config.SetCpuMathLibraryNumThreads(this->cpu_math_library_num_threads_);
|
||||||
|
}
|
||||||
|
|
||||||
|
// false for zero copy tensor
|
||||||
|
config.SwitchUseFeedFetchOps(!this->use_zero_copy_run_);
|
||||||
|
// true for multiple input
|
||||||
|
config.SwitchSpecifyInputNames(true);
|
||||||
|
|
||||||
|
config.SwitchIrOptim(true);
|
||||||
|
|
||||||
|
config.EnableMemoryOptim();
|
||||||
|
config.DisableGlogInfo();
|
||||||
|
|
||||||
|
this->predictor_ = CreatePaddlePredictor(config);
|
||||||
|
}
|
||||||
|
} // namespace PaddleOCR
|
@ -0,0 +1,140 @@
|
|||||||
|
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
from __future__ import absolute_import
|
||||||
|
from __future__ import division
|
||||||
|
from __future__ import print_function
|
||||||
|
from __future__ import unicode_literals
|
||||||
|
|
||||||
|
from PIL import Image, ImageEnhance, ImageOps
|
||||||
|
import numpy as np
|
||||||
|
import random
|
||||||
|
import six
|
||||||
|
|
||||||
|
|
||||||
|
class RawRandAugment(object):
|
||||||
|
def __init__(self,
|
||||||
|
num_layers=2,
|
||||||
|
magnitude=5,
|
||||||
|
fillcolor=(128, 128, 128),
|
||||||
|
**kwargs):
|
||||||
|
self.num_layers = num_layers
|
||||||
|
self.magnitude = magnitude
|
||||||
|
self.max_level = 10
|
||||||
|
|
||||||
|
abso_level = self.magnitude / self.max_level
|
||||||
|
self.level_map = {
|
||||||
|
"shearX": 0.3 * abso_level,
|
||||||
|
"shearY": 0.3 * abso_level,
|
||||||
|
"translateX": 150.0 / 331 * abso_level,
|
||||||
|
"translateY": 150.0 / 331 * abso_level,
|
||||||
|
"rotate": 30 * abso_level,
|
||||||
|
"color": 0.9 * abso_level,
|
||||||
|
"posterize": int(4.0 * abso_level),
|
||||||
|
"solarize": 256.0 * abso_level,
|
||||||
|
"contrast": 0.9 * abso_level,
|
||||||
|
"sharpness": 0.9 * abso_level,
|
||||||
|
"brightness": 0.9 * abso_level,
|
||||||
|
"autocontrast": 0,
|
||||||
|
"equalize": 0,
|
||||||
|
"invert": 0
|
||||||
|
}
|
||||||
|
|
||||||
|
# from https://stackoverflow.com/questions/5252170/
|
||||||
|
# specify-image-filling-color-when-rotating-in-python-with-pil-and-setting-expand
|
||||||
|
def rotate_with_fill(img, magnitude):
|
||||||
|
rot = img.convert("RGBA").rotate(magnitude)
|
||||||
|
return Image.composite(rot,
|
||||||
|
Image.new("RGBA", rot.size, (128, ) * 4),
|
||||||
|
rot).convert(img.mode)
|
||||||
|
|
||||||
|
rnd_ch_op = random.choice
|
||||||
|
|
||||||
|
self.func = {
|
||||||
|
"shearX": lambda img, magnitude: img.transform(
|
||||||
|
img.size,
|
||||||
|
Image.AFFINE,
|
||||||
|
(1, magnitude * rnd_ch_op([-1, 1]), 0, 0, 1, 0),
|
||||||
|
Image.BICUBIC,
|
||||||
|
fillcolor=fillcolor),
|
||||||
|
"shearY": lambda img, magnitude: img.transform(
|
||||||
|
img.size,
|
||||||
|
Image.AFFINE,
|
||||||
|
(1, 0, 0, magnitude * rnd_ch_op([-1, 1]), 1, 0),
|
||||||
|
Image.BICUBIC,
|
||||||
|
fillcolor=fillcolor),
|
||||||
|
"translateX": lambda img, magnitude: img.transform(
|
||||||
|
img.size,
|
||||||
|
Image.AFFINE,
|
||||||
|
(1, 0, magnitude * img.size[0] * rnd_ch_op([-1, 1]), 0, 1, 0),
|
||||||
|
fillcolor=fillcolor),
|
||||||
|
"translateY": lambda img, magnitude: img.transform(
|
||||||
|
img.size,
|
||||||
|
Image.AFFINE,
|
||||||
|
(1, 0, 0, 0, 1, magnitude * img.size[1] * rnd_ch_op([-1, 1])),
|
||||||
|
fillcolor=fillcolor),
|
||||||
|
"rotate": lambda img, magnitude: rotate_with_fill(img, magnitude),
|
||||||
|
"color": lambda img, magnitude: ImageEnhance.Color(img).enhance(
|
||||||
|
1 + magnitude * rnd_ch_op([-1, 1])),
|
||||||
|
"posterize": lambda img, magnitude:
|
||||||
|
ImageOps.posterize(img, magnitude),
|
||||||
|
"solarize": lambda img, magnitude:
|
||||||
|
ImageOps.solarize(img, magnitude),
|
||||||
|
"contrast": lambda img, magnitude:
|
||||||
|
ImageEnhance.Contrast(img).enhance(
|
||||||
|
1 + magnitude * rnd_ch_op([-1, 1])),
|
||||||
|
"sharpness": lambda img, magnitude:
|
||||||
|
ImageEnhance.Sharpness(img).enhance(
|
||||||
|
1 + magnitude * rnd_ch_op([-1, 1])),
|
||||||
|
"brightness": lambda img, magnitude:
|
||||||
|
ImageEnhance.Brightness(img).enhance(
|
||||||
|
1 + magnitude * rnd_ch_op([-1, 1])),
|
||||||
|
"autocontrast": lambda img, magnitude:
|
||||||
|
ImageOps.autocontrast(img),
|
||||||
|
"equalize": lambda img, magnitude: ImageOps.equalize(img),
|
||||||
|
"invert": lambda img, magnitude: ImageOps.invert(img)
|
||||||
|
}
|
||||||
|
|
||||||
|
def __call__(self, img):
|
||||||
|
avaiable_op_names = list(self.level_map.keys())
|
||||||
|
for layer_num in range(self.num_layers):
|
||||||
|
op_name = np.random.choice(avaiable_op_names)
|
||||||
|
img = self.func[op_name](img, self.level_map[op_name])
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
class RandAugment(RawRandAugment):
|
||||||
|
""" RandAugment wrapper to auto fit different img types """
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
if six.PY2:
|
||||||
|
super(RandAugment, self).__init__(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
|
def __call__(self, data):
|
||||||
|
img = data['image']
|
||||||
|
if not isinstance(img, Image.Image):
|
||||||
|
img = np.ascontiguousarray(img)
|
||||||
|
img = Image.fromarray(img)
|
||||||
|
|
||||||
|
if six.PY2:
|
||||||
|
img = super(RandAugment, self).__call__(img)
|
||||||
|
else:
|
||||||
|
img = super().__call__(img)
|
||||||
|
|
||||||
|
if isinstance(img, Image.Image):
|
||||||
|
img = np.asarray(img)
|
||||||
|
data['image'] = img
|
||||||
|
return data
|
@ -0,0 +1,30 @@
|
|||||||
|
# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
from __future__ import absolute_import
|
||||||
|
from __future__ import division
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
from paddle import nn
|
||||||
|
|
||||||
|
|
||||||
|
class ClsLoss(nn.Layer):
|
||||||
|
def __init__(self, **kwargs):
|
||||||
|
super(ClsLoss, self).__init__()
|
||||||
|
self.loss_func = nn.CrossEntropyLoss(reduction='mean')
|
||||||
|
|
||||||
|
def __call__(self, predicts, batch):
|
||||||
|
label = batch[1]
|
||||||
|
loss = self.loss_func(input=predicts, label=label)
|
||||||
|
return {'loss': loss}
|
@ -0,0 +1,46 @@
|
|||||||
|
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
class ClsMetric(object):
|
||||||
|
def __init__(self, main_indicator='acc', **kwargs):
|
||||||
|
self.main_indicator = main_indicator
|
||||||
|
self.reset()
|
||||||
|
|
||||||
|
def __call__(self, pred_label, *args, **kwargs):
|
||||||
|
preds, labels = pred_label
|
||||||
|
correct_num = 0
|
||||||
|
all_num = 0
|
||||||
|
for (pred, pred_conf), (target, _) in zip(preds, labels):
|
||||||
|
if pred == target:
|
||||||
|
correct_num += 1
|
||||||
|
all_num += 1
|
||||||
|
self.correct_num += correct_num
|
||||||
|
self.all_num += all_num
|
||||||
|
return {'acc': correct_num / all_num, }
|
||||||
|
|
||||||
|
def get_metric(self):
|
||||||
|
"""
|
||||||
|
return metircs {
|
||||||
|
'acc': 0,
|
||||||
|
'norm_edit_dis': 0,
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
acc = self.correct_num / self.all_num
|
||||||
|
self.reset()
|
||||||
|
return {'acc': acc}
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.correct_num = 0
|
||||||
|
self.all_num = 0
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue