zoukankan      html  css  js  c++  java
  • 人工智能识别图片入门

    前言

    TensorFlow 是一个开源的、基于 Python 的机器学习框架,它由 Google 开发,并在图形分类、音频处理、推荐系统和自然语言处理等场景下有着丰富的应用,是目前最热门的机器学习框架。
    除了 Python,TensorFlow 也提供了 C/C++、Java、Go、R 等其它编程语言的接口。

    TensorFlow 还有更多的特点,如下:

    • 支持所有流行语言,如 Python、C++、Java、R和Go。
    • 可以在多种平台上工作,甚至是移动平台和分布式平台。
    • 它受到所有云服务(AWS、Google和Azure)的支持。
    • Keras——高级神经网络 API,已经与 TensorFlow 整合。
    • 与 Torch/Theano 比较,TensorFlow 拥有更好的计算图表可视化。
    • 允许模型部署到工业生产中,并且容易使用。
    • 有非常好的社区支持。
    • TensorFlow 不仅仅是一个软件库,它是一套包括 TensorFlow,TensorBoard 和 TensorServing 的软件。

    环境准备

    安装Tensorflow

    pip install tensorflow
    

    第一个示例

    import tensorflow as tf
    
    # 载入并准备好 MNIST 数据集。将样本从整数转换为浮点数:
    mnist = tf.keras.datasets.mnist
    (x_train, y_train),(x_test, y_test) = mnist.load_data()
    x_train, x_test = x_train / 255.0, x_test / 255.0
    
    # 将模型的各层堆叠起来,以搭建 tf.keras.Sequential 模型。
    model = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),
            tf.keras.layers.Dense(128, activation='relu'),
            tf.keras.layers.Dropout(0.2),
            tf.keras.layers.Dense(10, activation='softmax')])
    
    # 为训练选择优化器和损失函数
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    
    # 训练并验证模型:
    model.fit(x_train, y_train, epochs=5)
    model.evaluate(x_test, y_test, verbose=2)
    

    现在,这个照片分类器的准确度已经达到 98%。

    实例进阶

    本指南将训练一个神经网络模型,对运动鞋和衬衫等服装图像进行分类。即使您不理解所有细节也没关系;这只是对完整 TensorFlow 程序的快速概述,详细内容会在您实际操作的同时进行介绍。

    import tensorflow as tf
    from tensorflow import keras
    import numpy as np
    import matplotlib.pyplot as plt
    
    print(tf.__version__)
    

    导入数据包

    该数据集包含 10 个类别的 70,000 个灰度图像。这些图像以低分辨率(28x28 像素)展示了单件衣物,如下所示:

    fashion_mnist = keras.datasets.fashion_mnist
    (train_images, train_labels),(test_images, test_labels) = fashion_mnist.load_data()
    
    

    加载数据集会返回四个 NumPy 数组:
    train_images 和 train_labels 数组是训练集,即模型用于学习的数据。
    测试集、test_images 和 test_labels 数组会被用来对模型进行测试。
    图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9 之间。这些标签对应于图像所代表的服装类:

    标签
    0 T恤/上衣
    1 裤子
    2 套头衫
    3 连衣裙
    4 外套
    5 凉鞋
    6 衬衫
    7 运动鞋
    8
    9 短靴

    每个图像都会被映射到一个标签。由于数据集不包括类名称,请将它们存储在下方,供稍后绘制图像时使用:

    class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
                   'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
    

    预处理数据

    在训练网络之前,必须对数据进行预处理。如果您检查训练集中的第一个图像,您会看到像素值处于 0 到 255 之间:

    plt.figure()
    plt.imshow(train_images[0])
    plt.colorbar()
    plt.grid(False)
    plt.show()
    

    将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,请将这些值除以 255。请务必以相同的方式对训练集和测试集进行预处理:

    train_images = train_images / 255.0
    test_images = test_images / 255.0
    

    为了验证数据的格式是否正确,以及您是否已准备好构建和训练网络,让我们显示训练集中的前 25 个图像,并在每个图像下方显示类名称。

    plt.figure(figsize=(10,10))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(train_images[i], cmap=plt.cm.binary)
        plt.xlabel(class_names[train_labels[i]])
    plt.show()
    

    构建模型

    构建神经网络需要先配置模型的层,然后再编译模型

    设置层

    神经网络的基本组成部分是层。层会从向其馈送的数据中提取表示形式。希望这些表示形式有助于解决手头上的问题。
    大多数深度学习都包括将简单的层链接在一起。大多数层(如 tf.keras.layers.Dense)都具有在训练期间才会学习的参数。

    model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28, 28)),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(10)
    ])
    

    该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。

    展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。

    编译模型

    在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:

    损失函数 - 用于测量模型在训练期间的准确率。您会希望最小化此函数,以便将模型“引导”到正确的方向上。
    优化器 - 决定模型如何根据其看到的数据和自身的损失函数进行更新。
    指标 - 用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。

    model.compile(optimizer='adam',
                  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                  metrics=['accuracy'])
    

    训练模型

    训练神经网络模型需要执行以下步骤:

    1. 将训练数据馈送给模型。在本例中,训练数据位于 train_images 和 train_labels 数组中。
    2. 模型学习将图像和标签关联起来。
    3. 要求模型对测试集(在本例中为 test_images 数组)进行预测。
    4. 验证预测是否与 test_labels 数组中的标签相匹配。

    向模型反馈数据

    model.fit(train_images, train_labels, epochs=10)
    


    在模型训练期间,会显示损失和准确率指标。此模型在训练数据上的准确率达到了 0.91(或 91%)左右。

    准确率评估

    test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    
    print('
    Test accuracy:', test_acc)
    


    结果表明,模型在测试数据集上的准确率略低于训练数据集

    进行预测

    probability_model = tf.keras.Sequential([model, 
                                             tf.keras.layers.Softmax()])
    predictions = probability_model.predict(test_images)
    print(predictions[0])
    print(np.argmax(predictions[0]))
    

    在上例中,模型预测了测试集中每个图像的标签。我们来看看第一个预测结果:

    因此,该模型非常确信这个图像是短靴,或 class_names[9]。
    您可以将其绘制成图表,看看模型对于全部 10 个类的预测。

    def plot_image(i, predictions_array, true_label, img):
      predictions_array, true_label, img = predictions_array, true_label[i], img[i]
      plt.grid(False)
      plt.xticks([])
      plt.yticks([])
    
      plt.imshow(img, cmap=plt.cm.binary)
    
      predicted_label = np.argmax(predictions_array)
      if predicted_label == true_label:
        color = 'blue'
      else:
        color = 'red'
    
      plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                    100*np.max(predictions_array),
                                    class_names[true_label]),
                                    color=color)
    
    def plot_value_array(i, predictions_array, true_label):
      predictions_array, true_label = predictions_array, true_label[i]
      plt.grid(False)
      plt.xticks(range(10))
      plt.yticks([])
      thisplot = plt.bar(range(10), predictions_array, color="#777777")
      plt.ylim([0, 1])
      predicted_label = np.argmax(predictions_array)
    
      thisplot[predicted_label].set_color('red')
      thisplot[true_label].set_color('blue')
    

    验证预测结果

    我们来看看第 0 个图像、预测结果和预测数组。正确的预测标签为蓝色,错误的预测标签为红色。数字表示预测标签的百分比(总计为 100)。

    i = 0
    plt.figure(figsize=(6,3))
    plt.subplot(1,2,1)
    plot_image(i, predictions[i], test_labels, test_images)
    plt.subplot(1,2,2)
    plot_value_array(i, predictions[i],  test_labels)
    plt.show()
    


    让我们用模型的预测绘制几张图像。请注意,即使置信度很高,模型也可能出错。

    num_rows = 5
    num_cols = 3
    num_images = num_rows*num_cols
    plt.figure(figsize=(2*2*num_cols, 2*num_rows))
    for i in range(num_images):
      plt.subplot(num_rows, 2*num_cols, 2*i+1)
      plot_image(i, predictions[i], test_labels, test_images)
      plt.subplot(num_rows, 2*num_cols, 2*i+2)
      plot_value_array(i, predictions[i], test_labels)
    plt.tight_layout()
    plt.show()
    

    训练好模型进行判断

    img = test_images[1]
    img = (np.expand_dims(img,0))
    predictions_single = probability_model.predict(img)
    print(predictions_single)
    plot_value_array(1, predictions_single[0], test_labels)
    _ = plt.xticks(range(10), class_names, rotation=45)
    print(np.argmax(predictions_single[0]))
    

    判断出这个图片的标签是2,通过上面的对照表对应生成套头衫。

    建议大家使用jupyter notebook来运行上面的代码查看效果更佳。

  • 相关阅读:
    hibernate01
    利用Struts2拦截器完成文件上传功能
    layui的CRUD案例
    最大流dinic模板 poj1273
    CodeForces
    POJ 2139 Six Degrees of Cowvin Bacon (floyd)
    POJ 3259 Wormholes (floyd或者spfa)
    POJ 3615 Cow Hurdles (flyod)
    Codeforces Round #446 (Div. 1) A. Pride
    Educational Codeforces Round 34 A. Hungry Student Problem
  • 原文地址:https://www.cnblogs.com/huny/p/14535108.html
Copyright © 2011-2022 走看看