Как подготовить форму тестового набора для модели. Оценить с помощью кераса и тензорного потока? - PullRequest
1 голос
/ 04 апреля 2019

Я пытаюсь запустить простой пример с NN, используя набор данных MNIST, предоставленный самим тензорным потоком и работающий в Google Colab.Я хочу получить необработанные данные и самостоятельно смонтировать структуру, которая содержит данные.Я могу обучить NN, но когда я пытаюсь предсказать один пример из набора тестов, я получаю ошибку

ValueError: Error when checking input: expected dense_input to have shape (784,) but got array with shape (1,).

Может ли кто-нибудь помочь мне с этой проблемой?Я довольно плохо знаком с Python и Keras / TensorFlow.

Когда я запускаю

print(inp.shape)

, я получаю (784,), а не (1,), как говорит ошибка.

Я также пытался оценить набор тестов, используя

test_loss, test_accuracy = model.evaluate(test_input.T)

, но я также получаю ошибку

ValueError: Arguments and signature arguments do not match: 25 27.

Исходный код следующий:

# Importing stuff
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import numpy as np
import math
import time
import keras

tf.enable_eager_execution()

# Functions
def normalize(images, labels):
  images = tf.cast(images, tf.float32)
  images /= 255
  return images, labels

# Getting dataset
ds, meta = tfds.load('fashion_mnist', as_supervised=True, with_info=True)

test_ds, train_ds = ds['test'], ds['train']

# Preprocess the data
train_ds =  train_ds.map(normalize)
test_ds  =  test_ds.map(normalize)

num_train_examples = meta.splits['train'].num_examples
num_test_examples = meta.splits['test'].num_examples

# Making the train set
train_input = np.empty(shape=(784, num_train_examples))
train_label = np.empty(shape=(1, num_train_examples))

i = 0
for image, label in train_ds:
  image = image.numpy().reshape((784, 1))
  train_input[:, i] = image.ravel()
  label = label.numpy().reshape(1)
  train_label[:, i] = label
  i = i + 1;

# Making the test set
test_input = np.empty(shape=(784, num_test_examples))
test_label = np.empty(shape=(1, num_test_examples))

i = 0
for image, label in test_ds:
  image = image.numpy().reshape((784, 1))
  test_input[:, i] = image.ravel()
  label = label.numpy().reshape(1)
  test_label[:, i] = label
  i = i + 1;

# Network
input_layer = tf.keras.layers.Dense(units=784, input_shape=[784])
h1 = tf.keras.layers.Dense(128, activation=tf.nn.relu)
output_layer = tf.keras.layers.Dense(10, activation=tf.nn.softmax)

model = tf.keras.Sequential([input_layer, h1, output_layer])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(train_input.T, train_label.T, epochs=3, steps_per_epoch=100, batch_size=1)

test_loss, test_accuracy = model.evaluate(test_input.T)

inp = test_input[:, 0].T
res = model.predict(inp)

1 Ответ

0 голосов
/ 04 апреля 2019

Все функции API ожидают входную форму, содержащую размер пакета в первую очередь.В вашем случае вы пытаетесь накормить только 1 пример, поэтому размер партии не указан.Вам просто нужно указать размер пакета как 1 путем изменения формы данных.

Использование numpy:

res = model.predict(np.reshape(inp, len(inp))

Аргумент метода predict теперь получает массив с формой (1, 784)в вашем случае, указав размер пакета равным 1.

Когда вы даете функции больше примеров для оценки, накладывая их друг на друга, размер пакета неявно задается формой массива, поэтомунеобходимо дальнейшее преобразование.

...