作者 | Aymeric Damien
编辑 | 奇予纪
出品 | 磐创AI团队
原项目 | https://github.com/aymericdamien/TensorFlow-Examples/
大多数示例使用手写数字的MNIST数据集。该数据集包含60,000个用于训练的示例和10,000个用于测试的示例。这些数字已经过尺寸标准化并位于图像中心,图像是固定大小(28x28像素),其值为0到1。为简单起见,每个图像都被平展并转换为784(28 * 28)个特征的一维numpy数组。
mark
在我们的示例中,我们使用TensorFlow input_data.py脚本来加载该数据集。
它对于管理我们的数据非常有用,并且可以处理:
# 导入 MNIST
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# 加载数据
X_train = mnist.train.images
Y_train = mnist.train.labels
X_test = mnist.test.images
Y_test = mnist.test.labels
next_batch
函数,可以遍历整个数据集并仅返回所需的数据集样本部分(以节省内存并避免加载整个数据集)。# 获取接下来的64个图像数组和标签
batch_X, batch_Y = mnist.train.next_batch(64)
[1]: http://yann.lecun.com/exdb/mnist/
使用TensorFlow v2张量的一个简单的“hello world”示例
import tensorflow as tf
# 创建一个张量
hello = tf.constant("hello world")
print hello
Output:
tf.Tensor(hello world, shape=(), dtype=string)
# 访问张量的值,调用numpy()
print hello.numpy()
output:
hello world
使用TensorFlow v2的基本张量操作
from __future__ import print_function
import tensorflow as tf
# 定义张量常量
a = tf.constant(2)
b = tf.constant(3)
c = tf.constant(5)
# 各种张量操作
# 注意:张量也支持python的操作(+,*,...)
add = tf.add(a,b)
sub = tf.subtract(a,b)
mul = tf.multiply(a,b)
div = tf.divide(a,b)
# 访问张量的值
print("add=",add.numpy())
print("sub=",sub.numpy())
print("mul=",mul.numpy())
print("div=",div.numpy())
output:
add= 5
sub= -1
mul= 6
div= 0.6666666666666666
# 更多一些操作
mean = tf.reduce_mean([a,b,c])
sum =tf.reduce_sum([a,b,c])
# 访问张量的值
print("mean=",mean.numpy())
print("sum=",sum.numpy())
output:
mean= 3
sum= 10
# 矩阵乘法
matrix1 = tf.constant([[1,2],[3,4]])
matrix2 = tf.constant([[5,6],[7,8]])
product = tf.matmul(matrix1,matrix2)
# 展示张量
product
output:
<tf.Tensor: id=74, shape=(2, 2), dtype=int32, numpy=
array([[19, 22],
[43, 50]])>
# 将张量转换为Numpy
product.numpy()
output:
array([[19., 22.],
[43., 50.]], dtype=float32)