Classification学习

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#number1-10 data.28X28  784个像素点。网上下载这个包
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))  # 定义权重为随机变量,因为随机变量生成初始变量要比0好很多。形状是【2】【3】:2行3列
    # 机器学习推荐变量不为0.他的size是:1行our_size列
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases # matmul是矩阵的乘法。还没被激活的值存在这个变量中
    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})
    #与真实数据对比
    correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return  result


#define placeholder for input.784个像素点
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])

#add output layer.  softmax一般是用来做分类的函数
prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)


#the error between prediction and real data.在softmax来说,这个cross_entropy算法做分类,生成分类算法
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))#loss

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)


sess = tf.Session()
#important stetp
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()
sess.run(init)


for i in range(1000):
    #这个就是不需要直接把全部的数据放进神经网络学习,分开100个100个这样会提高效率。
    #不是学习整套的data,会有一个快的速度
    #有traindata和testdata
    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))

猜你喜欢

转载自blog.csdn.net/daxuan1881/article/details/84875431