Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

448
Visualizações
¿Por qué plt.imshow() no muestra la imagen?

Soy un novato en keras, y cuando traté de ejecutar mi primer programa de keras en mi Linux, algo simplemente no salió como deseaba. Aquí está mi código Python:

 import numpy as np np.random.seed(123) from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist (X_train,y_train),(X_test,y_test) = mnist.load_data() print X_train.shape from matplotlib import pyplot as plt plt.imshow(X_train[0])

La última oración no muestra nada. Copié esos códigos de un tutorial sin ninguna modificación. Y no hay nada malo con el backend de matplotlib en mi computadora. Lo he probado a través del siguiente código.

 import matplotlib.pyplot as plt data = [[0, 0.25], [0.5, 0.75]] fig, ax = plt.subplots() im = ax.imshow(data, cmap=plt.get_cmap('hot'), interpolation='nearest', vmin=0, vmax=1) fig.colorbar(im) plt.show()

Y luego obtuve una imagen como esa: ingrese la descripción de la imagen aquí


Además, puedo imprimir X_train[0] y parece que no pasa nada.
Entonces, ¿cuál podría ser la razón de eso? ¿Por qué la función imshow() en mi primer código no mostró nada?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

La solución fue tan simple como agregar plt.show() al final del fragmento de código:

 import numpy as np np.random.seed(123) from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist (X_train,y_train),(X_test,y_test) = mnist.load_data() print X_train.shape from matplotlib import pyplot as plt plt.imshow(X_train[0]) plt.show()
over 4 years ago · Santiago Trujillo Relatório

0

plt.imshow simplemente termina de dibujar una imagen en lugar de imprimirla. Si desea imprimir la imagen, solo necesita agregar plt.show .

over 4 years ago · Santiago Trujillo Relatório

0

plt.imshow muestra la imagen en los ejes, pero si necesita mostrar varias imágenes, use show() para terminar la figura. El siguiente ejemplo muestra dos figuras:

 import numpy as np from keras.datasets import mnist (X_train,y_train),(X_test,y_test) = mnist.load_data() from matplotlib import pyplot as plt plt.imshow(X_train[0]) plt.show() plt.imshow(X_train[1]) plt.show()

En Google Colab, si comenta el método show() del ejemplo anterior, solo se mostrará una imagen (la última conectada con X_train[1] ).

Aquí está el contenido de la ayuda:

 plt.show(*args, **kw) Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt. In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block. A single experimental keyword argument, *block*, may be set to True or False to override the blocking behavior described above. plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs) Display an image on the axes. Parameters ---------- X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4) Display the image in `X` to current axes. `X` may be an array or a PIL image. If `X` is an array, it can have the following shapes and types: - MxN -- values to be mapped (float or int) - MxNx3 -- RGB (float or uint8) - MxNx4 -- RGBA (float or uint8) The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0.0 to 1.0. MxN arrays are mapped to colors based on the `norm` (mapping scalar to scalar) and the `cmap` (mapping the normed scalar to a color).
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda