InvalidArgumentError:不兼容的形状:[10000,6]与[10000,6,6]:自定义成本函数

时间:2018-11-24 17:24:34

标签: python tensorflow neural-network deep-learning

我正在Tensorflow框架中为Conv神经网络实现NDCG成本函数。输入数据是形状为(1499668,6,15,1)的数组,目标值是形状(1499668,6)

# log 2 with tensorflow
def log2(x):
    num = tf.log(x)
    den = tf.log(tf.constant(2,dtype=num.dtype))
    return num/den

#Create input placeholders
x = tf.placeholder("float", shape=[None, 6,15,1])
y = tf.placeholder("float", shape=[None, n_classes])
target_logs = tf.placeholder("float",shape=[None, n_classes])

#Define convolutional layer
def conv2d(x, W, b, strides=1, reuse=True):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

#Define Maxpool layer
def maxpool2d(x, k=2):
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],padding='SAME')

#Define a convolutional neural network function
def conv_net(x, weights, biases):  
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    conv1 = maxpool2d(conv1, k=2)

    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    conv2 = maxpool2d(conv2, k=2)

    conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])
    conv3 = maxpool2d(conv3, k=2)

    conv4 = conv2d(conv3, weights['wc4'], biases['bc4'])
    conv4 = maxpool2d(conv4, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv4, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Output, class prediction 
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

#Define Loss and Activation functions
pred = conv_net(x, weights, biases)
print(pred.shape)


# Get the indices of sorted predictions
sort_op,sort_indices = tf.nn.top_k(pred,k=6)
sort_op_act,sort_indices_act = tf.nn.top_k(y,k=6)
# Applying the sorting to log values
sort_log_vals = tf.gather(target_logs,sort_indices)


dcg_cost_a = tf.reduce_sum(tf.squared_difference(tf.reduce_sum(tf.divide(y,sort_log_vals),0),tf.reduce_sum(tf.divide(sort_op_act,target_logs),0)))
dcg_cost = tf.reduce_sum(tf.squared_difference(tf.reduce_sum(tf.divide(sort_op,target_logs),0),tf.reduce_sum(tf.divide(sort_op_act,target_logs),0)))
cr_ent_cost_sg = tf.losses.sigmoid_cross_entropy(y,pred)
tot_cost = dcg_cost + cr_ent_cost_sg + dcg_cost_a

#cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred, labels=y))
#optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(tot_cost)

Optimizer = tf.train.AdamOptimizer()
optim = Optimizer.minimize(loss=dcg_cost)
optim2 = Optimizer.minimize(loss=cr_ent_cost_sg)
optim3 = Optimizer.minimize(loss=tot_cost)

#Evaluate Model
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))

#calculate accuracy across all the given data and average them out. 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

#Train and Test the Model
with tf.Session() as sess:
    sess.run(init) 
    train_loss = []
    test_loss = []
    train_accuracy = []
    test_accuracy = []
    summary_writer = tf.summary.FileWriter('./Output', sess.graph)
    for i in range(training_iters):
        for batch in range(len(train_np)//batch_size):
            batch_x = train_np[batch*batch_size:min((batch+1)*batch_size,len(train_np))]
            batch_y = train_np_y[batch*batch_size:min((batch+1)*batch_size,len(train_np_y))]
            print(batch_y.shape)
            print(batch_x.shape)
            # Run optimization op and Calculate batch loss and accuracy
            ##opt = sess.run(optimizer, feed_dict={x: batch_x,
            ##                                     y: batch_y})

            num_rows, num_cols = batch_y.shape

            y_logs = np.asarray([np.log2(np.arange(2,8)) for itr in range(0,num_rows)])
            print(y_logs.shape)

            v1,lv = sess.run([optim,dcg_cost],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs})
            print(lv)
            v2,lv2 = sess.run([optim2,cr_ent_cost_sg],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs})
            print(lv2)
            v3,lv3 = sess.run([optim3,tot_cost],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs})
            print (lv+lv2,lv3)

输出如下

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1321     try:
-> 1322       return fn(*args)
   1323     except errors.OpError as e:

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
   1306       return self._call_tf_sessionrun(
-> 1307           options, feed_dict, fetch_list, target_list, run_metadata)
   1308 

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
   1408           self._session, options, feed_dict, fetch_list, target_list,
-> 1409           run_metadata)
   1410     else:

InvalidArgumentError: Incompatible shapes: [10000,6] vs. [10000,6,6]
     [[Node: truediv_44 = RealDiv[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_Placeholder_2_0_1, GatherV2_11)]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-85-33963d934f68> in <module>()
     26             v2,lv2 = sess.run([optim2,cr_ent_cost_sg],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs})
     27             print(lv2)
---> 28             v3,lv3 = sess.run([optim3,tot_cost],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs})
     29             print (lv+lv2,lv3)
     30 

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    898     try:
    899       result = self._run(None, fetches, feed_dict, options_ptr,
--> 900                          run_metadata_ptr)
    901       if run_metadata:
    902         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1133     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1134       results = self._do_run(handle, final_targets, final_fetches,
-> 1135                              feed_dict_tensor, options, run_metadata)
   1136     else:
   1137       results = []

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1314     if handle is None:
   1315       return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1316                            run_metadata)
   1317     else:
   1318       return self._do_call(_prun_fn, handle, feeds, fetches)

/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1333         except KeyError:
   1334           pass
-> 1335       raise type(e)(node_def, op, message)
   1336 
   1337   def _extend_graph(self):

InvalidArgumentError: Incompatible shapes: [10000,6] vs. [10000,6,6]
     [[Node: truediv_44 = RealDiv[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_Placeholder_2_0_1, GatherV2_11)]]

Caused by op 'truediv_44', defined at:
  File "/usr/local/anaconda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/local/anaconda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/anaconda/lib/python3.6/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/anaconda/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/anaconda/lib/python3.6/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/anaconda/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-72-9bbef16c3cc3>", line 13, in <module>
    dcg_cost_a = tf.reduce_sum(tf.squared_difference(tf.reduce_sum(tf.divide(y,sort_log_vals),0),tf.reduce_sum(tf.divide(sort_op_act,target_logs),0)))
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 198, in divide
    return x / y
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 847, in binary_op_wrapper
    return func(x, y, name=name)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 955, in _truediv_python3
    return gen_math_ops.real_div(x, y, name=name)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py", line 5704, in real_div
    "RealDiv", x=x, y=y, name=name)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3414, in create_op
    op_def=op_def)
  File "/usr/local/anaconda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1740, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): Incompatible shapes: [10000,6] vs. [10000,6,6]
     [[Node: truediv_44 = RealDiv[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_Placeholder_2_0_1, GatherV2_11)]]

该脚本错误位于:v3,lv3 = sess.run([optim3,tot_cost],feed_dict={x:batch_x,y:batch_y,target_logs:y_logs}) 以前的计算(v1,lv1和v2,lv2)在相同的字典输入下也可以正常工作。不太确定是什么导致这种形状不兼容。感谢任何输入。

0 个答案:

没有答案