美文网首页
安装 tensorflow2.0

安装 tensorflow2.0

作者: noodu | 来源:发表于2019-03-10 13:08 被阅读0次

谷歌发布了tensorflow2.0的alpha 版本,让我们来一睹为快.
作者的系统是ubuntu,为了简化安装,使用了官方的docker镜像

sudo docker pull tensorflow/tensorflow:2.0.0a0-gpu-py3

2.0.0a0-gpu-py3-jupyter是镜像的标签,它代表是tensorflow的2.0.0a0版本,支持GPU加速,python的版本是3.x.
可以根据自己的实际情况选择其他标签

在镜像文件下载完之后,可以查看确认

sudo docker image ls

可以看到刚才我们pull的镜像文件。现在我们来运行

sudo docker run --runtime=nvidia -it --rm tensorflow/tensorflow:2.0.0a0-gpu-py3 \
   python -c "import tensorflow as tf; print(tf.__version__)"

如果没什么意外,终端会显示

2.0.0-alpha0

到此,安装完毕,接下来我们可以试试这个新玩具。
为了方便,我们把系统文件目录~/Documents挂载到容器里/data

sudo docker run --runtime=nvidia --rm -it -v ~/Documents:/data tensorflow/tensorflow:2.0.0a0-gpu-py3 bash

这个命令运行后会打开一个交互式终端,由于完成了文件目录的挂载, 我们可以在系统中编辑文件,在容器中运行。
现在可以用你喜欢的编辑器输入以下代码

from __future__ import absolute_import, division, print_function

import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D

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)),
  tf.keras.layers.Dense(64, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

model.evaluate(x_test, y_test)

这段代码来自tensorflow官网,完成了手写图像的识别。
一些简单的注解
把28*28大小的图像数据变成一维度(压扁,  tf.keras.layers.Flatten)
使用的是全连接的网络tf.keras.layers.Dense, 最后用softmax完成分类。中间加入了 tf.keras.layers.Dropout(0.2)来减少过拟合。 大家可以改动其中的参数, 然后在容器的终端运行这个程序,看看结果有什么不同。
接下来,我们会用卷积神经网络来实现同样的功能。

相关文章

网友评论

      本文标题:安装 tensorflow2.0

      本文链接:https://www.haomeiwen.com/subject/owxupqtx.html