相关推荐recommended
【深度学习】实验07 使用TensorFlow完成逻辑回归
作者:mmseoamin日期:2024-03-04

文章目录

  • 使用TensorFlow完成逻辑回归
    • 1. 环境设定
    • 2. 数据读取
    • 3. 准备好placeholder
    • 4. 准备好参数/权重
    • 5. 计算多分类softmax的loss function
    • 6. 准备好optimizer
    • 7. 在session里执行graph里定义的运算
    • 附:系列文章

      使用TensorFlow完成逻辑回归

      TensorFlow是一种开源的机器学习框架,由Google Brain团队于2015年开发。它被广泛应用于图像和语音识别、自然语言处理、推荐系统等领域。

      TensorFlow的核心是用于计算的数据流图。在数据流图中,节点表示数学操作,边表示张量(多维数组)。将操作和数据组合在一起的数据流图可以使 TensorFlow 对复杂的数学模型进行优化,同时支持分布式计算。

      TensorFlow提供了Python,C++,Java,Go等多种编程语言的接口,让开发者可以更便捷地使用TensorFlow构建和训练深度学习模型。此外,TensorFlow还具有丰富的工具和库,包括TensorBoard可视化工具、TensorFlow Serving用于生产环境的模型服务、Keras高层封装API等。

      TensorFlow已经发展出了许多优秀的模型,如卷积神经网络、循环神经网络、生成对抗网络等。这些模型已经在许多领域取得了优秀的成果,如图像识别、语音识别、自然语言处理等。

      除了开源的TensorFlow,Google还推出了基于TensorFlow的云端机器学习平台Google Cloud ML,为用户提供了更便捷的训练和部署机器学习模型的服务。

      解决分类问题里最普遍的baseline model就是逻辑回归,简单同时可解释性好,使得它大受欢迎,我们来用tensorflow完成这个模型的搭建。

      1. 环境设定

      import os
      os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
      import warnings
      warnings.filterwarnings("ignore")
      import numpy as np
      import tensorflow as tf
      from tensorflow.examples.tutorials.mnist import input_data
      import time
      

      2. 数据读取

      #使用tensorflow自带的工具加载MNIST手写数字集合
      mnist = input_data.read_data_sets('./data/mnist', one_hot=True) 
      
      Extracting ./data/mnist/train-images-idx3-ubyte.gz
      Extracting ./data/mnist/train-labels-idx1-ubyte.gz
      Extracting ./data/mnist/t10k-images-idx3-ubyte.gz
      Extracting ./data/mnist/t10k-labels-idx1-ubyte.gz
      
      #查看一下数据维度
      mnist.train.images.shape
      
      (55000, 784)
      
      #查看target维度
      mnist.train.labels.shape
      
      (55000, 10)
      

      3. 准备好placeholder

      batch_size = 128
      X = tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder') 
      Y = tf.placeholder(tf.int32, [batch_size, 10], name='Y_placeholder')
      

      4. 准备好参数/权重

      w = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights')
      b = tf.Variable(tf.zeros([1, 10]), name="bias")
      
      logits = tf.matmul(X, w) + b 
      

      5. 计算多分类softmax的loss function

      # 求交叉熵损失
      entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y, name='loss')
      # 求平均
      loss = tf.reduce_mean(entropy)
      

      6. 准备好optimizer

      这里的最优化用的是随机梯度下降,我们可以选择AdamOptimizer这样的优化器

      learning_rate = 0.01
      optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
      

      7. 在session里执行graph里定义的运算

      #迭代总轮次
      n_epochs = 30
      with tf.Session() as sess:
          # 在Tensorboard里可以看到图的结构
          writer = tf.summary.FileWriter('../graphs/logistic_reg', sess.graph)
          start_time = time.time()
          sess.run(tf.global_variables_initializer())	
          n_batches = int(mnist.train.num_examples/batch_size)
          for i in range(n_epochs): # 迭代这么多轮
              total_loss = 0
              for _ in range(n_batches):
                  X_batch, Y_batch = mnist.train.next_batch(batch_size)
                  _, loss_batch = sess.run([optimizer, loss], feed_dict={X: X_batch, Y:Y_batch}) 
                  total_loss += loss_batch
              print('Average loss epoch {0}: {1}'.format(i, total_loss/n_batches))
          print('Total time: {0} seconds'.format(time.time() - start_time))
          print('Optimization Finished!')
      # 测试模型
          preds = tf.nn.softmax(logits)
          correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y, 1))
          accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
          
          n_batches = int(mnist.test.num_examples/batch_size)
          total_correct_preds = 0
          
          for i in range(n_batches):
              X_batch, Y_batch = mnist.test.next_batch(batch_size)
              accuracy_batch = sess.run([accuracy], feed_dict={X: X_batch, Y:Y_batch}) 
              total_correct_preds += accuracy_batch[0]
              
          print('Accuracy {0}'.format(total_correct_preds/mnist.test.num_examples))
          writer.close()
      
         Average loss epoch 0: 0.36748782022571785    
         Average loss epoch 1: 0.2978815356126198    
         Average loss epoch 2: 0.27840628396797845    
         Average loss epoch 3: 0.2783186247437706    
         Average loss epoch 4: 0.2783641471138923    
         Average loss epoch 5: 0.2750668214473413           
         Average loss epoch 6: 0.2687560408126502    
         Average loss epoch 7: 0.2713795114126239    
         Average loss epoch 8: 0.2657588795522154    
         Average loss epoch 9: 0.26322007090686916    
         Average loss epoch 10: 0.26289192279735646    
         Average loss epoch 11: 0.26248606019989873       
         Average loss epoch 12: 0.2604622903056356    
         Average loss epoch 13: 0.26015280702939403    
         Average loss epoch 14: 0.2581879366319496    
         Average loss epoch 15: 0.2590309207117085    
         Average loss epoch 16: 0.2630510463581219    
         Average loss epoch 17: 0.25501730025578767    
         Average loss epoch 18: 0.2547102673000945    
         Average loss epoch 19: 0.258298404375851    
         Average loss epoch 20: 0.2549241428330784    
         Average loss epoch 21: 0.2546788509283866    
         Average loss epoch 22: 0.259556887067837    
         Average loss epoch 23: 0.25428259843365575    
         Average loss epoch 24: 0.25442713139565676    
         Average loss epoch 25: 0.2553852511383159    
         Average loss epoch 26: 0.2503043229415978    
         Average loss epoch 27: 0.25468004046828596    
         Average loss epoch 28: 0.2552785321479633    
         Average loss epoch 29: 0.2506257003663859    
         Total time: 28.603315353393555 seconds    
         Optimization Finished!    
         Accuracy 0.9187
      

      附:系列文章

      序号文章目录直达链接
      1波士顿房价预测https://want595.blog.csdn.net/article/details/132181950
      2鸢尾花数据集分析https://want595.blog.csdn.net/article/details/132182057
      3特征处理https://want595.blog.csdn.net/article/details/132182165
      4交叉验证https://want595.blog.csdn.net/article/details/132182238
      5构造神经网络示例https://want595.blog.csdn.net/article/details/132182341
      6使用TensorFlow完成线性回归https://want595.blog.csdn.net/article/details/132182417
      7使用TensorFlow完成逻辑回归https://want595.blog.csdn.net/article/details/132182496
      8TensorBoard案例https://want595.blog.csdn.net/article/details/132182584
      9使用Keras完成线性回归https://want595.blog.csdn.net/article/details/132182723
      10使用Keras完成逻辑回归https://want595.blog.csdn.net/article/details/132182795
      11使用Keras预训练模型完成猫狗识别https://want595.blog.csdn.net/article/details/132243928
      12使用PyTorch训练模型https://want595.blog.csdn.net/article/details/132243989
      13使用Dropout抑制过拟合https://want595.blog.csdn.net/article/details/132244111
      14使用CNN完成MNIST手写体识别(TensorFlow)https://want595.blog.csdn.net/article/details/132244499
      15使用CNN完成MNIST手写体识别(Keras)https://want595.blog.csdn.net/article/details/132244552
      16使用CNN完成MNIST手写体识别(PyTorch)https://want595.blog.csdn.net/article/details/132244641
      17使用GAN生成手写数字样本https://want595.blog.csdn.net/article/details/132244764
      18自然语言处理https://want595.blog.csdn.net/article/details/132276591