Windows下TensorFlow安装及使用PyCharm简单调试

通过Anaconda安装TensorFlow

先安装Anaconda,记住安装目录,安装中有个添加到环境变量的,请打勾,其他省略。
安装完成后,允许cmd,创建一个名为tensorflow的环境(如果有提示升级,请按照命令先升级):

conda create -n tensorflow pip python=3.5 

完成后,激活环境:

activate tensorflow

在这个环境在安装TensorFlow, TensorFlow分CPU和GPU版,对于调试,我们一般选用CPU版,安装配置会简单很多:

pip install --ignore-installed --upgrade tensorflow 

在PyCharm上运行

PyCharm安装略。
打开PyCharm,新建一个项目时,前往选择刚才创建tensorflow的环境:

这里写图片描述

这里写图片描述

创建完成后,执行以下脚本,来一个HelloTensorFlow吧:

import tensorflow as tf #导入tensorflow
hello = tf.constant('Hello, TensorFlow!') #定义一个常量
with tf.Session() as sess: #使用session
    print(sess.run(hello))  #打印出常量

shift+f10,运行查看到输出代表安装成功:
这里写图片描述

注:如果出现警告:

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

这块我们可以暂时忽略,设置下日志等级就可以不再显示了:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf #导入tensorflow
hello = tf.constant('Hello, TensorFlow!') #定义一个常量
with tf.Session() as sess: #使用session
    print(sess.run(hello))  #打印出常量

TensorFlow基本使用

使用变量(Variable)

我们通过一个简单的运算来认识变量:

state = tf.Variable(1, name="counter") #定义变量counter
one = tf.constant(1) #定义常量为1
new_value = tf.add(state, one) #counter+1
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())  #全局变量初始化
    print(sess.run(state))  #counter为1
    print(sess.run(new_value))  #得到结果为2

注:官方教程中,使用的是tf.initialize_all_variables(), 会出现警告:
(from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use tf.global_variables_initializer instead.
只需按照提示替换为tf.global_variables_initializer()就可以了。

同时取多个值(Fetch)

还是按照上面的代码,我们同时打印出state和new_value:

state = tf.Variable(1, name="counter") #定义变量counter
one = tf.constant(1) #定义常量为1
new_value = tf.add(state, one) #counter+1
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())  #全局变量初始化
    print(sess.run([state,new_value]))  # counter为1,得到结果为2,以数据形式输出

使用占位符,在运行时传自定义值(Feed)

feed机制可以临时替代图中的任意操作中的 tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor。
如下input1只是定义了类型, 当会话运行时,再传入具体值。

input1 = tf.placeholder(tf.float32) #定义一个占位符
output = tf.multiply(input1, input1) #自己相乘
with tf.Session() as sess:  
    print(sess.run([output], feed_dict={input1:[7.0]})) #output为49, 

猜你喜欢

转载自blog.csdn.net/iamfrankjie/article/details/80214931