Search code examples
pythontensorflowkerasdeep-learningrecommendation-engine

How to Fix "model expected. Expected to see 2 array(s), but instead got ...." and " '_thread._local' object has no attribute 'value' "


I'm trying to build Matrix factorization model with deep learning and deploy it using flask. I also use apscheduler to retrain the model from new inputs. Here is the model.

Model has 2 inputs cloth_ids, user_ids and one outputs ratings. both inputs and the output has the shape of 1D

    #tensorflow version - 2.1.0
    #keras version - 2.3.1


    user_input = Input(shape=(1,))
    cloth_input = Input(shape=(1,))

    user_embedding = Embedding(self.n_users, embedding_dimR)(user_input)
    cloth_embedding = Embedding(self.n_cloths, embedding_dimR)(cloth_input)

    user_embedding = Flatten()(user_embedding)
    cloth_embedding = Flatten()(cloth_embedding)

    x = Concatenate()([user_embedding, cloth_embedding])
    # x = Dense(denseR, activation='relu')(x)
    x = Dense(R_hidden, activation='relu', name='dense1')(x)
    x = Dense(R_hidden, activation='relu', name='dense2')(x)
    x = Dense(R_hidden, activation='relu', name='dense3')(x)
    x = Dense(R_out, activation='relu', name='dense_out')(x)

    model = Model(
        inputs=[user_input, cloth_input],
        outputs=x
        )

    self.model = model

    self.model.fit(
        x=[self.train_user_ids,self.train_cloth_ids],
        y=self.train_ratings,
        batch_size=batch_sizeR,
        epochs=num_epochsR,
        validation_data=(
            [self.test_user_ids,self.test_cloth_ids],
            self.test_ratings
            )
        )

    self.model.predict([[user_id],[cloth_id]])
    # user_id, cloth_id are integers

1) First I used tensorflow.keras for import layer, model APIs and metrics. Then I got following error while do predictions but apscheduler worked properly

    ValueError: Error when checking model input: the list of Numpy arrays that you are passing
    to your model is not the size the model expected. Expected to see 2 array(s), for inputs 
    ['input_11', 'input_12'] but instead got the following list of 1 arrays: [array([[23],
    [ 0]], dtype=int64)]...

2) After I used keras instead of tensorflow.keras then model.predict worked properly but the apscheduler got the following error

    Job "train_task (trigger: interval[0:00:20], next run at: 2020-05-08 12:22:29 +0530)" raised
    an exception
    AttributeError: '_thread._local' object has no attribute 'value'

Downgrading keras to 2.2.5 or using debug=False, threaded=False inside app.run() not working. Please Help Me, Thanks


Solution

  • I just reshape the user_id and cloth_id as follows and it works.

      u =  np.array([user_id]).reshape(-1,1)
      c =  np.array([cloth_id]).reshape(-1,1)
      rating = float(self.model.predict([u,c]).squeeze())