MacOS安装Tensorflow,在PyCharm运行开发

作者: ImWiki | 来源:发表于2018-05-12 23:51 被阅读78次

在之前的文章介绍了如何在Docker安装Tensorflow和运行代码,但是遇到的问题也很显著,我们编写的代码没有无法直观看到静态错误,无法得知语法是否错误,必须运行过后才可以看到,同时也无法Debug代码。PyCharm是一个非常给力的Python开发工具,提供代码提示、代码静态错误提示,还有Debug等功能。所以在我们的Mac环境安装Tensorflow是很有必要的。

我是使用官网推荐的Virtualenv方式,基于Python 2.7

安装步骤
  1. 启动一个终端(即一个 shell)
  2. 通过发出以下命令来安装 pip 和 Virtualenv
 $ sudo easy_install pip
 $ pip install --upgrade virtualenv 
  1. 通过使用以下命令来创建一个 Virtualenv 环境:
 $ virtualenv --system-site-packages targetDirectory
激活 Virtualenv 环境
  1. 通过以下命令来激活该 Virtualenv 环境:
$ cd targetDirectory
$ source ./bin/activate 

执行上述 source 命令后,您的提示符应该会变成如下内容:

(targetDirectory)$ 
  1. 确保已安装了 pip 8.1 版或更高版本:
 (targetDirectory)$ easy_install -U pip
  1. 发出以下某个命令,将 TensorFlow 及其需要的所有软件包安装到处于活动状态的 Virtualenv 环境中:
 (targetDirectory)$ pip install --upgrade tensorflow  

当 Virtualenv 环境处于活动状态时,您就可以从该 shell 运行 TensorFlow 程序了。
用完 TensorFlow 后,可以通过发出以下命令来停用此环境:

(targetDirectory)$ deactivate 
验证安装环境:运行一个简短的 TensorFlow 程序

从 shell 中调用 Python,如下所示:

$ python

在 Python 交互式 shell 中输入以下几行简短的程序代码:

# Python
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

如果系统输出以下内容,则说明您可以开始编写 TensorFlow 程序了:

Hello, TensorFlow!

配置PyCharm开发环境

PyCharm的安装教程这里就不再介绍了,自行Google,很简单。PyCharm已经集成了VirtualEnv,在PyCharm即可快速的创建出虚拟环境并用于开发。

  1. 执行命令输出Python在Virtualenv的路径,一会儿需要用到
(targetDirectory)$ which python

/Users/Wiki/targetDirectory/bin/python

  1. 创建Python项目


    image.png
  2. 进入Preferences菜单,选择对于的项目的选项Project Interpreter

    image.png
image.png image.png image.png
  1. 运行代码:HelloWorld
    通过步骤3,那么环境就已经配置好了,创建一个hello.py的文件,输入以下代码:
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

右击Run 'hello',或者点击右上角的按钮,就完成运行了。

image.png

相关文章

网友评论

    本文标题:MacOS安装Tensorflow,在PyCharm运行开发

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