I have two arrays of size (128,) and a third one of size (784, 128):
array1.shape()
out: (128,)
array2.shape()
out: (128,)
array3.shape()
out: (784,128)
They have the same data type but the dtype() output is different:
array1.dtype
out: float32
array2.dtype
out: <dtype: 'float32'>
array2.dtype
out: <dtype: 'float32'>
And they belong to different classes:
type(array1)
out: <class 'numpy.ndarray'>
type(array2)
out: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
type(array3)
out: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
I want to perform the following matrix operation:
(array1 - array2) * array3.T
Where T is the transpose of array3.
Lastly, the output matrix (which is [784 * 1]) needs to be reshaped to become a uint8 array of shape 28 * 28 so I can plot that output on a matplotlip.
Can anyone help me to convert the arrays into matrices first. Then Transpose the third array properly. Finally, reshape the output to become an uint8 array of size 28 * 28.
I am working with tensorflow and keras in python.
Cast array1 as np.asmatrix()
array1 = np.asmatrix(array1)
For array2, change it to numpy array fist then cast it as a matrix:
array2 = array2.numpy()
array2 = np.asmatrix(array2)
For array3, change it to numpy array first then cast it as a matrix. Lastly, transpose that matrix:
array3 = array3.numpy()
array3 = np.asmatrix(array3)
array3 = np.transpose(array3)
Finally, apply the matrix operation:
result = (array1 - array2) * array3
To plot the output, use the following:
result = np.array(result)
plt.imshow(result.reshape(28, 28), cmap='gray')
plt.show()
Related
I have an np array n and the shape is (250,250). after that I converted (final array w)it into (250,250,3) because I need to do some operation on it.
is it possible to convert the shape of w to (250,250)?
thanks in advance.
I tried some reshaping operation of Numpy but it does not work!
Numpy reshaping array
Comparing two NumPy arrays for equality, element-wise
Numpy reshaping array
numpy.reshape
Gives a new shape to an array without changing its data.
so this is not right to convert array with shape of (250,250,3) into array with shape of (250,250) as 1st does have 187500 cells and 2nd does have 62500 cells.
You probably should use slicing, consider following example
import numpy as np
arr = np.array([[[0,1],[2,3]],[[4,5],[6,7]]]) # has shape (2,2,2)
arr2 = arr[:,:,0] # get certain cross-section, check what will happend if you use 1 inplace of 0 and 2 inplace of 0
print("arr2")
print(arr2)
print("arr2.shape",arr2.shape)
output
arr2
[[0 2]
[4 6]]
arr2.shape (2, 2)
I am following a tutorial to implement the K-nearest Neighbor algorithm on a dataset.
I have an array of shape (6003,) and I want to do this:
data = data.reshape((data.shape[0], 3072))
However, I am getting this error:
cannot reshape array of size 6003 into shape (6003,3072)
Any help on this, please? Thanks!
when you reshape a numpy array the total number elements shouldn't change.
e.g. a =[2,3,4,5,1,7] if you want to reshape this to a 2Darray then the dimensions multiplied should be equal to the total number elements in the original array a.
this means you can reshape array a in to dimension of (1,6) (2,3),(6,1),(3,2).
the title of your question does give away the error by the way.
Reshaping array of shape (x,) into an array of shape (x,y)
is impossible because you are trying to add more elements into your original data.
an array of shape (x,) can only be reshaped into an array of shape (x/y,y)
I hope this helps.
You are trying to reshape into an incompatible shape. Now, what do I mean by that? Look at this example:
a = np.array([[1, 2, 3],
[4, 5, 6],
])
The shape of this array is:
a.shape
>> (2, 3)
Array a has 2 x 3 = 6 elements. Let's try to reshape it into a (2, 6) array
a.reshape(2, 6)
This raises
>> ValueError: cannot reshape array of size 6 into shape (2,6)
Notice that we were trying to make an array that has 2 x 3 = 6 elements into an array that would have 2 x 6 = 12 elements. But NumPy cannot add those extra elements into your original array and give that your desired shape. So it raises ValueError.
In your case, you are trying to make an array with 6003 elements into an array that will have 6003 x 3072 = 18441216 elements!
I have a numpy array batch of shape (32,5). Each element of the batch consists of a numpy array batch_elem = [s,_,_,_,_] where s = [img,val1,val2] is a 3-dimensional numpy array and _ are simply scalar values.
img is an image (numpy array) with dimensions (84,84,3)
I would like to create a numpy array with the shape (32,84,84,3). Basically I want to extract the image information within each batch and transform it into a 4-dimensional array.
I tried the following:
b = np.vstack(batch[:,0]) #this yields a b with shape (32,3), type: <class 'numpy.ndarray'>
Now I would like to access the images (first index in second dimension)
img_batch = b[:,0] # this returns an array of shape (32,), type: <class 'numpy.ndarray'>
How can I best access the image data and get a shape (32,84,84,3)?
Note:
s = b[0] #first s of the 32 in batch: shape (3,) , type: <class 'numpy.ndarray'>
Edit:
This should be a minimal example:
img = np.zeros([5,5,3])
s = np.array([img,1,1])
batch_elem = np.array([s,1,1,1,1])
batch = np.array([batch_elem for _ in range(32)])
Assuming I understand the problem correctly, you can stack twice on the last axis.
res = np.stack(np.stack(batch[:,0])[...,0])
import numpy as np
# fabricate some data
batch = np.array((32, 1), dtype=object)
for i in range(len(batch)):
batch[i] = [np.random.rand(84, 84, 3), None, None]
# select images
result = np.array([img for img, _, _ in batch])
# double check!
for i in range(len(batch)):
assert np.all(result[i, :, :, :] == batch[i][0])
import numpy as np
a = np.array([1,2,3,4])
print a.shape[0]
Why it will output 4?
The array [1,2,3,4], it's rows should be 1, I think , so who can explain the reason for me?
because
print(a.shape) # -> (4,)
what you think (or want?) to have is
a = np.array([[1],[2],[3],[4]])
print(a.shape) # -> (4, 1)
or rather (?)
a = np.array([[1, 2 , 3 , 4]])
print(a.shape) # -> (1, 4)
If you'll print a.ndim you'll get 1. That means that a is a one-dimensional array (has rank 1 in numpy terminology), with axis length = 4. It's different from 2D matrix with a single row or column (rank 2).
More on ranks
Related questions:
numpy: 1D array with various shape
Python: Differentiating between row and column vectors
The shape attribute for numpy arrays returns the dimensions of the array. If a has n rows and m columns, then a.shape is (n,m). So a.shape[0] is n and a.shape[1] is m.
numpy arrays returns the dimensions of the array. So, when you create an array using,
a = np.array([1,2,3,4])
you get an array with 4 dimensions. You can check it by printing the shape,
print(a.shape) #(4,)
So, what you get is NOT a 1x4 matrix. If you want that do,
a = numpy.array([1,2,3,4]).reshape((1,4))
print(a.shape)
Or even better,
a = numpy.array([[1,2,3,4]])
a = np.array([1, 2, 3, 4])
by doing this, you get a a as a ndarray, and it is a one-dimension array. Here, the shape (4,) means the array is indexed by a single index which runs from 0 to 3. You can access the elements by the index 0~3. It is different from multi-dimensional arrays.
You can refer to more help from this link Difference between numpy.array shape (R, 1) and (R,).
I have an function that maps an ndarray of shape (3) to a float, and I have an ndarray of shape (...,3). What's the best way to map that function over that array to get an array of shape (...)?
Thanks.
You want numpy.apply_along_axis.
def f(a):
return a[0] + a[1] + a[2]
mm = numpy.random.randn(5, 3)
numpy.apply_along_axis(f, 1, mm)
output: array([-1.75875289, -0.34689792, 0.66092486, -0.21626001, -0.14125476])