“ValueError:使用序列设置数组元素” - 尝试将列表提供到feed_dict中的占位符时

时间:2017-11-15 19:13:55

标签: python machine-learning tensorflow neural-network valueerror

我必须承认我是初学者,但在StackOverflow或Github中提出的任何问题上,我无法找到问题的答案。请帮忙

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-a9ebf2ee96c3> in <module>()
     19             _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
     20                                                             v_i: np.array(onehot_item),
---> 21                                                             label:label_list})
     22             # Compute average loss
     23             avg_cost += c / total_batch

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             feed_handles[subfeed_t] = subfeed_val
   1092           else:
-> 1093             np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
   1094 
   1095           if (not is_tensor_handle_feed and

~/anaconda3/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529 
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532 
    533 

ValueError: setting an array element with a sequence.

# Loading data
t1 = time()
dataset = Dataset("/Users/shishir/Documents/botconnect_Playground/NCF_Prototype/Data/ml-1m")
train, testRatings, testNegatives = dataset.trainMatrix, dataset.testRatings, dataset.testNegatives
num_users, num_items = train.shape
print("Load data done [%.1f s]. #user=%d, #item=%d, #train=%d, #test=%d" 
      %(time()-t1, num_users, num_items, train.nnz, len(testRatings)))

“Train”是一个看起来像的矩阵:[(user_id,item_id)implicit_rating ....]

[  (0, 0)   1.0
  (0, 1)    1.0
  (0, 2)    1.0
  (0, 3)    1.0
  (0, 4)    1.0
  (0, 5)    1.0
  (0, 6)    1.0
  (0, 7)    1.0
  (0, 8)    1.0
  (0, 9)    1.0
  (0, 10)   1.0
  (0, 11)   1.0
  (0, 12)   1.0
  (0, 13)   1.0
  (0, 14)   1.0
  (0, 15)   1.0
  (0, 16)   1.0
  (0, 17)   1.0
  (0, 18)   1.0
  (0, 19)   1.0
  (0, 20)   1.0
  (0, 21)   1.0
  (0, 22)   1.0
  (0, 23)   1.0
  (0, 24)   1.0
  : :
  (0, 28)   1.0
  (0, 29)   1.0
  (0, 30)   1.0
  (0, 31)   1.0
  (0, 32)   1.0
  (0, 33)   1.0
  (0, 34)   1.0
  (0, 35)   1.0
  (0, 36)   1.0
  (0, 37)   1.0
  (0, 38)   1.0
  (0, 39)   1.0
  (0, 40)   1.0.....]

构建MLP的代码:

with tf.name_scope('MLP'):

   # num_layer = [20,10]


    # Network Parameters
    n_input = 1 #Dimensions of concatenated input vector
    n_hidden_1 = 40 # 1st layer number of neurons
    n_hidden_2 = 5 # 2nd layer number of neurons
    n_out = 1

    latent_dim=1

     #Input Variables
    with tf.name_scope('Input'):
        label = tf.placeholder(tf.float32, name='label1')
        v_u = tf.placeholder(tf.int32, [1,num_users], name='user_input')
        v_i = tf.placeholder(tf.int32, [1,num_items], name='item_input')

    with tf.name_scope('Embeddings'):
        P_M = tf.truncated_normal([num_users,n_input], stddev=0.1)
        tf.Variable(P_M,name="P_M")
        embedded_users = tf.matmul(tf.to_float(v_u),P_M)

        Q_M = tf.truncated_normal([num_items,n_input], stddev=0.1)
        tf.Variable(Q_M,name="Q_M")
        embedded_items = tf.matmul( tf.to_float(v_i),Q_M)

    # The 0-th layer is the concatenation of embedding layers
    concat_vector = tf.concat([embedded_users, embedded_items], 0)
    with tf.name_scope("MLP_Layers"):

        # Parameters
        learning_rate = 0.01
        training_epochs = 15
        batch_size = 100
        display_step = 1



        # Store layers weight & bias
        weights = {
            'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1]), name='Weight1'),
            'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name='Weight2'),
            'out': tf.Variable(tf.random_normal([n_hidden_2, n_out]), name='Weight_Output')}
        biases = {
            'b1': tf.Variable(tf.random_normal([n_hidden_1]), name='Bias1'),
            'b2': tf.Variable(tf.random_normal([n_hidden_2]), name='Bias2'),
            'out': tf.Variable(tf.random_normal([n_out]), name='Bias_Output')}
    with tf.name_scope("Model"):

        # Create model
        def mlp(x):
            layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='Layer1')
            layer_1_out = 1/(1 + tf.exp(-layer_1))
            layer_2 = tf.add(tf.matmul(layer_1_out, weights['h2']), biases['b2'], name='Layer2')
            layer_2_out = 1/(1 + tf.exp(-layer_2))
            final_layer = tf.add(tf.matmul(layer_2, weights['out']),biases['out'], name='Output_Layer')
            out_layer = 1/(1 + tf.exp(-final_layer))
            return out_layer

从训练矩阵构建输入的代码:

def get_training_data(train, num_negatives):
    user_input, item_input, labels = [],[],[]
    num_users = train.shape[0]
    for (u, i) in train.keys():
        # positive instance
        user_input.append(u)
        item_input.append(i)
        labels.append(1)
        # negative instances
        for t in range(num_negatives):
            j = np.random.randint(num_items)
            while (u,j) in train.keys():
                j = np.random.randint(num_items)
            user_input.append(u)
            item_input.append(j)
            labels.append(0)
    return user_input, item_input, labels

构建模型:

# Build model

prediction = mlp(concat_vector)
init = tf.global_variables_initializer()

 # Define loss and optimizer
with tf.name_scope('cross_entropy'):
    loss_op = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction, labels=label))
    tf.summary.scalar('cross_entropy', loss_op)

with tf.name_scope('train'):    
    optimizer = tf.train.AdamOptimizer(learning_rate=0.15)
    train_op = optimizer.minimize(loss_op)

# Initializing the variables
init = tf.global_variables_initializer()

最后培训(导致错误的代码)

num_epochs=1
num_negatives=3
# Training model
with tf.Session() as sess:
    for epoch in range(num_epochs):
        t1 = time()
        # Generate training instances
        user_input, item_input, labels = get_training_data(train, num_negatives)
        onehot_user = (tf.one_hot(user_input,len(user_input)))
        onehot_item = (tf.one_hot(item_input,len(item_input)))
        label_list = np.array(labels)


        total_batch = int(len(user_input))
        # Training
        for i in range(total_batch):

            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={v_u: np.array(onehot_user),
                                                            v_i: np.array(onehot_item),
                                                            label:label_list})
            # Compute average loss
            avg_cost += c / total_batch
            print("Batch:", '%04d' % (i),"Completed")
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
        print("Optimization Finished!")

        t2 = time()

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs', sess.graph)

任何调试的想法??

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您的label_list变量是一个整数数组,但label占位符需要tf.float32个值。如果你切换其中一种类型,它应该可以正常工作。