已过时 - Win10下Tensorflow + Keras + Pycharm + Jupyter 一站式环境配置

注意:今天(2018-7-14)安装Tensorflow GPU版本时出现错误,最后删了Anaconda重新安装,发现3.6环境可以直接安Tensorflow,根本无需设置虚环境,也无需关联!所以以下没什么用了哈哈哈!


一站式环境配置服务,省时省心。

一、大体流程

  1. 准备:安装Anaconda, Pycharm

  2. 创建conda虚环境,安装Tensorflow,安装Keras

  3. Pycharm下链接到虚环境,运行Tensorflow

  4. Jupyter Notebook 链接到虚环境,运行Tensorflow

二、详细说明

  1. 不多说。

  2. 创建虚环境

    因为当时Tensorflow只能在Py3.5中运行,而正常是3.6版本,我们只能创建一个3.5的新环境供其生长,Anaconda Prompt中,conda命令如下:

    # 可选: 将conda切换到清华镜像
    conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
    conda config --set show_channel_urls yes
    
    
    # 创建名为tensorflow 的python 3.5 环境
    conda create -n tensorflow python=3.5

    之后我们要进入这个环境安装tensorflow, 这个环境中

    # 进入tensorflow环境:
    activate tensorflow
    
    # 安装tensorflow
    pip install tensorflow
    
    # 如果上步不好使可以试下
    pip install --ignore-installed --upgrade tensorflow
    

    安装完毕后,可以在命令行中输入以下测试:

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

    已过时 - Win10下Tensorflow + Keras + Pycharm + Jupyter 一站式环境配置如果想退出该虚环境:

    deactivate tensorflow

    安装Keras及其他包(因为是新环境,好多包都没有)

    # conda 安装包的命令大体如下,此法不必切换到虚环境下
    conda install --name env_name package_name
    # 具体如 conda install --name tensorflow pandas
    
    #查看已安装环境名,可用
    conda info –envs
    
    #对于在名为tensorflow的环境下安装Keras
    conda install --name tensorflow -c conda-forge keras
    

  3. 链接Pycharm 

    其实原理就是,换个编译器,用3.5的编译器罢了!

    Settings -> Project -> Project Interpreter,选所创建环境所在目录下的那个Python,默认在 $ANACONDA_HOME/envs/env_name/python.exe

    切换完新编译器等待一段indexing后,输入 import tensorflow as tf 不报错,多半是稳了,进一步测试,可用:

    import tensorflow as tf
    
    x = tf.constant([[1.0, 2.0]]) #常数张量
    w = tf.constant([[3.0], [4.0]])
    
    y = tf.matmul(x, w) #计算图节点
    
    with tf.Session() as sess: #创建会话
        print (sess.run(y)) #运行计算

    若输出结果为11则说明OK

    已过时 - Win10下Tensorflow + Keras + Pycharm + Jupyter 一站式环境配置

  4. 链接Jupyter Notebook 参考:冷江

    没有Jupyter是不完整的,Anaconda Prompt中操作详情如下:

    # **环境(以名为tensorflow的为例)
    activate tensorflow
    
    # 安装
    conda install ipykernel
    
    # 将环境写入notebook kernel
    python -m ipykernel install --user --name 环境名称 --display-name "Python (环境名称)"
    
    # 然后打开Notebook
    jupyter notebook

    已过时 - Win10下Tensorflow + Keras + Pycharm + Jupyter 一站式环境配置

    至此,完成。

参考致谢:

    doublepython的博客

    Co_zy的博客

    及一些忘记来源的作者!