Tensorflow实战(1)

一、环境配置:

  我并没有按照书上的安装方法去安装Tensorflow,选择了一种偷懒的方式,因为先安装了Anaconda,所以直接:conda install tensorflow。因为台式机是集成显卡,没有安装NVDIA的显卡,所以没有使用GPU版本的。目前看起来没什么问题,但是肯定还是要重装的。

二、简单的例子:

  书中将Tensorflow实现Softmax Regression识别手写数字比作编程中的"Hello World",可见其重要性,所以还是认认真真的写了一遍。

  使用的数据库是MNIST的数据库。可以直接在官网中下到,下载完成后不需要解压。也可以使用Python代码进行下载。

1 from tensorflow.examples.tutorials.mnist import input_data
2 mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
View Code

  这样就可以把数据集放在代码存放位置的 MNIST_data 目录下,里面就是四个数据集,和在官网直接下载是一样的。

  之后就开是用到Tensorflow了。

  数据集的每一张是28*28像素大小的灰度图片,所以有一个784的一维向量,所有的数据集在一起就是一个55000*784的Tensor,然后将label也进行编码,得到 5500 * 10 的labels的Tensor。

  处理好数据集之后接着就是对于算法的设计了,这里采用的是:Softmax Regression算法。好吧,百度找了一圈,都是关于公式的证明什么的,无非就是想说明,将分类问题转换为概率问题,取最大概率,从而判断其分类, 之后就是一堆公式的转换了。数学公式比较难写下来,我要在准备一下,所以先上代码了。

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 11 14:03:39 2018

@author: TulLing
"""

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# =============================================================================
# print(mnist.train.images.shape,mnist.train.labels.shape)
# print(mnist.test.images.shape,mnist.test.labels.shape)
# print(mnist.validation.images.shape,mnist.validation.labels.shape)
# =============================================================================

import tensorflow as tf

sess =tf.InteractiveSession()
x = tf.placeholder(tf.float32,[None,784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

# =============================================================================
# print(x)
# print(w)
# print(b)
# =============================================================================
# Y
y = tf.nn.softmax(tf.matmul(x,W) + b)
# print(y)
#Y的导数
y_ = tf.placeholder(tf.float32,[None,10])
#损失函数的定义
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs,bathc_ys = mnist.train.next_batch(100)
    train_step.run({x:batch_xs,y_: bathc_ys})
correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))

 

转载于:https://www.cnblogs.com/hixkill/p/8270764.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值