You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tf_CNN.py 1.5 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import numpy as np
  2. import tensorflow as tf
  3. def tf_conv_relu_avg(x, shape):
  4. weight = tf.Variable(np.random.normal(
  5. scale=0.1, size=shape).transpose([2, 3, 1, 0]).astype(np.float32))
  6. x = tf.nn.conv2d(x, weight, padding='SAME', strides=[1, 1, 1, 1])
  7. x = tf.nn.relu(x)
  8. x = tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
  9. padding='VALID', strides=[1, 2, 2, 1])
  10. return x
  11. def tf_fc(x, shape):
  12. weight = tf.Variable(np.random.normal(
  13. scale=0.1, size=shape).astype(np.float32))
  14. bias = tf.Variable(np.random.normal(
  15. scale=0.1, size=shape[-1:]).astype(np.float32))
  16. x = tf.reshape(x, (-1, shape[0]))
  17. y = tf.matmul(x, weight) + bias
  18. return y
  19. def tf_cnn_3_layers(x, y_):
  20. '''
  21. 3-layer-CNN model in TensorFlow, for MNIST dataset.
  22. Parameters:
  23. x: Variable(tensorflow.python.framework.ops.Tensor), shape (N, dims)
  24. y_: Variable(tensorflow.python.framework.ops.Tensor), shape (N, num_classes)
  25. Return:
  26. loss: Variable(tensorflow.python.framework.ops.Tensor), shape (1,)
  27. y: Variable(tensorflow.python.framework.ops.Tensor), shape (N, num_classes)
  28. '''
  29. print('Building 3-layer-CNN model in tensorflow...')
  30. x = tf.reshape(x, [-1, 28, 28, 1])
  31. x = tf_conv_relu_avg(x, (32, 1, 5, 5))
  32. x = tf_conv_relu_avg(x, (64, 32, 5, 5))
  33. x = tf.transpose(x, [0, 3, 1, 2])
  34. y = tf_fc(x, (7 * 7 * 64, 10))
  35. loss = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)
  36. loss = tf.reduce_mean(loss)
  37. return loss, y

分布式深度学习系统

Contributors (1)