tensorflow python深度学习 安装使用 学习记录

资料1: https://blog.csdn.net/cs_hnu_scw/article/details/79695347

安装

windows版
预备:如果已经安装了2.7的python 请完整的卸载。新的tensorflow只支持3.7以上
检测当前环境中的python的版本:python --version
另外需要知道的是,mac版的tensorflow 已经不再支持gpu版的了。因为mac的安全机制问题。所以使用gpu版本最好使用linux 或windows。当然linux是首选。

1,首先安装 anaconda
这是个包管理工具,通过这个安装python 和tensorflow,才会比较容易的成功启动哦
需要注意的是安装时会问是否加入环境变量,一定要允许,否则还要自己配置很麻烦。
下载地址 : https://www.anaconda.com/download/

2,查看当前有哪些可以使用的软件版本:
conda search --full -name 程序包名

3,下载安装程序包,也可以先安装python3.7,然后在安装conda,然后跳过这个步骤3,直接步骤4 。
conda create --name tensorflow python=3.7

4, 安装tensorflow
pip install --upgrade --ignore-installed tensorflow

4,查看当前环境,如果成功安装的话,会显示出来安装好的程序包
conda info --envs

5,激活tensflow的环境:activate tensorflow
激活后,才可以运行tensorflow程序哦。
退出的命令是 deactivate

6 测试是否成功
首先找一个文本编辑器,新建一个test.py,然后输入以下代码。然后执行python test.py 如果成功输出结果就说明配置成功了

import tensorflow as tf
hello = tf.constant('first tensorflow')
sess = tf.Session()
print sess.run(hello)

hello world

就像很多教程说的 tensorflow 的hello wrold就是数字识别,不能坏了规矩,第一就这个吧。
新建一个脚本test.py

import tensorflow as tf  # tensorflow库
import os  #系统io库
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'   #跳过警告

#获取训练数据,如果本地没有则下载到目标目录
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#设置输入x,为784个节点 * N  ,784是28*28图片的像素数,N是可能输入的图片数
x = tf.placeholder(tf.float32, [None, 784])
#设置w权重 输入节点为784个,因为图片的像素点 输节点10个
w = tf.Variable(tf.zeros([784, 10]))
#偏置 为10个,因为输出节点是10个
b = tf.Variable(tf.zeros([10]))
#期待结果
y = tf.nn.softmax(tf.matmul(x, w) + b)
#训练结果
y_ = tf.placeholder(tf.float32, [None, 10])
#获取期望结果和训练结果的交叉熵 就是损失
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))
#优化损失,设置学习率
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#开启试图
sess = tf.InteractiveSession()
# 初始化变量
tf.global_variables_initializer().run()
#每次100张,训练1000次
for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_:batch_ys})

#正确的预测结果
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_, 1))
#预测准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#打印准确率
print(sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}))

2层神经网络 + 卷积的数字识别

import tensorflow as tf  # tensorflow库
import os  #系统io库
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'   #跳过警告

#获取训练数据,如果本地没有则下载到目标目录
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#设置输入x,为784个节点 * N  ,784是28*28图片的像素数,N是可能输入的图片数
x = tf.placeholder(tf.float32, [None, 784])
#训练结果 10是可能输出的节点数
y_ = tf.placeholder(tf.float32, [None, 10])

#将图片从矩阵数据还原成28*28图片  -1表示第一维 大小是根据x自动获取的
x_image = tf.reshape(x, [-1, 28, 28, 1])

#卷积方法
#shape 数据 权重w的初始化
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev = 0.1)
    return tf.Variable(initial)
#初始化偏置 b
def bias_variable(shape):
    initial = tf.constant(0.1, shape = shape)
    return tf.Variable(initial)

#计算权重
def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides = [1, 1, 1, 1], padding = 'SAME')

#2x2的池化
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = "SAME")

#卷积1
w_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
#卷积计算 使用relu 作为激活函数
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
#池化
h_pool1 = max_pool_2x2(h_conv1)

#卷积2
w_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

#全连接
w_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 *  7 *64])
h_fc1= tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1)+b_fc1)
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

#将1024向量 转为 10维 对应十个类别
w_fc2 = weight_variable([1024, 10])
#偏置10个
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2

#计算
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

#设置准确率
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#图初始化
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

#20000次训练 每次50张
for i in range(20000):
    batch = mnist.train.next_batch(50)
    #每隔100次(500张) 打印准确率
    if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict = {x:batch[0], y_: batch[1], keep_prob: 1.0})
        print("setp %d tranning accuracy %g" % (i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

#打印最终准确率
print("test accuracy %g" % accuracy.eval(feed_dict = {x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千年奇葩

从来没受过打赏,这玩意好吃吗?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值