1

I have converted images to tensors. How should I stack them to train for a Convolutional Neural Network in keras.

mask_tensor = tf.Variable([])
for img in mask_img:
    image = tf.io.read_file(img)
    tensor = tf.io.decode_jpeg(image, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    if mask_tensor.shape == 0:
        mask_tensor = tf.stack([tensor])
    else:
        tf.reshape(tensor, [1,128,128,3])
        mask_tensor = tf.stack([mask_tensor, tensor])



InvalidArgumentError: Input to reshape is a tensor with 49152 values, but the requested shape has 98304 [Op:Reshape]

2 Answers2

0

If your tensors are based on this, try :

mask_tensor = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
for img in mask_img:
    image = tf.io.read_file(img)
    tensor = tf.io.decode_jpeg(image, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    mask_tensor = mask_tensor.write(mask_tensor.size(), tensor)
images = mask_tensor.stack()
images.shape
AloneTogether
  • 25,814
  • 5
  • 20
  • 39
  • I think my code is too complicated do you know how's it done in the practice. –  Aug 27 '22 at 13:52
  • how to shuffle data (dtype=Tensors {can't use sklearn}) and label without disturbing their order https://stackoverflow.com/questions/73513049/how-to-shuffle-data-dtype-tensors-cant-use-sklearn-and-label-without-distur –  Aug 28 '22 at 05:45
  • 1
    Why not feed your data to `tf.data.Dataset.from_tensor_slices` – AloneTogether Aug 28 '22 at 06:19
0

Using tf.data.Dataset.from_tensor_slices as said in comment above

filenames = tf.constant(["img1.jpg", ...])
labels = tf.constant([1, ...])

dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

def _parse_function(filename, label):
    image_string = tf.read_file(filename)
    tensor = tf.image.decode_jpeg(image_string, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    image = tf.cast(tensor, tf.float32)/255.
    return image, label

dataset = dataset.map(_parse_function).batch(32)