Estaba siguiendo el tutorial básico de clasificación de tensorflow. Debido a razones de proxy, tengo que usar el conjunto de datos sin conexión. Entonces, en lugar de usar la base de datos fashion_mnist, estoy usando el conjunto de datos mnist.
from __future__ import absolute_import, division,
print_function, unicode_literals
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Flatten, Dense
# Noting class names
class_names = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
# Load dataset
mnist = keras.datasets.mnist
path = 'C:/projects/VirtualEnvironment/MyScripts/load/mnist.npz'
(train_x, train_y), (test_x, test_y) = mnist.load_data(path)
# Scale, so that training and testing set is preprocessed in the same way
train_x = train_x / 255.0
test_x = test_y / 255.0
train_y = tf.expand_dims(train_y, axis = -1)
test_y = tf.expand_dims(test_y, axis = -1)
#Build the model
#1. Setup the layers
model = keras.Sequential()
model.add(Flatten(input_shape = (28, 28)))
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dense(10, activation=tf.nn.softmax))
#2. Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_x, train_y, epochs=1)
print("Finished Training")
# Evaluate how the model performs on the test dataset
test_loss, test_acc = model.evaluate(test_x, test_y, verbose=2)
Recibo el siguiente error: ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (10000, 1).
Sé muy poco acerca de tensorflow, por lo que si alguien pudiera guiarme en la dirección de una página web útil, o pudiera explicarme qué significa el error, estaría muy agradecido
3 respuestas
Esto es causado por un error tipográfico en su código
Cambia esto
test_x = test_y / 255.0
Para
test_x = test_x / 255.0
Esto funciona para mí:
(train_x, train_y), (test_x, test_y) = tf.keras.datasets.mnist.load_data()
# Scale, so that training and testing set is preprocessed in the same way
train_x = train_x / 255.0
test_x = test_x / 255.0
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape = (28, 28)))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
#2. Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_x, train_y, epochs=1)
# Evaluate the model
test_loss, test_acc = model.evaluate(test_x, test_y, verbose=2)
El error que obtiene significa que ha reformado incorrectamente su entrada en algún lugar de su código.
No estoy seguro sobre el problema de la forma de la matriz, sin embargo, puedo ayudarlo con el proxy para que pueda descargar correctamente el conjunto de datos. Suponiendo que tiene todo claro de su TI para usar las herramientas que es, puede configurar el proxy pip exportando a nivel de terminal:
Digamos que su credencial de inicio de sesión es EMPRESA \ nombre de usuario
export http_proxy=http://COMPANY%5Cusername:password@proxy_ip:proxy_port
export https_proxy=http://COMPANY%5Cusername:password@proxy_ip:proxy_port
Si está utilizando un entorno conda, .condarc en C: \ Users \ username y edite como:
channels:
- defaults
# Show channel URLs when displaying what is going to be downloaded and
# in 'conda list'. The default is False.
show_channel_urls: True
allow_other_channels: True
proxy_servers:
http: http://COMPANY\username:password@proxy_ip:proxy_port
https: https://COMPANY\username:password@proxy_ip:proxy_port
ssl_verify: False
Espero eso ayude. Para depurar la forma de la matriz, le sugiero que imprima las formas train_y y train_x con train_y.shape () y train_x.shape () después de expandir las dimensiones. El error especifica que está obteniendo un objeto 10000D con 1 valor, que no debería ser el caso.