张量流中的自定义激活函数给定,等级未定义,但图层需要定义的等级错误

时间:2019-07-10 17:12:05

标签: python tensorflow machine-learning deep-learning conv-neural-network

我正在尝试在Tensorflow中实现自己的自定义激活功能。

def leaky_relu_6(x):
    if x >=0.0 and x < 6.0:
        return x*1.0
    elif x > 6.0:
        return 6.0
    else:
        return 0.2 * x

np_leaky_relu_6= np.vectorize(leaky_relu_6)

def d_leaky_relu_6(x):
    if x >=0.0 and x < 6.0:
        return 1.0
    elif x > 6.0:
        return 0.0
    else:
        return 0.2
np_d_leaky_relu_6 = np.vectorize(d_leaky_relu_6)

def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+2))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

def relu_grad(op, grad):
    x = op.inputs[0]

    n_gr = tf_d_leaky_relu_6(x)
    return grad * n_gr  



np_leaky_relu_6_32 = lambda x: np_leaky_relu_6(x).astype(np.float32)

def tf_leaky_relu_6(x,name=None):
    with tf.name_scope(name, "leaky_relu_6", [x]) as name:
        y = py_func(np_leaky_relu_6_32,
                        [x],
                        [tf.float32],
                        name=name,
                         grad= relu_grad)
        return y[0]

np_d_leaky_relu_6_32 = lambda x: np_d_leaky_relu_6(x).astype(np.float32)


def tf_d_leaky_relu_6(x,name=None):
    with tf.name_scope(name, "d_leaky_relu_6", [x]) as name:
        y = py_func(np_d_leaky_relu_6_32,
                        [x],
                        [tf.float32],
                        name=name,
                        stateful=False)
        return y[0]

使用以下输入,代码可以正常运行。

with tf.Session() as sess:

    x = tf.constant([0.2,0.7,1.2,-8.7])
    y = tf_leaky_relu_6(x)
    tf.initialize_all_variables().run()

    print(x.eval(), y.eval(), tf.gradients(y, [x])[0].eval())

但是当我尝试将其与CNN代码一起使用进行分类时。

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
  conv1_act = tf.placeholder(tf.float32, [4,])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same")
      #activation=tf.nn.relu6)   
      #activation =tf_leaky_relu_6)

  conv1_act = tf_leaky_relu_6(conv1)

  print(tf.shape(conv1_act))  
  #output of the above print statement: Tensor("Shape:0", shape=(?,), dtype=int32)

  pool1 = tf.layers.max_pooling2d(inputs=conv1_act, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu6) #to try other activation function replcae relu6 by leaky_relu or relu
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu6) #to try other activation function replcae relu6 by leaky_relu or relu
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  predictions = {
      # Generate predictions (for PREDICT and EVAL mode)
      "classes": tf.argmax(input=logits, axis=1),
      # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
      # `logging_hook`.
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
  }

  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

  # Calculate Loss (for both TRAIN and EVAL modes)
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
  eval_metric_ops = {
      "accuracy": tf.metrics.accuracy(
          labels=labels, predictions=predictions["classes"])
  }
  return tf.estimator.EstimatorSpec(
      mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

((train_data, train_labels),
 (eval_data, eval_labels)) = tf.keras.datasets.mnist.load_data()

train_data = train_data/np.float32(255)
train_labels = train_labels.astype(np.int32)  # not required

eval_data = eval_data/np.float32(255)
eval_labels = eval_labels.astype(np.int32)  # not required

mnist_classifier = tf.estimator.Estimator(
    model_fn=cnn_model_fn)

train_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": train_data},
    y=train_labels,
    batch_size=100,
    num_epochs=None,
    shuffle=True)
# train one step and display the probabilties
#mnist_classifier.train(input_fn=train_input_fn, steps=1,hooks=[logging_hook])
mnist_classifier.train(input_fn=train_input_fn, steps=1,)

当我运行上述代码时,它给我以下错误:ValueError:max_pooling2d_1层的输入0与该层不兼容:其等级未定义,但该层需要定义的等级。

错误来自以下行:pool1

0 个答案:

没有答案