model.py 2.3 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
C
chenxuyi 已提交
14 15 16 17
"""
Model template
"""

C
chenxuyi 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import sys
import six
import logging
import os
import itertools
import json
import abc
import numpy as np


@six.add_metaclass(abc.ABCMeta)
C
chenxuyi 已提交
33 34 35 36 37
class Model(object):
    """
    template
    """

C
chenxuyi 已提交
38 39 40 41 42 43 44 45 46 47 48 49
    def __init__(self, config, mode):
        """
        Args:
            config (dict): hyper param
            mode (propeller.RunMode):  will creat `TRAIN` and `EVAL` model in propeller.train_and_eval
        """
        self.mode = mode

    @abc.abstractmethod
    def forward(self, features):
        """
        Args:
C
chenxuyi 已提交
50
            features (list of Tensor): inputs features that depends on your Dataset.output_shapes
C
chenxuyi 已提交
51
        Returns:
C
chenxuyi 已提交
52
            return (Tensor): prediction
C
chenxuyi 已提交
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
        """
        pass

    @abc.abstractmethod
    def loss(self, predictions, label):
        """
        Args:
            predictions (Tensor): result of  `self.forward`
            label (Tensor): depends on your Dataset.output_shapes
        Returns:
            return (paddle scalar): loss
        """
        pass

    @abc.abstractmethod
    def backward(self, loss):
        """
        Call in TRAIN mode
        Args:
            loss (Tensor): result of `self.loss`
        Returns:
            None
        """
        pass

    @abc.abstractmethod
    def metrics(self, predictions, label):
        """
        Call in EVAL mode
        Args:
            predictions (Tensor): result of  `self.forward`
            label (Tensor): depends on your Dataset.output_shapes
        Returns:
            (dict): k-v map like: {"metrics_name": propeller.Metrics } 
        """
        return {}