Home>

I wanted to create a virtual environment with anaconda and do machine learning using tensorflow and keras there, so I modified the "machine learning code using images I prepared" that was lying on the net ( I made the neural network part my own idea) and tried it. Then, the file names of the images I prepared were lined up in the execution result column, and I thought it would work, but I got the following error statement.

Error statement
AttributeError Traceback (most recent call last)<ipython-input-9-ddcfcffbcd49>in<module>   59 # Squeeze
     60 model = Sequential ()
--->61 model.add (GlobalAveragePooling2D () (input))
     62 model.add (Dense (200, activation = "relu"))
     63 model.add (Dense (200, activation = "sigmoid"))
~ \ anaconda3 \ envs \ ban \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ base_layer.py in __call__ (self, inputs, * args, ** kwargs)
    892 # Eager execution on data tensors.
    893 with backend.name_scope (self._name_scope ()):
->894 self._maybe_build (inputs)
    895 cast_inputs = self._maybe_cast_inputs (inputs)
    896 with base_layer_utils.autocast_context_manager (
~ \ anaconda3 \ envs \ ban \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ base_layer.py in _maybe_build (self, inputs)
   2125 if not self.built:
   2126 input_spec.assert_input_compatibility (
->2127 self.input_spec, inputs, self.name)
   2128 input_list = nest.flatten (inputs)
   2129 if input_list and self._dtype_policy.compute_dtype is None:
~ \ anaconda3 \ envs \ ban \ lib \ site-packages \ tensorflow_core \ python \ keras \ engine \ input_spec.py in assert_input_compatibility (input_spec, inputs, layer_name)
    161 spec.min_ndim is not None or
    162 spec.max_ndim is not None):
->163 if x.shape.ndims is None:
    164 raise ValueError ('Input' + str (input_index) +'of layer' +
    165 layer_name +'is incompatible with the layer:'
AttributeError:'function' object has no attribute'shape'

Below is the full text of the code that caused the error

Source code
from tensorflow.keras.layers import Conv2D, BatchNormalization, Activation, AveragePooling2D, GlobalAveragePooling2D, Dense, Multiply, Input
from keras.activations import linear
from keras.utils import to_categorical
import numpy as np
import os, pickle, zipfile, globfrom keras.models import Sequential
from keras.layers import Activation, Dense, Dropout
from keras.utils.np_utils import to_categorical
from keras.optimizers import Adagrad
from keras.optimizers import Adam
import numpy as np
from PIL import Image
import os
image_list = []
label_list = []
for dir in os.listdir ("data/training"):
    if dir == ".DS_Store":
        continue
    dir1 = "data/training /" + dir
    label = 0
    if dir == "no":
        label = 0
    elif dir == "ok":
        label = 1
    for file in os.listdir (dir1):
        if file! = ".DS_Store":
            label_list.append (label)
            filepath = dir1 + "/" + file
          image = np.array (Image.open (filepath) .resize ((25, 25)))
            print (filepath)
            image = image.transpose (2, 0, 1)
            image = image.reshape (1, image.shape [0] * image.shape [1] * image.shape [2]). astype ("float32") [0]
            image_list.append (image/255.)
image_list = np.array (image_list)
Y = to_categorical (label_list)
model = Sequential ()
model.add (GlobalAveragePooling2D () (input))
model.add (Dense (200, activation = "relu"))
model.add (Dense (200, activation = "sigmoid"))
opt = Adam (lr = 0.001)model.compile (loss = "categorical_crossentropy", optimizer = opt, metrics = ["accuracy"])
model.fit (image_list, Y, nb_epoch = 1500, batch_size = 100, validation_split = 0.1)
total = 0.
ok_count = 0.
for dir in os.listdir ("data/training"):
    if dir == ".DS_Store":
        continue
    dir1 = "data/validation /" + dir
    label = 0
    if dir == "no":
        label = 0
    elif dir == "ok":
        label = 1
    for file in os.listdir (dir1):
        if file! = ".DS_Store":
            label_list.append (label)
            filepath = dir1 + "/" + file
            image = np.array (Image.open (filepath) .resize ((25, 25)))
            print (filepath)
            image = image.transpose (2, 0, 1)
            image = image.reshape (1, image.shape [0] * image.shape [1] * image.shape [2]). astype ("float32") [0]
            result = model.predict_classes (np.array ([image/255.]))
            print ("label:", label, "result:", result [0])
            total + = 1.
            if label == result [0]:
                ok_count + = 1.
print ("seikai:", ok_count/total * 100, "%")
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
SVG (model_to_dot (model) .create (prog ='dot', format ='svg')) Enter the language here

I didn't write the function part in the code, and when I ran the original code without any modification, I didn't get such an error. I'm stuck and I don't understand the following points
1: What caused the error?
2: What can be solved?
3: Where did the word function come from?
I'm a beginner who has no idea what I'm doing with the source code. Thank you

  • Answer # 1

    It may have already been resolved, but ...
    The error code is "the object called function does not have a method called shape", which is a common error code when touching python. function is more like a generic term used by python to issue error codes to instances, etc., rather than what the code this time is. This time, because I wrote the code incorrectly, the method called "shape" that should be used for ndarray etc. was applied to a completely different object, so an error occurred. In particular,

    if x.shape.ndims is None:


    In the part of, ndarray etc. should be stored in x originally, but it seems that some other object has been assigned due to a mistake in the code.

    It's an important code error, but as shown in the error

    model = Sequential ()
    model.add (GlobalAveragePooling2D () (input)) #<-This part
    model.add (Dense (200, activation = "relu"))
    model.add (Dense (200, activation = "sigmoid"))


    I think. Correctly

    model = Sequential ()
    model.add (GlobalAveragePooling2D ())
    model.add (Dense (200, activation = "relu"))
    model.add (Dense (200, activation = "sigmoid"))


    is not it. It seems that you are confusing how to write the Sequential model and the functioncnal API model.
    However, since it is common to insert an input layer such as model.add (Dense (32, input_dim = 784)) in the first layer, it is clear whether it will work with GlobalAveragePooling2D () in the first layer. not.