NorwegianClassic
NorwegianClassic

Reputation: 1115

Stacking arrays of multi dimensional arrays in Python

I can't really wrap my head around this... and I'm not sure if stacking is the right term to use here.

A.shape = (28,28,1)
B.shape = (28,28,1)

If I want to merge/add/stack these arrays to this format:

C.shape = (2,28,28,1)

How do I do this? And is it a += version of this there I can add new arrays of shape (28,28,1) into the existing stack to get (3,28,28,1).

EDIT

I have this array of 100 grayscale images: (100, 784) which I guess I can reshape to (100,28,28,1) with tf.reshape.

I want to standardize all pixel values of the 100 images with tf.image.per_image_standardization (doc), but this function accepts only input shape (h,w,ch) aka. (28,28,1).

Any suggestions on how to optimize this?

CODE

for i in range(epochs):
    for j in range(samples/batch_size):

        batch_xs, batch_ys = mnist.train.next_batch(batch_size) #(100,784)
        batch_xsr = tf.reshape(batch_xs, [-1, 28, 28, 1]) # (100,28,28,1)

        ... 

        #somehow use tf.image.per_image_standardization (input shape = 
        #(28,28,1)) on each of the 100 images, and end up with 
        #shape (100,28,28,1) again.

        ...

        _, loss = sess.run([train, loss_op], feed_dict={x: batch_xs, y: batch_ys})

Note to self: TensorFlow needs np.array in feed dict.

Upvotes: 1

Views: 120

Answers (2)

ascripter
ascripter

Reputation: 6223

You can use numpy's functions stack and concatenate

import numpy as np

A = np.zeros((28, 28, 1))
B = np.zeros((28, 28, 1))

C = np.stack((A, B), axis=0)

print (C.shape)

>>> (2L, 28L, 28L, 1L)

Append further arrays of shape (28, 28, 1) to an array of shape (x, 28, 28, 1) by concatenating along axis=0:

D = np.ones((28,28,1))
C = np.concatenate([C, [D]], axis=0)
#C = np.append(C, [D], axis=0)  # equivalent using np.append which is wrapper around np.concatenate

print (C.shape)

>>> (3L, 28L, 28L, 1L)

EDIT

I'm not familiar with tensorflow, but try this to normalize your images

for i in range(epochs):
    for j in range(samples/batch_size):

        batch_xs, batch_ys = mnist.train.next_batch(batch_size) #(100,784)
        batch_xsr = tf.reshape(batch_xs, [-1, 28, 28, 1]) # (100,28,28,1)

        for i_image in range(batch_xsr.shape[0]):
            batch_xsr[i_image,:,:,:] = tf.image.per_image_standardization(batch_xsr[i_image,:,:,:])

        _, loss = sess.run([train, loss_op], feed_dict={x: batch_xs, y: batch_ys})

Upvotes: 2

Chris Farr
Chris Farr

Reputation: 3759

You could go like this...

import numpy as np

A = np.zeros(shape=(28, 28, 1))
B = np.zeros(shape=(28, 28, 1))
A.shape  # (28, 28, 1)
B.shape  # (28, 28, 1)

C = np.array([A, B])

C.shape  # (2, 28, 28, 1)

Then use this to add more, assuming 'new' here is the same shape as A or B.

def add_another(C, new):
    return np.array(list(C) + [new])

Upvotes: 3

Related Questions