Example #1
0
    def plotar_dataset(self, x, y=None):
        matplotlib.use('GTK3Agg')

        fig = plt.figure()
        ax = fig.add_subplot(111)

        x = np.copy(x)

        x, fator = util.normalizar(x, self.rn.fator_normalizacao)

        #### CALCULAR CORES
        if (type(y) != type(None)):
            y = y[:, 1]

            # laranja   = (255,160,0)   = ( 1 , 0.6 , 0  )
            # azul      = (0,0,255)     = ( 0 , 0   , 1. )
            cores = np.empty([y.size, 3])
            cores[:, 0] = (1 - y) / 2
            cores[:, 1] = (1 - y) / 3
            cores[:, 2] = (y + 1) / 2
        else:
            cores = np.zeros([y.size, 3])

        #### PLOTAR PONTOS
        plt.scatter(x[:, 0], x[:, 1], color=cores, s=10)

        ax.set_xlim(-1.1, 1.1)
        ax.set_ylim(-1.1, 1.1)

        plt.show()
        plt.close('all')
    def treino(self, x, d, verbose=False, guardar_historico=False):
        x = np.copy(x)

        x, self.fator_normalizacao = util.normalizar(x,
                                                     self.fator_normalizacao)

        possui_erro = True
        while (possui_erro and self.epoca <= 2000):
            possui_erro = False

            u = self.feedforward(x)
            y = self.ativacao(u)

            if ((y != d).any()):
                self.pesos = self.pesos + self.taxa_aprendizado * (d -
                                                                   y).dot(x)
                possui_erro = True

            if (verbose):
                w0, w1, w2 = self.pesos
                erro = (d - y).dot(x)
                print(self.epoca, abs(erro).sum(), -w1 / w2, w0 / w2)

            if (guardar_historico and self.epoca % 1 == 0):
                self.historico.append(np.copy(self.pesos))

            self.epoca += 1
    def iniciar_figura_e_plotar_dataset(self, x, y, titulo):
        fig = plt.figure()
        ax = fig.add_subplot(111)

        maior_valor_absoluto_dataset = 1

        if (type(x) != type(None)):
            x = np.copy(x)

            x, fator = util.normalizar(x, self.rn.fator_normalizacao)

            #### CALCULAR CORES
            if (type(y) != type(None)):
                # laranja   = (255,160,0)   = ( 1 , 0.6 , 0  )
                # azul      = (0,0,255)     = ( 0 , 0   , 1. )
                cores = np.empty([y.size, 3])
                cores[:, 0] = (1 - y) / 2
                cores[:, 1] = (1 - y) / 3
                cores[:, 2] = (y + 1) / 2
            else:
                cores = np.zeros([y.size, 3])

            #### PLOTAR PONTOS
            plt.scatter(x[:, 1], x[:, 2], color=cores, s=10, zorder=1)

            maior_valor_absoluto_dataset = util.maior_valor_absoluto(x)

        ax.set_xlim(-maior_valor_absoluto_dataset * 1.1,
                    maior_valor_absoluto_dataset * 1.1)
        ax.set_ylim(-maior_valor_absoluto_dataset * 1.1,
                    maior_valor_absoluto_dataset * 1.1)

        plt.title(titulo)

        return fig, ax, maior_valor_absoluto_dataset
    def treino(self, x, d, verbose=False, guardar_historico=False):
        x = np.copy(x)

        x, self.fator_normalizacao = util.normalizar(x,
                                                     self.fator_normalizacao)

        erro_minimo = 1e-12
        ultimo_erro = 1
        while (self.epoca <= 1000):
            u = self.feedforward(x)

            erro = ((d - u)**2).sum() / float(d.size)

            if (abs(erro - ultimo_erro) <= erro_minimo):
                break

            self.pesos = self.pesos + self.taxa_aprendizado * (d - u).dot(x)

            ultimo_erro = erro
            self.epoca += 1

            if (verbose):
                w0, w1, w2 = self.pesos
                # print('%04d - %.12f - [ %.12f , %.12f , %.12f ]'%(self.epoca, erro, -w1/w2, w0/w2))
                # print('%04d - %.12f - [ %.12f , %.12f , %.12f ]'%(self.epoca, erro, w0, w1, w2))
                # print(self.epoca, erro, -w1/w2, w0/w2)
                print('%04d - %.12f' % (self.epoca, erro))

            if (guardar_historico and self.epoca % 1 == 0):
                self.historico_pesos.append(np.copy(self.pesos))
                self.historico_erro.append(erro)
Example #5
0
    def treinar(self, x, d, verbose=False, guardar_historico=False):
        x = np.copy(x)

        x, self.fator_normalizacao = util.normalizar(x,
                                                     self.fator_normalizacao)

        erro_minimo = 1e-12
        ultimo_erro = 100
        while (self.epoca <= 2000):
            y = self.forward(x)

            erro = ((d - y)**2).sum() / float(d.size)

            if (verbose):
                print('%04d - %.12f' % (self.epoca, erro))

            if (ultimo_erro - erro <= erro_minimo):
                print('UNDERFITTING')
                break

            self.backward(x, d)

            ultimo_erro = erro
            self.epoca += 1

            if (guardar_historico and self.epoca % 1 == 0):
                pesos = [np.copy(camada) for camada in self.camadas]
                self.historico_camadas.append(pesos)
                self.historico_erro.append(erro)
    def classificar(self, x, salvar_imagem=False):
        x = np.copy(x)

        x, fator = util.normalizar(x, self.fator_normalizacao)

        u = self.feedforward(x)
        y = self.ativacao(u)

        return y
Example #7
0
def main():
    iris_parameters = []
    iris_species = []

    with open('datasets/iris.csv', mode='r') as iris_file:
        irises = list(csv.reader(iris_file))
        rd.shuffle(irises)  # get our lines of data in random order
        for iris in irises:
            parameters = [float(n) for n in iris[0:4]]
            iris_parameters.append(parameters)
            species = iris[4]
            iris_species.append(species)

    iris_parameters = np.array(iris_parameters)
    normalizar(iris_parameters)
    iris_species = np.array(iris_species).reshape(-1, 1)

    print("\nTreinando...\n")

    iris_network = Perceptron(taxa=0.2, ativacao="l_relu", N=[4], debug=1)

    # número de dados de treino
    n_train = 120

    # train over the first 140 irises in the data set 50 times
    x_train = iris_parameters[:n_train]
    y_train = iris_species[:n_train]

    iris_network.treinar(x_train, y_train, M=100)
    y_train_pred = iris_network.prever(x_train)
    scores = Scores(y_train, y_train_pred)
    scores.exibir_grafico()

    # test over the last 10 of the irises in the data set
    x_test = iris_parameters[n_train:]
    y_test = iris_species[n_train:]
    y_test_pred = iris_network.prever(x_test)

    # minha classe geradora da matriz de confusão
    scores = Scores(y_test, y_test_pred)
    scores.exibir_grafico()
Example #8
0
print("Classificação da base MNIST usando a API Keras\n")

# Testando o mnist clássico dos números
print("Obtendo dados...")
mnist = load_digits() # versao 8x8
#mnist = fetch_openml('mnist_784', version=1) # versao 28x28

_N = int(mnist.data.shape[0]*0.8)
x_train, y_train = mnist.data[:_N], mnist.target[:_N].astype(np.uint8)
x_test, y_test = mnist.data[_N:], mnist.target[_N:].astype(np.uint8)

# deixando os vetores nos formatos corretos pra usar no keras
y_train = y_train.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)
normalizar(x_train)
normalizar(x_test)

# 3 camadas do tipo "perceptron" que aqui se chama "Dense" pois 
# significa que as camadas estão totalmente conectadas
# (poderia ser diferente, o que configuraria outro tipo de rede)
model = tf.keras.Sequential()
layers = tf.keras.layers

model.add(layers.Flatten())  #input_shape=(28, 28)
model.add(layers.Dense(48, activation='elu'))
model.add(layers.Dense(24, activation='elu'))
model.add(layers.Dense(10, activation='softmax'))

# assim o tipo de rede é definido pelo tipo da conexão dos neurônios
# e o mesmo tipo pode ser treinado de formas diferentes, mas 
import matplotlib.cm as cm

import util

def equacao_reta(x, y):
    # RETA: y = 0.25*x + 0.5
    return y > -1*x + 5

def ativacao_reta(x, y):
    # degrau bipolar
    return equacao_reta(x,y)*2-1

# util.gerar_dataset('reta_1/dataset_map.data', ativacao_reta, tamanho=1000)

x,d = util.carregar_dataset('reta_1/dataset_map.data')
x,f = util.normalizar(x, None)
d = np.array([d])

m1 = np.ones([x[:,0].size,1])

t = 1.1
s = 600.0

xx,yy = np.meshgrid( np.arange(0.6,t,t/s) , np.arange(0.6,t,t/s) )

md = np.empty([x[:,0].size,xx.size])
md[:] = d.T

pesos = np.empty([xx.size,3])
pesos[:,1] = xx.flatten()
pesos[:,2] = yy.flatten()