# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import theano
import numpy as np
import theano.tensor as T

__author__ = 'fuhuamosi'


class LogisticRegression:
    def __init__(self, x, n_in, n_out):
        self.w = theano.shared(
            value=np.zeros((n_in, n_out), dtype=theano.config.floatX),
            name='W',
            borrow=True)
        self.b = theano.shared(
            value=np.zeros((n_out,), dtype=theano.config.floatX),
            name='b',
            borrow=True)
        self.p_y_given_x = T.nnet.softmax(T.dot(x, self.w) + self.b)
        self.pre_y = T.argmax(self.p_y_given_x, axis=1)
        self.params = [self.w, self.b]
        self.x = x

    def negative_log_likelihood(self, y):
        return -T.mean(T.log(self.p_y_given_x[T.arange(y.shape[0]), y]))

    def errors(self, y):
        if y.ndim != self.pre_y.ndim:
            raise TypeError('you should have the same shape as self.pre_y',
                            ('y', y.dtype, 'pre_y', self.pre_y.dtype))
        if y.dtype.startswith('int'):
            return T.mean(T.neq(y, self.pre_y))
        else:
            raise NotImplementedError()
