tensorflow 安装错误的错误,怎么解决

本文记录一下自己在使用TensorFlow的过程中,遇到的较为困扰的问题及最终的解决方法。
Q1. 如何查看TensorFlow中Tensor, Variable, Constant的值?TensorFlow中的许多方法返回的都是一个Tensor对象。在Debug的过程中,我们发现只能看到Tensor对象的一些属性信息,无法查看Tensor具体的输出值;而对于Variable和Constant,我们很容易对其进行创建操作,但是如何得到它们的值呢?
假设ts是我们想要查看的对象(Variable / Constant / 0输入的Tensor),运行
ts_res = sess.run(ts)
print(ts_res)
其中,sess为之前创建或默认的session. 运行后将得到一个narray格式的ts_res对象,通过print函数我们可以很方便的查看其中的内容。
但是,如果ts是一个有输入要求的Tensor,需要在查看其输出值前,填充(feed)输入数据。如下(假设ts只有一种输入):
input = ××××××
# the input data need to feed
ts_res = sess.run(ts, feed_dict=input)
print(ts_res)
其他要求多种输入的Tensor类似处理即可。
Q2. 模型训练完成后,如何获取模型的参数?模型训练完成后,通常会将模型参数存储于/checkpoint/×××.model文件(当然文件路径和文件名都可以更改,许多基于TensorFlow的开源包习惯将模型参数存储为model或者model.ckpt文件)。那么,在模型训练完成后,如何得到这些模型参数呢?
需要以下两个步骤:
Step 1: 通过tf.train.Saver()恢复模型参数
saver = tf.train.Saver()
通过saver的restore()方法可以从本地的模型文件中恢复模型参数。大致做法如下:
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
W = tf.Variable(...)
b = tf.Variable(...)
y_ = tf.add(b, tf.matmul(x, w))
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, "/your/path/model.ckpt")
print("Model restored.")
pred = sess.run(y_, feed_dict={batch_x})
有关TensorFlow中变量的创建、存储及恢复操作,详细见.
Step 2: 通过tf.trainable_variables()得到训练参数
tf.trainable_variables()方法将返回模型中所有可训练的参数,详细见。类似于以下的变量参数不会被返回:
tf_var = tf.Variable(0, name="××××××", trainable=False)
还可以通过Variable的name属性过滤出需要查看的参数,如下:
= [v for v in t_vars if v.name == "W"]
(不断更新中…)
本文结束,感谢欣赏。
欢迎转载,请注明本文的链接地址:他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)请选择类别建议投诉 提交
翻译进度:已翻译&&&& 翻译赏金:10 元&()&&&
& 参与翻译: (27), (13), (8), (7), (6)介绍让我们帮你从头开始安装并运行 TensorFlow 吧!但在开始之前,先来看看一个最简单的使用 TensorFlow Python API 的示例代码,这样你就会对我们接下来要做的事情有所了解。这是一个 Python 小程序,该程序生成一个二维数组并使之填充到一条线中。
import tensorflow as tf
import numpy as np
# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
# Minimize the mean squared errors.
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# Before starting, initialize the variables.
We will 'run' this first.
init = tf.global_variables_initializer()
# Launch the graph.
sess = tf.Session()
sess.run(init)
# Fit the line.
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(W), sess.run(b))
# Learns best fit is W: [0.1], b: [0.3]这段代码的第一部分构建了数据流图。 TensorFlow 只有在会话创建以及run方法被调用了以后才会真正运行计算任务。为进一步激起你的兴趣,&我们建议你看看一个经典的机器学习问题在TensorFlow看起来是什么样子的。在神经网络的世界里,最&经典&的经典问题是MNIST手写体数字的识别。我们在这里提供两个介绍,一个是为机器学习的新手看的,另一个则是为专业人员看的。如果你已经在其他的软件包里训练过几十个MNIST模型,请阅读红色部分。如果你从来没有听说过MNIST,那就一定要阅读蓝色部分。如果你在中间的某个位置,我们建议简略阅读蓝色部分,然后再阅读红色部分。Images 许可 CC BY-SA 4.0; W. Carter 原创如果你确认你已经学习并安装了 TensorFlow ,那么你可以跳过这些步骤。但你仍需要了解 MNIST -- 我们的例子中也使用到了 MNIST ,这是我们专门针对 TensorFlow 特性而精心设计的。下载并安装你可以使用官方提供的二进制包或者从 github 源码中安装 TensorFlow。要求TensorFlow Python API 支持 Python 2.7 和 Python 3.3+.GPU 版本与&Cuda Toolkit 8.0 和 cuDNN v5 搭配最佳。其他版本也支持 (Cuda toolkit &= 7.0 and cuDNN &= v3) ,但只能通过源码的方式安装。详情请看&&。如果你的系统是 Mac OS X,请看&.概述我们支持多种方式安装&TensorFlow:: 在你的机器中安装 TensorFlow,可能需要升级已安装的 Python 包。可能会影响已有的 Python 程序的执行。: 将 TensorFlow 安装到其独立的目录,不会影响任何已有的 Python 程序。: 在运行有 Anaconda Python 分发版的独立环境中安装 TensorFlow。不会影响你机器中已有的 Python 程序。: 使用一个独立的 Docker 容器运行 TensorFlow,该容器与其他程序是隔离的。: 通过&pip 链构建&TensorFlow ,并使用 pip 进行安装如果你熟悉 Pip、Virtualenv、Anaconda 或者是 Docker 的话,那么只需遵循指示就可以轻松满足你的需求。pip 和 Docker 映像的名称在相关安装章节中已经列出。如果你安装过程中发生错误,可以从&&获得一些解决方案。Pip 安装&是一个包管理系统,用于安装和管理使用 Python 编写的软件包。我们在 Linux、Mac OS X 以及 Windows 下提供 TensorFlow 的 pip 包。对于 Windows 系统,可以阅读&.在 pip 安装的过程中将会安装并升级很多的包,这些包都在&&这里列表出来了。安装 pip (或者是 pip3 for python3)# Ubuntu/Linux 64-bit $ sudo apt-get install python-pip python-dev # Mac OS X $ sudo easy_install pip $ sudo easy_install --upgrade six我们同时也上传了二进制文件到 Pypi,你可以通过 pip 简单的在 Windows、Linux 和 Mac 上安装。注意你需要 pip 的版本至少为 8.1 ,这样才能在 Linux 下使用:$ pip install tensorflow为了安装对 GPU 的支持,需要:$ pip install tensorflow-gpu如果上述命令无法在你的系统中正常执行,请看看下面的指引:安装 TensorFlow:# Python 2 $ sudo pip install --upgrade $TF_BINARY_URL # Python 3 $ sudo pip3 install --upgrade $TF_BINARY_URL注意: 如果你从 0.7.1 以前的 TensorFlow 升级过来,你需要先使用 pip uninstall 卸载 &TensorFlow 和&protobuf&,确保安装了更新的 protobuf 依赖。现在可以&。在 Windows 下安装 PipTensorFlow 在 Windows 下只支持 64 位的 Python 3.5 。我们已经在以下的 Python 分发中测试过该 pip 包:.注意: TensorFlow 需要&MSVCP140.DLL, 这个文件可能在你的系统中不存在。当你&import tensorflow as tf, 时看到了错误信息&No module named "_pywrap_tensorflow"&那么说明&DLL 加载失败,检查&MSVCP140.DLL&文件是否在你的&%PATH%&环境变量对应的路径中存在,如果不存在,你需要安装&&(x64 版本).这两个分发版都包含了 pip。为了安装纯 CPU 版本的&TensorFlow,请输入如下命令: &C:\& pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-0.12.0-cp35-cp35m-win_amd64.whl为了安装 GPU 版本的 TensorFlow ,请在命令行中输入以下命令:C:\& pip install --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-0.12.0-cp35-cp35m-win_amd64.whl然后就可以&。你也可以&&或者&&来管理 Windows 下的 TensorFlow 安装。Virtualenv 安装&是一个用来保持不同 Python 项目在独立的位置有独立的依赖的工具。使用 Virtualenv 来安装 TensorFlow 并不会覆盖已有 TensorFlow 需要的 Python 包。在
下的安装步骤如下:安装 pip 和 Virtualenv.创建一个 Virtualenv 环境.激活 Virtualenv 环境并安装 TensorFlow安装结束后你需要在每次使用 TensorFlow 时激活 Virtualenv 环境安装 pip 和 Virtualenv:# Ubuntu/Linux 64-bit $ sudo apt-get install python-pip python-dev python-virtualenv # Mac OS X $ sudo easy_install pip $ sudo pip install --upgrade virtualenv创建一个 Virtualenv 环境到 ~/tensorflow 目录:$ virtualenv --system-site-packages ~/tensorflow激活环境:$ source ~/tensorflow/bin/activate &# If using bash $ source ~/tensorflow/bin/activate.csh &# If using csh (tensorflow)$ &# Your prompt should change现在安装 TensorFLow 作为一个常规的 pip 安装,首先选择正确的安装路径:# Ubuntu/Linux 64-bit, CPU only, Python 2.7 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp27-none-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 2.7 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp27-none-linux_x86_64.whl # Mac OS X, CPU only, Python 2.7: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py2-none-any.whl # Mac OS X, GPU enabled, Python 2.7: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-0.12.0-py2-none-any.whl # Ubuntu/Linux 64-bit, CPU only, Python 3.4 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp34-cp34m-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 3.4 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp34-cp34m-linux_x86_64.whl # Ubuntu/Linux 64-bit, CPU only, Python 3.5 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp35-cp35m-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 3.5 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp35-cp35m-linux_x86_64.whl # Mac OS X, CPU only, Python 3.4 or 3.5: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl # Mac OS X, GPU enabled, Python 3.4 or 3.5: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-0.12.0-py3-none-any.whl最后安装 TensorFlow:# Python 2 (tensorflow)$ pip install --upgrade $TF_BINARY_URL # Python 3 (tensorflow)$ pip3 install --upgrade $TF_BINARY_URL一旦 Virtualenv 环境被激活就可以 当你使用完 TensorFlow ,请停用 Virtualenv 环境。(tensorflow)$ deactivate $ &# Your prompt should change back再次使用 TensorFlow 时需要再次激活 Virtualenv :$ source ~/tensorflow/bin/activate &# If using bash. $ source ~/tensorflow/bin/activate.csh &# If using csh. (tensorflow)$ &# Your prompt should change. # Run Python programs that use TensorFlow. ... # When you are done using TensorFlow, deactivate the environment. (tensorflow)$ deactivateAnaconda 安装 是一个 Python 的分发版,包含大量标准的数学和科学计算包。Anaconda 使用一个名为
的包管理器,有其类似 Virtualenv 的独立的
。和 Virtualenv 一样,conda 环境为不同的 Python 项目保留独立的路径和各自的依赖。使用 Anaconda 环境去安装 TensorFlow 不会覆盖已有版本的 Python 包。安装 Anaconda.创建一个 conda 环境激活 conda 环境并安装 TensorFlow 到其环境中安装完毕后需要在每次想用 TensorFlow 时激活 conda 环境也可以现在 ipython 和其他包到 conda 环境中安装 Anaconda:请参考
中的说明进行安装。创建一个 conda 环境,名为 tensorflow:# Python 2.7 $ conda create -n tensorflow python=2.7 # Python 3.4 $ conda create -n tensorflow python=3.4 # Python 3.5 $ conda create -n tensorflow python=3.5激活环境,然后使用 conda 或者 pip 来安装 TensorFlow 。使用 conda社区维护的 conda 包可从
上获取。这时候只有支持 GPU 的 TensorFlow 版本可以使用,要求使用 Python 2 或者 Python 3 的 conda 环境。
$ source activate tensorflow
(tensorflow)$ &# Your prompt should change # Linux/Mac OS X, Python 2.7/3.4/3.5, CPU only: (tensorflow)$ conda install -c conda-forge tensorflow使用 pip如果你使用 pip ,请确保使用 --ignore-installed 参数来阻止 easy_install 的错误。$ source activate tensorflow (tensorflow)$ &# Your prompt should change现在可以按正常的 Pip 方式安装 TensorFlow ,首先选择正确的路径进行安装:# Ubuntu/Linux 64-bit, CPU only, Python 2.7 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp27-none-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 2.7 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp27-none-linux_x86_64.whl # Mac OS X, CPU only, Python 2.7: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py2-none-any.whl # Mac OS X, GPU enabled, Python 2.7: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-0.12.0-py2-none-any.whl # Ubuntu/Linux 64-bit, CPU only, Python 3.4 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp34-cp34m-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 3.4 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp34-cp34m-linux_x86_64.whl # Ubuntu/Linux 64-bit, CPU only, Python 3.5 (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.0-cp35-cp35m-linux_x86_64.whl # Ubuntu/Linux 64-bit, GPU enabled, Python 3.5 # Requires CUDA toolkit 8.0 and CuDNN v5. For other versions, see "Installing from sources" below. (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-0.12.0-cp35-cp35m-linux_x86_64.whl # Mac OS X, CPU only, Python 3.4 or 3.5: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl # Mac OS X, GPU enabled, Python 3.4 or 3.5: (tensorflow)$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow_gpu-0.12.0-py3-none-any.whl最后安装 TensorFlow:# Python 2 (tensorflow)$ pip install --ignore-installed --upgrade $TF_BINARY_URL # Python 3 (tensorflow)$ pip3 install --ignore-installed --upgrade $TF_BINARY_URL使用方法当 conda 环境被成功激活,你可以 。当你用完 TensorFlow ,请停用环境。(tensorflow)$ source deactivate $ &# Your prompt should change back为了在之后使用 TensorFlow ,你需要重新激活 conda 环境。$ source activate tensorflow (tensorflow)$ &# Your prompt should change. # Run Python programs that use TensorFlow. ... # When you are done using TensorFlow, deactivate the environment. (tensorflow)$ source deactivate安装 IPython为了使用 TensorFlow 和 IPython,需要在 TensorFlow 环境中安装 IPython:$ source activate tensorflow (tensorflow)$ conda install ipython同样的,其他例如 pandas 这样的&Python 包也需要安装进 TensorFlow 环境中,因为这也是 TensorFlow 所需的包。Docker 安装&是一个用来构建自容器版本&Linux 操作系统的平台。当你希望通过 Docker 来运行 TensorFlow 时,它可以实现安装的完全隔离,不会对系统现有的包产生任何影响。我们提供了4个Docker镜像:gcr.io/tensorflow/tensorflow: TensorFlow CPU 二进制镜像.gcr.io/tensorflow/tensorflow:latest-devel: CPU 二进制镜像+ 源码.gcr.io/tensorflow/tensorflow:latest-gpu: TensorFlow GPU 二进制镜像.gcr.io/tensorflow/tensorflow:latest-devel-gpu: GPU B二进制镜像+ 源码.我们也会使用一个发布版本号来来代替latest标签&(例如&0.12.0-gpu).使用Docker安装的方式如下:在你的机器上安装Docker。创建一个&&来允许不使用sudo命令启动容器。使用TensorFlow镜像启动一个Docker容器。镜像会在第一次启动的时候 自动下载。参考中相关的指令来在你的机器上安装Docker。在安装完Docker之后,用下列命令来启动一个带有TensorFlow二进制镜像的Docker容器。 &
$ docker run -it -p
gcr.io/tensorflow/tensorflow选项&-p 是用来将Docker容器的内部端口发布到主机上的,在这种情况下请确保Jupyter笔记本的连接是有效的。端口映射的格式是&hostPort:containerPort。你可以指定任何有效的端口号给主机,但在容器端口选项必须使用8888。如果你使用一个带GPU支持的容器,需要添加些必须的标识用来将GPU设备暴露到容器中。为支持NVidia GPU安装最新的NVidia驱动和。&运行如下
$ nvidia-docker run -it -p
gcr.io/tensorflow/tensorflow:latest-gpu如果你使用默认设置运行nvidia-docker时出现问题,我们在仓库中带有一个包含有这些标识的,因此命令行会看起来像&
$ path/to/repo/tensorflow/tools/docker/docker_run_gpu.sh -p
gcr.io/tensorflow/tensorflow:latest-gpu更多的细节参考&.你现在可以在Docker容器中了测试TensorFlow安装(可选,Linux)启用GPU支持如果你安装了TensorFlow GPU的版本,你还必须安装&Cuda Toolkit 8.0 和 cuDNN v5。 请参考&.您还需要设置LD_LIBRARY_PATH和CUDA_HOME环境变量。&可以考虑将下面的命令添加到~/.bash_profile。假设你的CUDA安装在&/usr/local/cuda:
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64"
export CUDA_HOME=/usr/local/cuda从命令行运行TensorFlow如果发生错误请参考。打开一个终端,输入以下内容:
&&& import tensorflow as tf
&&& hello = tf.constant('Hello, TensorFlow!')
&&& sess = tf.Session()
&&& print(sess.run(hello))
Hello, TensorFlow!
&&& a = tf.constant(10)
&&& b = tf.constant(32)
&&& print(sess.run(a + b))
&&&运行一个TensorFlow 演示模型所有的TensorFlow包,包括演示用的模型,都被安装在Python的库里。Python 库的确切存放位置取决于你的系统,但通常是以下中的一个:
/usr/local/lib/python2.7/dist-packages/tensorflow
/usr/local/lib/python2.7/site-packages/tensorflow&你可以使用如下的命令来找出响应目录(请确认你使用的是安装 TensorFlow 的那个 Python,例如如果你用 Python 3 安装的,那么应该使用 python3 而不是 python):$ python -c ' print(os.path.dirname(inspect.getfile(tensorflow)))'这个简单的演示模型用来对来自 MNIST 数据集的数字手写体进行分类,该数据集位于子目录 models/image/mnist/convolutional.py. 你可以用命令行来执行,如下所示:# Using 'python -m' to find the program in the python search path: $ python -m tensorflow.models.image.mnist.convolutional Extracting data/train-images-idx3-ubyte.gz Extracting data/train-labels-idx1-ubyte.gz Extracting data/t10k-images-idx3-ubyte.gz Extracting data/t10k-labels-idx1-ubyte.gz ...etc... # You can alternatively pass the path to the model program file to the python # interpreter (make sure to use the python distribution you installed # TensorFlow to, for example, .../python3.X/... for Python 3). $ python /usr/local/lib/python2.7/dist-packages/tensorflow/models/image/mnist/convolutional.py ...从源码安装当选择从源码安装时,你将会构建一个 pip 轮,然后使用 pip 进行安装。因此需要先安装 pip ,安装过程已经介绍过。为了在 Windows 上使用源码构建 TensorFlow,我们可以使用还在实验阶段的&&或者是&。克隆 TensorFlow 仓库$ git clone https://github.com/tensorflow/tensorflow注意这个指令是获取&tensorflow 源码最新更新的代码。如果你想安装一个指定的分支(例如发行分支)那么请用 -b 参数指定分支名称,以及&--recurse-submodules&参数指定 r0.8 来获取 TensorFlow 依赖的 protobuf 版本。准备Linux环境安装Bazel按照的说明来安装bazel的依赖。 然后下载适合你系统的最新稳定版的bazel并按照如下方式来安装:
$ chmod +x PATH_TO_INSTALL.SH
$ ./PATH_TO_INSTALL.SH --user记得要用你下载安装包的路径来替换掉PATH_TO_INSTALL.SH。最后,按照该脚本中的指令将bazel放到你的二进制文件的路径。安装其他的依赖
# For Python 2.7:
$ sudo apt-get install python-numpy python-dev python-wheel
# For Python 3.x:
$ sudo apt-get install python3-numpy python3-dev python3-wheel&可选:安装CUDA(GPUs on Linux)为了构建和运行带有GPU支持的TensorFlow,NVIDIA's Cuda 工具包(&= 7.0)和cuDNN (&= v3)都需要被安装。TensorFlow GPU支持功能要求显卡带有NVidia计算能力 (&= 3.0). 支持的卡包括以下但不限于:NVidia TitanNVidia Titan XNVidia K20NVidia K40确认下你的显卡的NVIDIA计算能力下载并安装CUDA工具包如果使用我们的二进制发布请安装8.0版本。安装工具包到如下路径/usr/local/cuda.下载并安装cuDNN下载cuDNN v5。解压并复制cudnn文件到工具包目录。假设工具包安装在/usr/local/cuda,运行下面的命令(按你下载的cuDNN版本来编辑):
tar xvzf cudnn-8.0-linux-x64-v5.1-ga.tgz
sudo cp -P cuda/include/cudnn.h /usr/local/cuda/include
sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda/lib64
sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib64/libcudnn*安装其他的依赖
$ sudo apt-get install libcupti-devMac OS X环境准备我们建议使用来安装bazel的依赖,并且使用easy_install或是pip来安装Python的相关依赖。依赖按照的指令来为bazel安装依赖。然后你可以使用homebrew安装bazel:
$ brew install bazel你可以使用easy_install 或 pip来安装python的依赖。使用easy_install, 命令如下
$ sudo easy_install -U six
$ sudo easy_install -U numpy
$ sudo easy_install wheel我们也建议用来增强python shell,你可以使用下面的命令安装它:
$ sudo easy_install ipython可选:为Mac设置GPU如果你打算构建GPU的支持,你将需要确保已经通过homebrew安装了GNU coreutils:
$ brew install coreutilsNext you will need to make sure you have a recent&&installed by either downloading the package for your version of OSX directly from&&or by using the&&extension:接下来你将需要确保你安装了最近的要么直接从下载你OSX适用的版本安装包或是使用&扩展:
$ brew tap caskroom/cask
$ brew cask install cuda一旦你安装了CUDA工具包您将需要添加以下代码到~/.bash_profile来设置所需的环境变量:
export CUDA_HOME=/usr/local/cuda
export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$CUDA_HOME/lib"
export PATH="$CUDA_HOME/bin:$PATH"最后, 你也会想要安装(cuDNN v5.1)库,它目前需要一个加速计算开发计划账户。 当下载到本地后,你可以解压缩并将头文件和库文件移动到CUDA工具包的目录下:
$ sudo mv include/cudnn.h /Developer/NVIDIA/CUDA-8.0/include/
$ sudo mv lib/libcudnn* /Developer/NVIDIA/CUDA-8.0/lib
$ sudo ln -s /Developer/NVIDIA/CUDA-8.0/lib/libcudnn* /usr/local/cuda/lib/&要验证CUDA的安装,你可以构建和运行deviceQuery以确保它是正常的。
$ cp -r /usr/local/cuda/samples ~/cuda-samples
$ pushd ~/cuda-samples
$ ~/cuda-samples/bin/x86_64/darwin/release/deviceQuery如果你想编译tensorflow并且已经安装了Xcode 7.3和CUDA 7.5,注意当前Xcode 7.3与CUDA 7.5不兼容。你可以选择升级到CUDA 8.0,或者你需要下载Xcode 7.2并选择它作为你的默认设置:
$ sudo xcode-select -s /Application/Xcode-7.2/Xcode.app配置安装在根目录下运行configure脚本。&配置脚本问你的Python解释器的路径和允许(可选)的CUDA库配置项。这个步骤是用来定位 python 和 numpy 头文件的路径,以及在有 CUDA 的 GPU 和相应工具包安装的系统上启用 GPU 支持。当询问是否构建带 GPU 支持的 TensorFlow 时请选择 Y。如果你有多个版本的 Cuda 或者 cuDNN 安装,你应该明确的选择一个,而不是使用系统默认的那个。例如:
$ ./configure
Please specify the location of python. [Default is /usr/bin/python]:
Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] N
No Google Cloud Platform support will be enabled for TensorFlow
Do you wish to build TensorFlow with GPU support? [y/N] y
GPU support will be enabled for TensorFlow
Please specify which gcc nvcc should use as the host compiler. [Default is /usr/bin/gcc]:
Please specify the Cuda SDK version you want to use, e.g. 7.0. [Leave empty to use system default]: 8.0
Please specify the location where CUDA 8.0 toolkit is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:
Please specify the cuDNN version you want to use. [Leave empty to use system default]: 5
Please specify the location where cuDNN 5 library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:
Please specify a list of comma-separated Cuda compute capabilities you want to build with.
You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus.
Please note that each additional compute capability significantly increases your build time and binary size.
[Default is: "3.5,5.2"]: 3.0
Setting up Cuda include
Setting up Cuda lib
Setting up Cuda bin
Setting up Cuda nvvm
Setting up CUPTI include
Setting up CUPTI lib64
Configuration finished这将创建一个规范的符号链接到系统上的Cuda库。 每次更改Cuda库路径时,您需要在调用bazel build命令之前再次运行此步骤。 对于cuDNN库,对R3使用&7.0&,对R4使用&4.0.7&。已知问题虽然可以在同一源代码树下构建Cuda和非Cuda配置,但我们建议在同一源代码树中在这两个配置之间切换时运行bazel clean。您必须在运行bazel build之前运行configure。 否则,构建将失败并显示清除的错误消息。 在将来,我们可以考虑通过在我们的构建过程中包括配置步骤来使这更方便。创建pip包并安装从源代码构建时,你仍将构建一个pip包并安装。请注意使用默认设置从源码构建时会消耗大量内存资源,如果想限制RAM的使用你可以在调用bazel时加上—local_resources .0。
$ bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
# To build with GPU support:
$ bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package
$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
# The name of the .whl file will depend on your platform.
$ sudo pip install /tmp/tensorflow_pkg/tensorflow-0.12.0-py2-none-any.whl&设置 TensorFlow 开发环境如果你只是做 TensorFlow 本身的开发,这个步骤对在交互式 python 命令行环境中测试变更是很有帮助的,无需重装 TensorFlow。为了设置 TensorFlow 使得所有文件被正确链接到系统目录(而不是拷贝),请在 TensorFlow 根目录运行以下命令:
bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
# To build with GPU support:
bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package
mkdir _python_build
cd _python_build
ln -s ../bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/org_tensorflow/* .
ln -s ../tensorflow/tools/pip_package/* .
python setup.py develop请注意这个安装仍需要你在每次更改 C++ 文件、添加、删除或者移动任意 python 文件,或者你更改了 bazel 构建规则时重建&//tensorflow/tools/pip_package:build_pip_package&目标。同时需要注意的是&bazel test&不会总是能正确解决这些符号链接的依赖问题,因此测试结果可能不可信。解决的办法是在运行 bazel test 命令前移除&_python_build&目录。训练你的首个 TensorFlow 神经网络模型在你源码的根目录下运行以下命令:
$ cd tensorflow/models/image/mnist
$ python convolutional.py
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting data/train-images-idx3-ubyte.gz
Extracting data/train-labels-idx1-ubyte.gz
Extracting data/t10k-images-idx3-ubyte.gz
Extracting data/t10k-labels-idx1-ubyte.gz
Initialized!
Epoch 0.00
Minibatch loss: 12.054, learning rate: 0.010000
Minibatch error: 90.6%
Validation error: 84.6%
Epoch 0.12
Minibatch loss: 3.285, learning rate: 0.010000
Minibatch error: 6.2%
Validation error: 7.0%
...常见问题GPU相关问题如果在尝试运行TensorFlow程序时遇到以下情况:ImportError: libcudart.so.7.0: cannot open shared object file: No such file or directory确保您遵循GPU安装说明。如果从源代码构建,并且将Cuda或cuDNN版本留空,请尝试明确指定它们。Protobuf库相关问题TensorFlow pip包依赖于protobuf pip包版本3.1.0。从PyPI下载的Protobuf的pip包(当运行pip install protobuf时)是一个只有Python的库,它具有原序列化/反序列化的Python实现,它比C ++实现慢10倍到50倍。 Protobuf还支持Python包的二进制扩展,包含基于快速C ++的原始解析。此扩展在标准的仅限Python的PIP包中不可用。我们为包含二进制扩展的protobuf创建了一个自定义的二进制pip包。按照以下说明安装自定义二进制protobuf pip软件包:
# Ubuntu/Linux 64-bit:
$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0-cp27-none-linux_x86_64.whl
# Mac OS X:
$ pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/protobuf-3.0.0-cp27-cp27m-macosx_10_11_x86_64.whl对于Python 3.5:
# Ubuntu/Linux 64-bit:
$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0-cp35-cp35m-linux_x86_64.whl
# Mac OS X:
$ pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/protobuf-3.0.0-cp35-cp35m-macosx_10_11_x86_64.whl&如果你的 system/configuration 不在上述列表中,可以使用下面的命令来构建自己的 protobuf 文件,安装依赖请看&:然后执行:
$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ ./autogen.sh
$ CXXFLAGS="-fPIC -g -O2" ./configure
$ make -j12
$ export PROTOC=$PWD/src/protoc
$ cd python
$ python setup.py bdist_wheel --cpp_implementation --compile_static_extension
$ pip uninstall protobuf
$ pip install dist/&wheel file name&在你通过 pip 安装完 TensorFlow 后需要安装上述包,标准的做法&pip install tensorflow&将安装相应的 python pip 包。上面的 pip 包会覆盖已有的 protobuf 包。注意二进制的 pip 包已经支持超过 64MB 的 protobuf,这就可以修复如下的错误:
[libprotobuf ERROR google/protobuf/src/google/protobuf/io/coded_stream.cc:207] A
protocol message was rejected because it was too big (more than
To increase the limit (or to disable these warnings), see
CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.
Pip 安装问题无法导入'descriptor'这个name(Cannot import name 'descriptor')
ImportError: Traceback (most recent call last):
& File "/usr/local/lib/python3.4/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in &module&
& & from google.protobuf import descriptor as _descriptor
ImportError: cannot import name 'descriptor'&如果在升级到新版本的 TensorFlow 时候遇见上述错误,请尝试卸载 TensorFlow 和 protobuf (如果有的话) 然后重新安装 TensorFlow (这同时也会安装正确的 protobuf 版本).Can't find setup.py如果在执行 pip install, 出现如下错误:... IOError: [Errno 2] No such file or directory: '/tmp/pip-o6Tpui-build/setup.py'解决方法: 升级 pip 版本:pip install --upgrade pip这个操作可能需要在 sudo 下执行,取决于 pip 安装的方式。SSLError: SSL_VERIFY_FAILED如果在从某个 URL 中执行 pip install 时发生如下错误:
SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed解决办法:通过curl或wget手动下载这个wheel,然后使用“pip install”进行本地安装。Operation not permitted即使用了sudo,你还是会遇到这样的错误:&
Installing collected packages: setuptools, protobuf, wheel, numpy, tensorflow
Found existing installation: setuptools 1.1.6
Uninstalling setuptools-1.1.6:
Exception:
[Errno 1] Operation not permitted: '/tmp/pip-a1DXRT-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib'解决办法:在pip命令中增加一个--ignore-installed&标记。Linux 问题如果你碰到如下错误:... &"__add__", "__radd__", & & & & & & &^ SyntaxError: invalid syntax解决方案:确认你正在使用 Python 2.7。在 Ubuntu 16.04 下使用 --config=cuda 时的构建问题:构建失败,提示信息 cuda: identifier "__builtin_ia32_mwaitx" is undefined.GitHub issue: 解决方案:添加如下的编译选项到 third_party/gpus/crosstool/CROSSTOOL 文件cxx_flag: "-D_MWAITXINTRIN_H_INCLUDED" cxx_flag: "-D_FORCE_INLINES"Mac OS X: ImportError: No module named copyreg在 Mac OS X 中你可能会在导入 tensorflow 时碰到如下错误:
&&& import tensorflow as tf
ImportError: No module named copyreg解决方案: TensorFlow 依赖于 protobuf, 要求 Python 包&six-1.10.0。而苹果系统默认安装的 Python 版本只提供&six-1.4.1.你可以通过以下步骤来解决这个问题:升级 Python 安装包,包含当前最新的 six 版本:$ sudo easy_install -U six使用一个独立的 Python 库来安装 TensorFlow :使用&.使用&.通过&&或者&&安装独立的 Python 拷贝,然后使用这个 Python 拷贝重装 TensorFlow 。Mac OS X: OSError: [Errno 1] Operation not permitted:在El Capitan里, &six& 是一个无法被改变的特殊包,并且当执行&pip install&来修改这个包的时候这个错误会出现。要修复这个问题,请使用 &ignore-installed& 标记,比如:
sudo pip install --ignore-installed six https://storage.googleapis.com/....Mac OS X: TypeError:&__init__()&got an unexpected keyword argument 'syntax'在Mac OS X上,你在导入tensorflow时可能会遇到如下的问题:
&&& import tensorflow as tf
Traceback (most recent call last):
File "&stdin&", line 1, in &module&
File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 4, in &module&
from tensorflow.python import *
File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 13, in &module&
from tensorflow.core.framework.graph_pb2 import *
File "/usr/local/lib/python2.7/site-packages/tensorflow/core/framework/tensor_shape_pb2.py", line 22, in &module&
serialized_pb=_b('\n,tensorflow/core/framework/tensor_shape.proto\x12\ntensorflow\"d\n\x10TensorShapeProto\x12-\n\x03\x64im\x18\x02 \x03(\x0b\x32 .tensorflow.TensorShapeProto.Dim\x1a!\n\x03\x44im\x12\x0c\n\x04size\x18\x01 \x01(\x03\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3')
TypeError: __init__() got an unexpected keyword argument 'syntax'&这是因为不同 protobuf 版本之间的冲突(我们要求使用 protobuf 3.0.0)。当前最好的解决方案是不要安装老的 protobuf 办法,例如:$ pip install --upgrade protobufMac OS X: 导入 tensorflow 时 Segmentation Fault在 Mac OS X 系统上,你可以在 python 导入 tensorflow 时碰到如下错误信息:&&& import tensorflow I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcublas.dylib locally I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcudnn.dylib locally I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcufft.dylib locally "import tensorflow" terminated by signal SIGSEGV (Address boundary error)这是由于默认情况下 cuda 创建&libcuda.dylib 文件,但 tensorflow 却尝试加载的是&libcuda.1.dylib 文件。这个可以通过创建一个符号链接来解决这个问题:
ln -sf /usr/local/cuda/lib/libcuda.dylib /usr/local/cuda/lib/libcuda.1.dylib
Mac OS X: RuntimeError: Broken toolchain: cannot link a simple C program在 Mac OS X 系统上安装 tensorflow 时可能会看到一大堆的警告和错误,错误信息结尾包含&a&Broken toolchain: cannot link a simple C program&message 这样的内容:
&&& sudo pip install --upgrade $TF_BINARY_URL
...&lots more warnings and errors&这是因为你没有同意 Xcode 的许可证协议,请打开终端窗口运行 'xcodebuild -license' (用户级别的协议接受) 或者 'sudo xcodebuild -license' (系统级别的协议接受) ,该命令会让你重新审核许可证并进行确认。
...&more stack trace output&
File "numpy/core/setup.py", line 653, in get_mathlib_info
raise RuntimeError("Broken toolchain: cannot link a simple C program")
RuntimeError: Broken toolchain: cannot link a simple C program这通常是因为您安装了Xcode构建工具,但是您仍然需要接受许可协议。 要解决它,通过打开Xcode或从命令行运行xcodebuild -license接受许可协议。基本用法要使用TensorFlow,您需要了解TensorFlow如何:将计算表示为图形。在会话的上下文中执行图形。将数据表示为张量。使用变量维护状态。使用feed和fetches来获取数据进出任意操作。概述TensorFlow是一个编程系统,您可以在其中将计算表示为图形。 图中的节点称为ops(操作的缩写)。 一个op取零个或多个Tensors,执行一些计算,并产生零个或多个Tensors。 在TensorFlow术语中,Tensor是一个类型化的多维数组。 例如,您可以将一小批图像表示为具有尺寸[批,高,宽,通道]的浮点数的4-D数组。TensorFlow图是计算的描述。 要计算任何东西,必须在会话中启动图表。 会话将图形操作放置到设备(例如CPU或GPU)上,并提供执行它们的方法。 这些方法返回ops产生的张量作为Python中的numpy ndarray对象,以及作为tensorflow :: Tensor实例在C和C ++中。计算图TensorFlow程序通常被构造为构建阶段,组装图形,以及执行阶段,使用会话在图形中执行ops。例如,通常在创建阶段创建用于表示和训练神经网络的图,然后在执行阶段在图中重复执行一组训练op。TensorFlow 可以在 C、C++ 以及 Python 程序中使用。当前使用 Python 来组装图是非常容易的,因为它提供了大量的助手函数,而这些函数并没有出现在 C 和 C++ 库中。三种语言的 session 库都具有相同的功能。构建图要使用 ops 开始构建图时无需任何的输入(source&ops),类似 Constant ,然后将其输出传递给其他 ops 来做计算。Python 库中的 ops 构造函数返回对象用来表示构建操作的输出结果。你可以将这个对象传递给其他 ops 作为输入。TensorFlow的Python类库里有一个用于操作构造函数和节点的默认图。这个默认图对大多数应用都是够用的。&请查阅的文档来了解如何显式地管理多个图。
import tensorflow as tf
# Create a Constant op that produces a 1x2 matrix.
# added as a node to the default graph.
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])
# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.],[2.]])
# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)&默认的图包含三个节点:两个&constant()&ops 和一个&matmul()&op。为了对矩阵做乘法操作并获得计算结果,你必须在 session 中启动图。在 session 中启动图启动操作在构造函数之后执行。为了启动一个图,需要创建一个&Session&对象,如果不给对象构造函数传递任何值就会创建一个默认的图。请浏览&&查看完整的 session API 列表。
# Launch the default graph.
sess = tf.Session()
# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op.
This indicates to the call
# that we want to get the output of the matmul op back.
# All inputs needed by the op are run automatically by the session.
# typically are run in parallel.
# The call 'run(product)' thus causes the execution of three ops in the
# graph: the two constants and matmul.
# The output of the matmul is returned in 'result' as a numpy `ndarray` object.
result = sess.run(product)
print(result)
# ==& [[ 12.]]
# Close the Session when we're done.
sess.close()你需要手工关闭 Sessions 来释放资源。你也可以使用 "with" 块来进入一个&Session&。Session&会在 with 代码块结束之后自动关闭。with tf.Session() as sess: & result = sess.run([product]) & print(result)TensorFlow 实现了将图定义翻译成可在多个分布式的计算资源中执行的操作,例如 CPU 或者 GPU 。一般你无需手工指定在哪个 CPU 或者 GPU 执行。Tensorflow 默认使用你的第一个 GPU(如果有的话)来尽可能的完成多个操作。如果你的机器上有多个 GPU,为了使用超过 1 个的 GPU,你必须显式的给 ops 赋值进行指定。可使用&with...Device&语句来指定那个 CPU 或者 GPU 用来处理当前语句:with tf.Session() as sess: & with tf.device("/gpu:1"): & & matrix1 = tf.constant([[3., 3.]]) & & matrix2 = tf.constant([[2.],[2.]]) & & product = tf.matmul(matrix1, matrix2) & & ...设备是通过字符串形式进行指定的,当前支持的设备包括:"/cpu:0": 系统的 CPU"/gpu:0": 系统的 GPU ,如果有的话"/gpu:1": 机器上的第二个 GPU&有关GPU和TensorFlow的更多信息,请参阅使用GPU。在分布式会话中启动图要创建TensorFlow集群,请在集群中的每台计算机上启动TensorFlow服务器。 当在客户端中实例化会话时,您传递集群中其中一台计算机的网络位置:
with tf.Session("grpc://example.org:2222") as sess:
# Calls to sess.run(...) will be executed on the cluster.
...此计算机成为会话的主服务器。 主服务器在集群中的其他机器(工作器)上分布图,就像本地实现在机器内的可用计算资源中分布图一样。你可以使用 "with tf.device():" 语句直接为图的每一个特定部分指定&workers :with tf.device("/job:ps/task:0"): & weights = tf.Variable(...) & biases = tf.Variable(...)更多关于分布式的会话和集群请阅读&&。交互式用法文档中关于 Python 示例使用一个&&来启动图,并使用&&方法来执行操作。为了便于在交互式的 Python 环境中使用,诸如&&你可以替换为&&类,以及&&和&&方法。这个避免了必须为会话保存一个相应变量的做法。
# 进入交互式的 TensorFlow 会话
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])
# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()
# Add an op to subtract 'a' from 'x'. &Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())
# ==& [-2. -1.]
# Close the Session when we're done.
sess.close()TensorsTensorFlow 程序使用一个 tensor 数据接口来表示所有的数据 —— 计算图中所有操作间传递的数据都是 tensor 结构的参数。你可以把一个 TensorFlow 的 tensor 想象成是一个 N 维的数组或者列表。tensor 拥有一个静态的 type、rank 和 shape 属性。为了了解更多关于 TensorFlow 如何处理这些概念,请阅读&&手册。变量变量维护着图执行时的状态。以下例子展示了一个作为简单的计数器的变量,更多的详情请查看。
# Create a Variable, that will be initialized to the scalar value 0.
state = tf.Variable(0, name="counter")
# Create an Op to add one to `state`.
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)
# Variables must be initialized by running an `init` Op after having
# launched the graph.
We first have to add the `init` Op to the graph.
init_op = tf.global_variables_initializer()
# Launch the graph and run the ops.
with tf.Session() as sess:
# Run the 'init' op
sess.run(init_op)
# Print the initial value of 'state'
print(sess.run(state))
# Run the op that updates 'state' and print 'state'.
for _ in range(3):
sess.run(update)
print(sess.run(state))
此代码中的assign()操作与add()操作一样是表达式图表的一部分,因此在run()执行表达式之前,它不会实际执行赋值操作。您通常将统计模型的参数表示为一组变量。&例如,您可以将神经网络的权重作为张量存储在变量中。&在训练期间,通过重复运行训练图更新此张量。获取要获取操作的输出,请使用对Session对象的run()调用执行图形,并传递张量来检索。&在前面的例子中,我们获取了单个节点状态,但是你也可以获取多个张量:
input1 = tf.constant([3.0])
input2 = tf.constant([2.0])
input3 = tf.constant([5.0])
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)
with tf.Session() as sess:
& result = sess.run([mul, intermed])
& print(result)
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]用来生成请求 tensors 值的所有操作只运行一次(而不是每个请求的 tensor 运行一次)。Feeds上述的例子介绍了将 tensor 引入计算图并在&Constants&和&Variables 中存储的方法。TensorFlow 同时提供了一个 feed 机制用来修补图中 tensor 的任意操作。feed 将操作的输出值临时替换成一个 tensor 的值。你需要为 run() 方法调用提供 feed 数据作为参数。feed 只用于 run() 方法的调用。绝大多数涉及到指定具体操作的使用场景都可以通过使用 tf.placeholder() 来创建:
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.mul(input1, input2)
with tf.Session() as sess:
& print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
# [array([ 14.], dtype=float32)]如果你没有提供 feed 的话,placeholder()&操作会错误。&() 这里有一个大规模的 feed 示例。金额:N/A元姓名:N/A留言:N/A请使用
扫码二维码,支付成功后直接关闭此窗口打赏金额:你的姓名:打赏留言:选择支付方式:&& &&下一步&& :bowtie: :smile: :laughing: :blush: :smiley: :relaxed: :smirk: :heart_eyes: :kissing_heart: :kissing_closed_eyes: :flushed: :relieved: :satisfied: :grin: :wink: :stuck_out_tongue_winking_eye: :stuck_out_tongue_closed_eyes: :grinning: :kissing: :kissing_smiling_eyes: :stuck_out_tongue: :sleeping: :worried: :frowning: :anguished: :open_mouth: :grimacing: :confused: :hushed: :expressionless: :unamused: :sweat_smile: :sweat: :weary: :pensive: :disappointed: :confounded: :fearful: :cold_sweat: :persevere: :cry: :sob: :joy: :astonished: :scream: :tired_face: :angry: :rage: :triumph: :sleepy: :yum: :mask: :sunglasses: :dizzy_face: :imp: :smiling_imp: :neutral_face: :innocent: :alien: :heart: :cupid: :sparkles: :boom: :exclamation: :question: :zzz: :+1: :-1: :ok_hand: :punch: :fist: :v: :open_hands: :point_up: :point_down: :point_left: :point_right: :raised_hands: :pray: :clap: :muscle: :metal: :kiss: :trollface: 发表评论终于翻译完了啊感谢分享!已推荐到《开发者头条》: 欢迎点赞支持! 欢迎订阅《可译网计算机频道》 :bowtie: 邀请好友翻译关闭发送邀请

我要回帖

更多关于 tensorflow 段错误 的文章

 

随机推荐