のねのBlog

パソコンの問題や、ソフトウェアの開発で起きた問題など書いていきます。よろしくお願いします^^。

ValueError: Floating point image RGB values must be in the 0..1 range.

ValueError: Floating point image RGB values must be in the 0..1 range.

Time taken for epoch 1 is 132.77519750595093 sec

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    332                 pass
    333             else:
--> 334                 return printer(obj)
    335             # Finally look for special method names
    336             method = get_real_method(obj, self.print_method)

/usr/local/lib/python3.6/dist-packages/IPython/core/pylabtools.py in <lambda>(fig)
    239 
    240     if 'png' in formats:
--> 241         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    242     if 'retina' in formats or 'png2x' in formats:
    243         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/usr/local/lib/python3.6/dist-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    123 
    124     bytes_io = BytesIO()
--> 125     fig.canvas.print_figure(bytes_io, **kw)
    126     data = bytes_io.getvalue()
    127     if fmt == 'svg':

/usr/local/lib/python3.6/dist-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2214                     orientation=orientation,
   2215                     dryrun=True,
-> 2216                     **kwargs)
   2217                 renderer = self.figure._cachedRenderer
   2218                 bbox_inches = self.figure.get_tightbbox(renderer)

/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    505 
    506     def print_png(self, filename_or_obj, *args, **kwargs):
--> 507         FigureCanvasAgg.draw(self)
    508         renderer = self.get_renderer()
    509         original_dpi = renderer.dpi

/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py in draw(self)
    428             # if toolbar:
    429             #     toolbar.set_cursor(cursors.WAIT)
--> 430             self.figure.draw(self.renderer)
    431         finally:
    432             # if toolbar:

/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/usr/local/lib/python3.6/dist-packages/matplotlib/figure.py in draw(self, renderer)
   1297 
   1298             mimage._draw_list_compositing_images(
-> 1299                 renderer, self, artists, self.suppressComposite)
   1300 
   1301             renderer.close_group('figure')

/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2435             renderer.stop_rasterizing()
   2436 
-> 2437         mimage._draw_list_compositing_images(renderer, self, artists)
   2438 
   2439         renderer.close_group('axes')

/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/usr/local/lib/python3.6/dist-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in draw(self, renderer, *args, **kwargs)
    564         else:
    565             im, l, b, trans = self.make_image(
--> 566                 renderer, renderer.get_image_magnification())
    567             if im is not None:
    568                 renderer.draw_image(gc, l, b, im)

/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in make_image(self, renderer, magnification, unsampled)
    791         return self._make_image(
    792             self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
--> 793             unsampled=unsampled)
    794 
    795     def _check_unsampled_image(self, renderer):

/usr/local/lib/python3.6/dist-packages/matplotlib/image.py in _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification, unsampled, round_to_pixel_border)
    482             # (of int or float)
    483             # or an RGBA array of re-sampled input
--> 484             output = self.to_rgba(output, bytes=True, norm=False)
    485             # output is now a correctly sized RGBA array of uint8
    486 

/usr/local/lib/python3.6/dist-packages/matplotlib/cm.py in to_rgba(self, x, alpha, bytes, norm)
    255                 if xx.dtype.kind == 'f':
    256                     if norm and xx.max() > 1 or xx.min() < 0:
--> 257                         raise ValueError("Floating point image RGB values "
    258                                          "must be in the 0..1 range.")
    259                     if bytes:

ValueError: Floating point image RGB values must be in the 0..1 range.
<matplotlib.figure.Figure at 0x7f7e6f384908>
Time taken for epoch 1 is 132.77519750595093 sec

---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-48-d152560ca122> in <module>()
----> 1 train(train_dataset, EPOCHS)

<ipython-input-47-24e63cd58368> in train(dataset, epochs)
     17                                               generator.variables)
     18       discriminator_gradients = disc_tape.gradient(disc_loss, 
---> 19                                                    discriminator.variables)
     20 
     21       generator_optimizer.apply_gradients(zip(generator_gradients, 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/backprop.py in gradient(self, target, sources, output_gradients)
    899         nest.flatten(target),
    900         flat_sources,
--> 901         output_gradients=output_gradients)
    902 
    903     if not self._persistent:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/imperative_grad.py in imperative_grad(tape, target, sources, output_gradients)
     62       target,
     63       sources,
---> 64       output_gradients)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/backprop.py in _gradient_function(op_name, attr_tuple, num_inputs, inputs, outputs, out_grads)
    115     return [None] * num_inputs
    116 
--> 117   return grad_fn(mock_op, *out_grads)
    118 
    119 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_grad.py in _SelectGrad(op, grad)
   1115   x = op.inputs[1]
   1116   zeros = array_ops.zeros_like(x)
-> 1117   return (None, array_ops.where(c, grad, zeros), array_ops.where(
   1118       c, zeros, grad))
   1119 

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/array_ops.py in where(condition, x, y, name)
   2622       return gen_array_ops.where(condition=condition, name=name)
   2623   elif x is not None and y is not None:
-> 2624     return gen_math_ops.select(condition=condition, x=x, y=y, name=name)
   2625   else:
   2626     raise ValueError("x and y must both be non-None or both be None.")

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py in select(condition, x, y, name)
   7008       _result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
   7009         _ctx._context_handle, _ctx._eager_context.device_name, "Select", name,
-> 7010         _ctx._post_execution_callbacks, condition, x, y)
   7011       return _result
   7012     except _core._FallbackException:

KeyboardInterrupt: 

InvalidArgumentError: You must feed a value for placeholder tensor

Google ColabでTensorBoardを利用しようとしていたら、以下のエラーがでた。

CPUだと起こるみたい、GPUにするとエラーが出なくなった。
ランタイムのリセットも必要かもしれない。


ソースの元
stackoverflow.com

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import callbacks

#log_dir='/Users/shlomi.shwartz/tensorflow/notebooks/logs/minist'
log_dir = 'work_dir'

batch_size  = 100
num_classes = 10
epochs      = 20

tb = callbacks.TensorBoard(
    log_dir,
    histogram_freq=10,
    batch_size=32,
    write_graph=True,
    write_grads=True,
    write_images=True,
    embeddings_freq=0,
    embeddings_layer_names=None,
    embeddings_metadata=None)

early_stop = callbacks.EarlyStopping(
    monitor='val_loss',
    min_delta=0,
    patience=3,
    verbose=1,
    mode='auto')


# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test  = x_test.reshape(10000, 784)

x_train = x_train.astype('float32') / 255
x_test  = x_test.astype('float32')  / 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
#y_train = keras.utils.to_categorical(y_train, num_classes)
#y_test  = keras.utils.to_categorical(y_test, num_classes)
y_train = keras.utils.to_categorical(y_train)
y_test  = keras.utils.to_categorical(y_test)

model = Sequential()
#model.add(Dense(200, activation='relu', input_shape=(784,)))
model.add(Dense(32, activation='relu', input_shape=(784,)))
#model.add(Dropout(0.2))
#model.add(Dense(100, activation='relu'))
#model.add(Dropout(0.2))
#model.add(Dense(60, activation='relu'))
#model.add(Dropout(0.2))
#model.add(Dense(30, activation='relu'))
#model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))

model.summary()

model.compile(
    #optimizer='adam',
    optimizer='rmsprop',
    loss='categorical_crossentropy',
    metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    callbacks=[tb,early_stop],
                    #callbacks=[tb],
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

エラー

InvalidArgumentError: You must feed a value for placeholder tensor 'dense_5_sample_weights' with dtype float and shape [?]
	 [[{{node dense_5_sample_weights}} = Placeholder[dtype=DT_FLOAT, shape=[?], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

During handling of the above exception, another exception occurred:
続きを読む

TensorBoard

ValueError: To visualize embeddings, embeddings_data must be provided.
callbacks = [
    keras.callbacks.TensorBoard(
      log_dir='my_log_dir', # ログ・ファイルはこの場所に書き込まれる
      histogram_freq  = 1,  # 1エポックごとに活性化ヒストグラムを記録
      embeddings_freq = 1   # 1エポックごとに埋め込みデータを記録
    )
]

history = model.fit(x_train, y_train,
                    epochs = 20,
                    batch_size =128,
                    validation_split=0.2,
                    callbacks=callbacks)

stackoverflow.com

teratail.com