写在前面:Google在2019年发行了TensorFlow 2,这个版本借用了Keras的一些语法,与TensorFlow 1有一些不同。该Tutorial是在TensorFlow 1环境中以Jupyter Notebook来进行的。
该Tutorial是参照Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization的TensorFlow编程作业来完成的。
1 TensorFlow 1.x的安装和使用
首先需要注意两点,1)TensorFlow 1.x版本是分CPU和GPU版本的,2)TensorFlow 1.x的Python 3版本是一定要在Python 3.5-3.7之间,低了高了都不行。
1.1 安装
- 通过Conda来创建包含Python 3.7的名为tf1的虚拟环境
conda create -n tf1 python=3.7
- 激活tf1虚拟环境
Conda activate tf1
- 升级pip版本 (由于安装的是Python 3.7版本,该步可省略)
pip install —upgrade pip
- 安装TensorFlow 1.15版本(这是1.x的最后一个版本)
pip install tensorflow==1.15
- 验证是否安装成功
python -c “import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))”
详细的安装要求和过程可以参考官网: https://www.tensorflow.org/install/pip
1.2 使用
使用TensorFlow 1.x来编写和运行程序时,一般需要以下五个步骤:
- 创建Tensors (即变量)
- 编写Tensors之间的运算方法
- 初始化Tensors
- 创建一个Session
- 运行Session
y_hat = tf.constant(36, name=‘y_hat’)
y = tf.constant(39, name=‘y’)
loss = tf.Variable((y - y_hat)**2, name=‘loss’)
init = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
print(session.run(loss))
如果不创建Session并运行这个Session的话,会得不到期望的结果,而是一个空的Tensor: (tf.Variable ‘loss_1:0’ shape=() dtype=int32)
因为All you did was put in the ‘computation graph’, but you have not run this computation yet.
placeholder
另外一种定