简体   繁体   中英

What does Keras model.predict returns?

I am building an autoencoder network for finding outliers in a single-column list of text.

I pick up each character, transform it to ASCII, and put them into an array.

Each line of the array is a row of my input, and each element in the array is an integer representation of the ascii code for the character.

Each array has the size of the largest element on my array, the smaller ones are padded with zeroes to the right.

So I end up with Numpy Arrays with ascii codes, and I create an autoencoder network so I can find ones that do not follow a pattern, that stand out from the rest.

My whole code is:

import sys
from keras import Input, Model
import matplotlib.pyplot as plt
from keras.layers import Dense
import numpy as np
from pprint import pprint
from google.colab import drive

# Monta o arquivo do Google Drive
drive.mount('/content/drive')
with open('/content/drive/My Drive/Colab Notebooks/drawables.txt', 'r') as arquivo:
    dados = arquivo.read().splitlines()

# Define uma função para pegar uma lista e retornar um inteiro com o tamanho do 
# maior elemento
def tamanho_maior_elemento(lista):
  maior = 0
  for elemento in lista:
    tamanho_elemento = len(elemento)
    if tamanho_elemento > maior:
      maior = tamanho_elemento
  return maior

# Define uma função para pegar uma lista e o tamanho do maior elemento e
# retornar uma lista contendo uma outra lista com cada caractere convertido para
# ascii, antes de converter são adicionados zeros a direita para eles ficarem
# com o mesmo tamanho do maior elemento.
def texto_para_ascii(lista, tamanho_maior_elemento):
  #para cada linha
  lista_ascii = list()
  for elemento in lista:
    elemento_ascii_lista = list()
    #coloca zeros do lado da string
    elemento_com_zeros = elemento.ljust(tamanho_maior_elemento, "0")
    for caractere in elemento_com_zeros:
      elemento_ascii_lista.append(ord(caractere))
    lista_ascii.append(elemento_ascii_lista)
  return lista_ascii

def ascii_para_texto(lista):
  #para cada linha
  lista_ascii = list()
  for elemento in lista:
    elemento_ascii_lista = list()
    for caractere in elemento:
      elemento_ascii_lista.append(chr(caractere))
    elemento_ascii_string = "".join(elemento_ascii_lista)
    lista_ascii.append(elemento_ascii_string)
  return lista_ascii

# Pega o tamanho do maior elemento
tamanho_maior_elemento = tamanho_maior_elemento(dados)

# Pega o tamanho da lista
tamanho_lista = len(dados)

# Converte os dados para ascii
dados_ascii = texto_para_ascii(dados, tamanho_maior_elemento)

# Converte a linha de dados em ascii para um array numpy
np_dados_ascii = np.array(dados_ascii)

# Define o tamanho da camada comprimida
tamanho_comprimido = int(tamanho_maior_elemento/5)

# Cria a camada de Input com o tamanho do maior elemento
dados_input = Input(shape=(tamanho_maior_elemento,))

# Cria uma camada escondida com o tamanho da camada comprimida
hidden = Dense(tamanho_comprimido, activation='relu')(dados_input)

# Cria a camada de saida com o tamanho do maior elemento
output = Dense(tamanho_maior_elemento, activation='relu')(hidden)
#resultado = Dense(tamanho_maior_elemento, activation='sigmoid')(output)
resultado = Dense(tamanho_maior_elemento)(output)

# Cria o modelo
autoencoder = Model(input=dados_input, output=resultado)

# Compila o modelo
autoencoder.compile(optimizer='adam', loss='mse')

# Faz o fit com os dados
history = autoencoder.fit(np_dados_ascii, np_dados_ascii, epochs=20)

# Plota o gráfico das epochs
plt.plot(history.history["loss"])
plt.ylabel("Loss")
plt.xlabel("Epoch")
plt.show()

# Pega a saída do predict
predict = autoencoder.predict(np_dados_ascii)

# What now?

What I want to know is, I've predicted the value, what's the next step? I mean, the model.predict function from keras returned me an array of float values. How can I get it back to ascii characters so I can see the text it predicted?

I don't know if I said it right, english is not my main language and I'm utterly lost with this.

You can convert back your ASCII numbers to text and you can visulize your result. Use chr , a python built-in function. It requires input as integer value in range of 0 to 255. So, make sure that your model predicts the value between this range.

predict = np.random.uniform(0,255,(1,100)) # Replace with your original prediction
predict_text=[]
for i in range(predict.shape[1]):
  predict_text.append(chr(int(predict[0][i])))
predict_text =  np.expand_dims(np.asarray(predict_text),axis=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM