之前十一,十二章节,使用的都是TF1.0的版本和概念进行讲解。
现在TF升级到2.0了,变化蛮大,至少不大像兼容的样子。跑之前的 十一,十二章节代码,跑不动。
TF2.0主要用到的是keras包,这个确实写起来比1.0要简介非常非常多。下来逐个讲解。
首先安装,官网的,参考如下:
使用 pip 安装 TensorFlow
按顺序装吧,注意中途需要安装的插件,尽管安装即可。
注意,里面需要一个python的虚拟环境,这个我们直接用PyCharm吧,创建新项目本身就是一个干净的环境了。
这里有个坑。这个版本号称是支持CPU和GPU版本,但实际上我装上去后,直接还是报没有GPU的错。(当然,也有可能是因为我的电脑本身有英伟达的显卡原因)
按照错误提示,打开对应的网址(TF官方的),这里要按照里面的要求步骤,逐个逐个的安装英伟达的驱动,工具等(有链接地址)注意,英伟达官网的驱动和工具下载选项里面有一个10,11,这个不是工具版本,而是win10,还是win11,我被这个可坑惨了。
一系列安装操作结束,设置环境变量,再跑代码,这个时候会告警:
2021-11-11 19:13:02.870676: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2021-11-11 19:13:03.326665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 2788 MB memory: -> device: 0, name: Quadro P620, pci bus id: 0000:01:00.0, compute capability: 6.1
估计GPU还是没装上,不过代码已经能跑了,就不管了。
开跑TF训练,先来个经典的神经网络,官网入门级的教程就有:
import tensorflow as tf
#获取训练数据,返回的对象是NumPy 数组
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
#创建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),#输入层,将二维的图片28*28的数据展平成1*784
tf.keras.layers.Dense(128, activation='relu'),#第一个隐藏层,输出是一个1*128的数据
tf.keras.layers.Dropout(0.2),#过拟合处理,压平数据
tf.keras.layers.Dense(10, activation='softmax')#第二个隐藏层,并输出1*10结果
])
#设定梯度迭代公式
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#喂数据,进行训练
model.fit(x_train, y_train, epochs=5)
#验证数据
model.evaluate(x_test, y_test)
代码很简单,我们看看输入的数据的结构:
print(x_train.shape) print(y_train.shape) (60000, 28, 28) (60000,)
x输入层,有60000个然后是一个28*28的一个数组,数组里面是0-255的灰度颜色值



