一个单层的基础神经网络实现手写字识别

`import tensorflow  from tensorflow.examples.tutorials.mnist import input_data  import matplotlib.pyplot as plt    # 普通的神经网络学习  # 学习训练类  class Normal:        weight = []      biases = []        def __init__(self):          self.times = 1000          self.mnist = []          self.session = tensorflow.Session()          self.xs = tensorflow.placeholder(tensorflow.float32, [None, 784])          self.ys = tensorflow.placeholder(tensorflow.float32, [None, 10])          self.save_path = 'learn/result/normal.ckpt'        def run(self):          self.import_data()          self.train()          self.save()        def _setWeight(self,weight):          self.weight = weight        def _setBiases(self,biases):          self.biases = biases        def _getWeight(self):          return self.weight        def _getBiases(self):          return self.biases      # 训练      def train(self):            prediction = self.add_layer(self.xs, 784, 10, activation_function=tensorflow.nn.softmax)            cross_entropy = tensorflow.reduce_mean(              -tensorflow.reduce_sum(                  self.ys * tensorflow.log(prediction)                  , reduction_indices=[1])          )          train_step = tensorflow.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)            self.session.run(tensorflow.global_variables_initializer())            for i in range(self.times):              batch_xs, batch_ys = self.mnist.train.next_batch(100)              self.session.run(train_step, feed_dict={self.xs: batch_xs, self.ys: batch_ys})              if i % 50 == 0:                  # images 变换为 labels，images相当于x，labels相当于y                  accurary = self.computer_accurary(                      self.mnist.test.images,                      self.mnist.test.labels,                      prediction                  )        # 数据导入      def import_data(self):          self.mnist = input_data.read_data_sets('MNIST_data', one_hot=True)        # 数据保存      def save(self):          saver = tensorflow.train.Saver()          path = saver.save(self.session,self.save_path)        # 添加隐藏层      def add_layer(self,inputs,input_size,output_size,activation_function=None):            weight = tensorflow.Variable(tensorflow.random_normal([input_size,output_size]),dtype=tensorflow.float32,name='weight')            biases = tensorflow.Variable(tensorflow.zeros([1,output_size]) + 0.1,dtype=tensorflow.float32,name='biases')          Wx_plus_b = tensorflow.matmul(inputs,weight) + biases            self._setBiases(biases)          self._setWeight(weight)            if activation_function is None:              outputs = Wx_plus_b          else:              outputs = activation_function(Wx_plus_b,)            return outputs          # 计算结果数据与实际数据的正确率      def computer_accurary(self,x_data,y_data,tf_prediction):            prediction = self.session.run(tf_prediction,feed_dict={self.xs:x_data,self.ys:y_data})            # 返回两个矩阵中***值的索引号位置，然后进行相应位置的值大小比较并在此位置设置为True/False          correct_predition = tensorflow.equal(tensorflow.argmax(prediction,1),tensorflow.argmax(y_data,1))            # 进行数据格式转换，然后进行降维求平均值          accurary = tensorflow.reduce_mean(tensorflow.cast(correct_predition,tensorflow.float32))            result = self.session.run(accurary,feed_dict={self.xs:x_data,self.ys:y_data})            return result    # 识别类  class NormalRead(Normal):        input_size = 784      output_size = 10        def run(self):          self.import_data()          self.getSaver()          origin_input = self._getInput()          output = self.recognize(origin_input)            self._showImage(origin_input)          self._showOutput(output)          pass        # 显示识别结果      def _showOutput(self,output):          number = output.index(1)          print('识别到的数字:',number)        # 显示被识别图片      def _showImage(self,origin_input):          data = []          tmp = []          i = 1          # 原数据转换为可显示的矩阵          for v in origin_input[0]:              if i %28 == 0:                  tmp.append(v)                  data.append(tmp)                  tmp = []              else:                  tmp.append(v)              i += 1            plt.figure()          plt.imshow(data, cmap='binary')  # 黑白显示          plt.show()          def _setBiases(self,biases):          self.biases = biases          pass        def _setWeight(self,weight):          self.weight = weight          pass        def _getBiases(self):          return self.biases        def _getWeight(self):          return self.weight        # 获取训练模型      def getSaver(self):          weight = tensorflow.Variable(tensorflow.random_normal([self.input_size, self.output_size]), dtype=tensorflow.float32,name='weight')            biases = tensorflow.Variable(tensorflow.zeros([1, self.output_size]) + 0.1, dtype=tensorflow.float32, name='biases')            saver = tensorflow.train.Saver()          saver.restore(self.session,self.save_path)            self._setWeight(weight)          self._setBiases(biases)        def recognize(self,origin_input):          input = tensorflow.placeholder(tensorflow.float32,[None,784])          weight = self._getWeight()          biases = self._getBiases()            result = tensorflow.matmul(input,weight) + biases          resultSof = tensorflow.nn.softmax(result,) # 把结果集使用softmax进行激励          resultSig = tensorflow.nn.sigmoid(resultSof,) # 把结果集以sigmoid函数进行激励，用于后续分类          output = self.session.run(resultSig,{input:origin_input})            output = output[0]            # 对识别结果进行分类处理          output_tmp = []          for item in output:              if item < 0.6:                  output_tmp.append(0)              else :                  output_tmp.append(1)            return output_tmp        def _getInput(self):          inputs, y = self.mnist.train.next_batch(100);          return [inputs[50]] `

`def _getInput(self):          inputs, y = self.mnist.train.next_batch(100);          return [inputs[50]] `

`def _getInput(self):          inputs, y = self.mnist.train.next_batch(1);          return [inputs[0]] `

`resultSof = tensorflow.nn.softmax(result,) # 把结果集使用softmax进行激励  resultSig = tensorflow.nn.sigmoid(resultSof,) # 把结果集以sigmoid函数进行激励，用于后续分类 `

`[0,0,0,0,0,0,0,0,1,0] `

`[1,0,0,0,0,0,0,0,0,0] `

https://segmentfault.com/a/11...

Python 人工智能 神经网络

更多资讯推荐

「新基建」下大火的工业智能，问题依旧很多

「新基建」火了。连同 5G、人工智能、物联网等信息数字化基础设施，都成为国家新的发展方向，不仅在这些新领域内的从业者们明确了目标，传统行业对数字化转型的需求也蓄势待发。

2019 年 8 月 29 日，微软发布了一个名为 Suphx（超级凤凰）的「麻将 AI」，在专业的麻将竞技平台上，Suphx 的实力胜过了顶级人类选手的平均水平。

AI如何改变人类社会的各种业务模式？

CDA数据分析师 ·  4天前