安装Python
Windows下安装TensorFlow只支持Python3.5以上的版本,这里我安装Python3.6,Python的安装可以从官网下载。
例如我安装后的版本如下:
pip3 –version
下载tensorflow
在下面的网址下载对应的Python3.6的tensorflow代码。
https://mirrors.tuna.tsinghua.edu.cn/tensorflow/windows/cpu/
例如我下载的是tensorflow-1.2.1-cp36-cp36m-win_amd64.whl
使用正确的版本后可以安装。
pip3 install tensorflow-1.2.1-cp36-cp36m-win_amd64.whl
测试你的程序
新建文件:
test.py
打开输入
import tensorflow as tf
sess = tf.Session()
a = tf.constant(10)
b= tf.constant(12)
print(sess.run(a+b))
成功
手写字体识别程序
# encoding:utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 获取数据,number 1 to 10
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def add_layer(inputs, in_size, out_size, activation_function=None):
with tf.name_scope('layer'):
with tf.name_scope('weights'):
W = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('bias'):
b = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, W) + b
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
corrct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
accuracy = tf.reduce_mean(tf.cast(corrct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])
# add output layer, softmax通常用于做classification
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.Session()
# important step
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys:batch_ys})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels
))
使用anaconda进行安装
在目录https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
下载Anaconda3-5.3.1-Windows-x86_64.exe
安装完成后,创建python3.5环境。
conda create -n tensorflow python=3.5
表示创建成功,打开Anaconda安装目录,我的是C:\Users\Administrator\Anaconda3\envs,会发现多了个tensorflow的文件夹,这就是创建的Tensorflow环境,里面有Python3.5.2相关的dll等
使用这个环境
activate tensorflow
检测当前环境版本,使用这个命令可以知道使用路径。
在网址https://mirrors.tuna.tsinghua.edu.cn/tensorflow/windows/cpu/下载tensorflow-1.2.1-cp35-cp35m-win_amd64.whl
pip install E:\study\python\教材\tensorflow-1.2.1-cp35-cp35m-win_amd64.whl
表示安装Tensorflow库成功。
测试命令,依次输入:Python,import tensorflow as tf
如果没有报错,表示Tensorflow库安装成功。
打开软件进行代码debug
运行