I think Image objects have size attributes and arrays have shape attributes. Try renaming it in your code. (See : http://effbot.org/imagingbook/image.htm)
Answer from Daneel on Stack OverflowAttributeError: 'NoneType' object has no attribute 'shape' - imgcodecs - OpenCV
Cannot do inference on a model AttributeError: 'Image' object has no attribute 'shape'. Did you mean: 'save'?
python - the question of 'list' object has no attribute 'shape' - Stack Overflow
I get a weird " 'function object has no attribute 'shape' " for a parameter which is clearly not an object, just a numpy array.
I'm implementing a cost function for a neural network, which takes in the predictions made on the training set by the forward propagation step, the true output labels Y, and calculates the cost of the model. The function definition is -
def calculate_cost (Y, prediction, activation_output = 'sigmoid'):
"""
Calculates the cost.
Takes in the output labels and the prediction from forward propagation, as well as the activation function of the output layer.
Returns the cost.
"""
m = Y.shape[1]
if activation_output.lower() == 'sigmoid':
cost = (1/m)*np.sum(Y*np.log(prediction) + (1-Y)*np.log(1-prediction))
if activation_output.lower() == 'softmax':
cost = (1/m)*np.sum(np.sum(Y*np.log(prediction), axis = 0, keepdims = True))
return costI get an error on the line where I declare m as the second dimension of the input parameter Y.
<ipython-input-6-0c38b0031612> in calculate_cost(Y, prediction, activation_output)
10 """
---> 11 m = Y.shape[1]
12
13 if activation_output.lower() == 'sigmoid':
AttributeError: 'function' object has no attribute 'shape'Why is this happening? Y is clearly a numpy array.
I am calling a function model() which I have defined which takes in the input data set, the corresponding output labels, and a few hyperparameters and trains the model. This is the function definition for the model() function -
def model (X, Y, architecture, activation_functions, learning_rate = 0.001, print_cost = True, number_of_iterations = 10000):
"""
Takes in the training set X, the labels Y, and all the required parameters and trains the defined model for the given number of iterations.
Prints the cost if print_cost is true.
"""
costs = []
number_of_layers = len(architecture) - 1
parameters = initialize_parameters(architecture)
for i in range(number_of_iterations):
prediction, cache = forward_propagation(X, parameters, number_of_layers, activation_functions)
cost = calculate_cost(Y, prediction, activation_functions[-1])
costs.append(cost)
gradients = backward_propagation(X, Y, cache, number_of_layers)
parameters = update_parameters(parameters, number_of_layers, gradients, alpha=0.01)
if print_cost and i%100 == 0:
print(f'Completed {i} iterarions.\n')
print(f'Cost after iteration {i} = {cost}')
plt.plot(costs)
plt.xlabel('Iterations (in hundereds)')
plt.ylabel('Cost')
plt.title(f'Learning rate = {learning_rate}')
plt.show()
print(f'Ran {number_of_iterations} iterations. Returning parameters now.')
print(f'The final cost of the model was: {costs[-1]}')
print(f'The training accuracy was: {calculate_accuracy(X, Y, parameters, number_of_layers, activation_functions)}')
return parametersI am calling the function like this -
X_train = pd.read_csv('training_set.csv', header = None).to_numpy()
Y_train = pd.read_csv('training_labels.csv', header = None).to_numpy
model(X_train, Y_train, [10,5,5,1], ['relu','relu','relu','relu','sigmoid'])The second parameter Y_train gets passed to the calculate_cost() function. And Y_train is clearly an array:/
It means that somewhere a function which should return a image just returned None and therefore has no shape attribute. Try "print img" to check if your image is None or an actual numpy object.
I faced the same problem today, please check for the path of the image as mentioned by cybseccrypt. After imread, try printing the image and see. If you get a value, it means the file is open.
Code:
Copyimg_src = cv2.imread('/home/deepak/python-workout/box2.jpg',0)
print img_src
Hope this helps!
Use numpy.array to use shape attribute.
>>> import numpy as np
>>> X = np.array([
... [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
... [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
... [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]
... ])
>>> X.shape
(3L, 3L, 1L)
NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.
Alternatively, you can use np.shape(...)
For instance:
import numpy as np
a=[1,2,3]
and np.shape(a) will give an output of (3,)