zoukankan      html  css  js  c++  java
  • tensorflow学习-第一章

    tensorflow项目的github地址:

    https://github.com/teafternoon/tensorflow-using

    tensorflow学习

    安装tensorflow:

      作者使用的是python3,安装命令pip3 install tensorflow,这个时cpu版本的,如果要安装gpu版本的使用命令pip3 install tensorflow-gpu

    安装GPU版tensorflow需要先安装cuda sdk

    cuda sdk下载官网:https://www.nvidia.cn/object/cuda_get_cn_old.html

    第一小节:MNIST

    MNIST是一个入门级的计算机视觉数据集,它包含了各种手写数字图片。

    基于此,我们训练一个机器学习模型用于识别图片里面的数字。该识别基于Softmax Regression

    mnist数据集下载地址:http://yann.lecun.com/exdb/mnist/

    demo1:

     1 #!/usr/bin/python3
     2 # -*- coding: utf-8 -*-
     3 
     4 from tensorflow.examples.tutorials.mnist import input_data
     5 
     6 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
     7 
     8 import tensorflow as tf
     9 
    10 x = tf.placeholder("float", [None, 784])
    11 
    12 W = tf.Variable(tf.zeros([784, 10]))
    13 b = tf.Variable(tf.zeros([10]))
    14 
    15 y = tf.nn.softmax(tf.matmul(x, W) + b)
    16 
    17 y_ = tf.placeholder("float", [None, 10])
    18 
    19 cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
    20 
    21 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
    22 
    23 init = tf.initialize_all_variables()
    24 
    25 sess = tf.Session()
    26 sess.run(init)
    27 
    28 for i in range(1000):
    29     batch_xs, batch_ys = mnist.train.next_batch(100)
    30     sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    31 
    32 correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    33 
    34 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    35 
    36 print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

    demo2:

     1 #!/usr/bin/python3
     2 # -*- coding: utf-8 -*-
     3 
     4 from tensorflow.examples.tutorials.mnist import input_data
     5 
     6 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
     7 
     8 import tensorflow as tf
     9 
    10 sess = tf.InteractiveSession()
    11 
    12 x = tf.placeholder("float", shape=[None, 784])
    13 y_ = tf.placeholder("float", shape=[None, 10])
    14 
    15 W = tf.Variable(tf.zeros([784, 10]))
    16 b = tf.Variable(tf.zeros([10]))
    17 
    18 sess.run(tf.initialize_all_variables())
    19 
    20 y = tf.nn.softmax(tf.matmul(x, W) + b)
    21 
    22 cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
    23 
    24 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
    25 
    26 for i in range(1000):
    27     batch = mnist.train.next_batch(50)
    28     train_step.run(feed_dict={x: batch[0], y_: batch[1]})
    29 
    30 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
    31 
    32 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    33 
    34 print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
    35 
    36 def weight_variable(shape):
    37     initial = tf.truncated_normal(shape, stddev=0.1)
    38     return tf.Variable(initial)
    39 
    40 def bias_variable(shape):
    41     initial = tf.constant(0.1, shape=shape)
    42     return tf.Variable(initial)
    43 
    44 def conv2d(x, W):
    45     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
    46 
    47 def max_pool_2x2(x):
    48     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
    49                         strides=[1, 2, 2, 1], padding='SAME')
    50 
    51 W_conv1 = weight_variable([5, 5, 1, 32])
    52 b_conv1 = bias_variable([32])
    53 
    54 x_image = tf.reshape(x, [-1,28,28,1])
    55 
    56 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    57 h_pool1 = max_pool_2x2(h_conv1)
    58 
    59 W_conv2 = weight_variable([5, 5, 32, 64])
    60 b_conv2 = bias_variable([64])
    61 
    62 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    63 h_pool2 = max_pool_2x2(h_conv2)
    64 
    65 W_fc1 = weight_variable([7 * 7 * 64, 1024])
    66 b_fc1 = bias_variable([1024])
    67 
    68 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    69 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    70 
    71 keep_prob = tf.placeholder("float")
    72 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    73 
    74 W_fc2 = weight_variable([1024, 10])
    75 b_fc2 = bias_variable([10])
    76 
    77 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    78 
    79 cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
    80 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    81 correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
    82 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    83 sess.run(tf.initialize_all_variables())
    84 for i in range(20000):
    85     batch = mnist.train.next_batch(50)
    86     if i%100 == 0:
    87         train_accuracy = accuracy.eval(feed_dict={
    88         x:batch[0], y_: batch[1], keep_prob: 1.0})
    89         print("step %d, training accuracy %g"%(i, train_accuracy))
    90     train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    91 
    92 print("test accuracy %g"%accuracy.eval(feed_dict={
    93     x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    第二小节:tensorboard

    安装tensorflow的时候会一并安装,可以通过pip3 freeze查看已经安装了的tensorflow相关的库

    tensor开头的有:tensorflow,tensorboard,tensorflow-estimator这三个

    tensorboard是一款tensorflow的可视化工具,可以用来展现 TensorFlow 图,绘制图像生成的定量指标图以及显示附加数据(如其中传递的图像)

    demo1:

     1 #!/usr/bin/python3
     2 # -*- coding: utf-8 -*-
     3 
     4 import tensorflow as tf
     5 
     6 a = tf.constant([1.0, 2.0, 3.0], name='input1')
     7 b = tf.Variable(tf.random_uniform([3]), name='input2')
     8 add = tf.add_n([a, b], name='addOP')
     9 
    10 with tf.Session() as sess:
    11     sess.run(tf.global_variables_initializer())
    12     writer = tf.summary.FileWriter('./', sess.graph)
    13     print(sess.run(add))
    14 writer.close()

    To Be Continue......

  • 相关阅读:
    数据库设计三大范式
    导航下拉栏 简单方法
    原生js制作弹出框
    原生js和jquery实现图片轮播特效
    用js 做大图轮播方法(一)
    Apple 企业开发者账号申请记录
    libnids介
    n++ ++n
    空指针为什么能调用成员函数?
    c++单例
  • 原文地址:https://www.cnblogs.com/live-program/p/11026477.html
Copyright © 2011-2022 走看看