机器学习之TensorFlow – 补充学习中20220828

文章目录

前言

以下是学习过程中的一些注意事项,难免会有失误和失误。如果我惹了什么麻烦,我很抱歉。

[En]

The following are some notes in the learning process, there will inevitably be mistakes and mistakes. I’m sorry if I caused any trouble.

TensorFlow™是一个基于数据流编程(dataflow programming)的符号数学系统,是一个功能强大的开源软件库,它由Google的布莱恩(Brain)团队开发,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief。

一、前置基础

说明:您可以在此处添加要记录在本文中的一般内容。

[En]

Description: here you can add the general content to be recorded in this article.

1.1 什么是神经网络

让我们从人类的大脑开始,它由无数的神经元组成,这些神经元通过静脉相互连接,形成一个巨大的神经网络。

[En]

Let’s start with the human brain, which is made up of countless neurons, which are linked to each other through veins to form a huge neural network.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GT4mnGTG-1662906394071)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/头脑风暴.png)]

当有人看到一只猫的时候?或者,当它是一只狗时,神经网络是如何处理这些信息的?

[En]

When someone sees a cat? Or how does the neural network process this information when it is a dog?

机器学习之TensorFlow - 补充学习中20220828

当一组图像被输入神经网络时,它们会被分解成无数可识别/无法识别的标签,并通过多层算法来找到你认为正确的结果(无论是猫是狗还是其他东西)。

[En]

When a group of images are input into the neural network, they will be disassembled into numerous recognizable / unrecognizable tags, and go through layers of algorithms to find a result (whether a cat is a dog or something else) that you think is correct.

神经网络小玩具地址
A Neural Network Playground (tensorflow.org)

然后简单的看一下分类

机器学习之TensorFlow - 补充学习中20220828

单个神经网络由多个互联的神经元构成,组织形式叫 层,某一层的神经元会将消息传递到其下一层神经元(术语为” 发射“),这即是神经网络的运行方式。

具有单个线性层的模型叫做感知器,如果模型中含有多个线性层,则称之为 多层感知器(MLP)。

实际上,机器学习的模型是一种计算函数的方法,它将相应的输入映射到相应的输出,在这个过程中,通过损失函数(待优化的内容)的一些度量,逐步修改模型。

[En]

In fact, the model of machine learning is a method of calculating a function, which maps the corresponding input to the corresponding output, and in this process, through some metrics of the loss function (the content to be optimized), gradually modify the model.

; 1.2 机器学习的类型

在机器学习中,根据不同的学习风格,它们大致分为以下几类:

[En]

In machine learning, according to different learning styles, they are roughly classified into the following categories:

  • 监督学习 – Supervised Learning
  • 无监督学习 – Unsupervised Learning
  • 强化学习
  • 元学习/AutoML – Meta Learning

监督学习

事先处理过带有标签的数据组进行训练及量化,常见的方式有

  • 分类—–类别,一手房/二手房
  • 回归—–连续性数据,如耗电量

无监督学习

没有标签的数据进行建模,对没有事先标记的、 无法事先处理的数据进行自动分类/分群,常用的算法有

  • 聚类算法
  • 数据降维

强化学习

通过自动调整策略获取最大期望回报,自主探索寻找最佳模型,例如AI下棋。

AutoML

将机器学习应用于实际问题的端到端过程自动化,从特征工程、建模和超参数优化三个方面实现。

[En]

Machine learning is applied to the end-to-end process automation of practical problems, which is realized from three aspects: feature engineering, model building and super-parameter optimization.

1.3 什么是线性回归

线性回归是利用数理统计中的回归分析来确定两个或多个变量之间相互依赖的数量关系的一种统计分析方法。其表达式如下:

[En]

Linear regression is a statistical analysis method which uses regression analysis in mathematical statistics to determine the interdependent quantitative relationship between two or more variables. Its expression is as follows:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-md5TkXrO-1662906394072)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/机器学习入门-线性回归模型公式-2.png)]

b为误差服从均值为0的正态分布。

如果只有一个自变量的情况下就叫 一元回归

如果有多个自变量的情况下就叫 多元回归

以你的工资为例,影响你工资的可能因素有很多:老板赏识、工作努力、运气不错等,如果从一个相对简单的角度去思考,你的工资仅仅由领导的心情决定,通过回归,我们就可以确定领导的心情 (自变量:这类变量不依赖于其他任何变量)与工资 (因变量:这类变量依赖于一个或多个自变量)之间的关系。

1.4 TensorFlow Keras

地址
关于TensorFlow | TensorFlow中文官网 (google.cn)

Keras是由Python编写的高阶深度学习API,它主要面向与用户快速开发,而 Keras作为 TensorFlow的前端,屏蔽了底层较为难以理解的算法实现,对用户友好,允许简单而快速的原型设计。

1.5 TensorFlow Estimator

首先对TensorFlow基础架构组成有一个初步的了解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AhVxZc5N-1662906394073)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-基础API架构分布-1.png)]

对于 Estimator来说,它是一个高度封装的API,简化开发者的使用,内有许多封装好的、可以直接使用的分类及回归模型。

使用操作步骤

  1. 创建 x 个输入函数, input_fn
  2. 定义特征列, feature_columns,充当输入数据和模型之间的桥梁;
  3. 实例化 Estimator,指定特征列和参数;
  4. Estimator 对象上调用一个或多个方法,传递适当的输入函数作为数据的来源(train, evaluate, predict);

什么是特征列?什么是输入函数?

  • 特征列 充当输入数据和模型之间的桥梁,用于估算器训练的输入参数作为特征列传递,并指定模型如何解析数据。
  • 输入函数 用于训练、评估和预测的数据需要由输入函数提供。输入函数返回一个tf.data.Dataset对象,该对象返回一个包含特征和标签的元组。

下面看看feature_columns中提供的函数使用

函数名作用密集数值categorical_column_with_identity每个类目都是One-Hot(独热)编码的,因此具有唯一标识。它只适用于数字值。密集数值categorical_column_with_vocabulary_file当分类输入是字符串且类目在文件中给出时,使用此函数。字符串首先会转换为数字值,然后进行One-Hot编码。密集数值categorical_column_with_vocabulary_list当分类输入是字符串且类目在列表中明确定义时,使用此函数。字符串首先会转换为数字值,然后进行One-Hot编码。密集数值categorical_column_with_hash_bucket如果类目的数量非常大,且不可能进行One-Hot编码时,我们使用哈希。密集数值crossed_column当我们希望将两列合并成单个特征来使用时,使用此函数。例如,对基于地理位置的数据,将经度值和纬度值合并为一项特征是合理的。密集数值numeric_column当特征为数字时使用,它可以是单个值,甚至是矩阵。分类indicator_column我们不直接使用它。当且仅当类目数量有限并可由One-Hot编码表示时,将其与分类列一起使用。分类embedding_column我们不直接使用它。当且仅当类目数量非常大且不能由One-Hot编码表示时,将其与分类列一起使用。分类bucketized_column当我们根据数据本身的值(而不是特定的数值)将数据划分为不同的类别时,使用此函数。

让我们通过一个代码示例来理解上面的内容

[En]

Let’s digest the above through a code example


import tensorflow as tf
from tensorflow import feature_column as fc

numeric_column = fc.numeric_column
categorical_column_with_vocabulary_list = fc.categorical_column_with_vocabulary_list

featCols = [
    tf.feature_column.numeric_column("area"),
    tf.feature_column.categorical_column_with_vocabulary_list(
        "type", ["bungalow", "apartment"]
    )
]

def train_input_fn():
    features = {
        "area": [1000, 2000, 4000, 1000, 2000, 4000],
        "type": ["bungalow", "bungalow", "house", "apartment", "apartment", "apartment"]
    }
    labels = [500, 1000, 1500, 700, 1300, 1900]
    return features, labels

model = tf.estimator.LinearRegressor(featCols)
model.train(train_input_fn, steps=200)

def predict_input_fn():
    features = {
        "area": [1500, 1800],
        "type": ["house", "apt"]
    }
    return features

predictions = model.predict(predict_input_fn)
print(next(predictions))
print(next(predictions))

总结知识点

  1. 多元输入
  2. 特征列函数的使用

1.6 案例:简单一元回归

只有一个自变量和因变量的简单一元线性回归

[En]

Simple unitary linear regression with only single independent variable and dependent variable

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

np.random.seed(0)
area = 2.5 * np.random.randn(100) + 25
price = 25 * area + 5 + np.random.randint(20, 50, size=len(area))

data = np.array([area, price])
data = pd.DataFrame(data=data.T, columns=['area', 'price'])

W = sum(price * (area - np.mean(area))) / sum((area - np.mean(area)) ** 2)
b = np.mean(price) - W * np.mean(area)

y_pred = W * area + b

plt.plot(area, y_pred, color='red', label="forecast")
plt.scatter(data['area'], data['price'], label="train")
plt.xlabel("areaX")
plt.ylabel("priceY")
plt.legend()
plt.show()

1.7 模型训练流程

培训体系的组成大致分为四个步骤

[En]

The composition of the training system is roughly divided into four steps

  1. 数据预处理 -> 相当于数据的准备;
  2. 算法学习 -> 根据数据的具体情况选择合适的机器学习方式,根据不同的精度选择合适的算法;
  3. 模型验证;
  4. 模型预测;

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ua8KwCQr-1662906394073)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/机器学习入门-机器学习系统构成-2.jpg)]

结合上面的库,业务开发人员不必太担心算法的核心实现,只需在合适的场景中选择合适的模型即可。

[En]

Combined with the above libraries, business developers do not have to worry too much about the core implementation of the algorithm, and just select the appropriate model in the appropriate scenario.

1.8 业务通讯结合

在Java代码中执行python文件

package org.springblade.utils;

import org.springblade.core.tool.api.R;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PythonUtils {

    private static final String PYTHON_ENV = "E:\\27_python 3\\python";

    public static R executeAndRecord(String pathFile) {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec(PYTHON_ENV + " " + pathFile);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            in.close();
            proc.waitFor();
            return R.data(stringBuilder);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("IOException");
        } catch (InterruptedException e) {
            e.printStackTrace();
            return R.fail("InterruptedException");
        }
    }
}

二、环境安装

说明:您可以在此处添加要记录在本文中的一般内容。

[En]

Description: here you can add the general content to be recorded in this article.

2.1 CPU版本安装

1

2.2 GPU版本安装

检查GPU是否合规

C:\Users\13544>nvidia-smi
Sun Sep 11 21:39:10 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 512.52       Driver Version: 512.52       CUDA Version: 11.6     |
|-------------------------------+----------------------+----------------------+
| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ... WDDM  | 00000000:01:00.0  On |                  N/A |
| 23%   40C    P8    12W / 125W |   1156MiB /  6144MiB |     15%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      2588    C+G   ...ge\Application\msedge.exe    N/A      |
|    0   N/A  N/A      3176    C+G   ...r\RoundedTB\RoundedTB.exe    N/A      |
|    0   N/A  N/A     10784    C+G   C:\Windows\explorer.exe         N/A      |
|    0   N/A  N/A     12332    C+G   ...n1h2txyewy\SearchHost.exe    N/A      |
|    0   N/A  N/A     12436    C+G   ...artMenuExperienceHost.exe    N/A      |
|    0   N/A  N/A     15260    C+G   ...lPanel\SystemSettings.exe    N/A      |
|    0   N/A  N/A     15344    C+G   ...2txyewy\TextInputHost.exe    N/A      |
|    0   N/A  N/A     15976    C+G   ...d\runtime\WeChatAppEx.exe    N/A      |
|    0   N/A  N/A     16720    C+G   ...perience\NVIDIA Share.exe    N/A      |
|    0   N/A  N/A     16756    C+G   E:\56_PicGo\PicGo.exe           N/A      |
|    0   N/A  N/A     18628    C+G   ...tracted\WechatBrowser.exe    N/A      |
|    0   N/A  N/A     20344    C+G   ...y\ShellExperienceHost.exe    N/A      |
|    0   N/A  N/A     21284    C+G   ...6.1.12\NutstoreClient.exe    N/A      |
|    0   N/A  N/A     25876    C+G   ..._Typora\Typora\Typora.exe    N/A      |
+-----------------------------------------------------------------------------+

C:\Users\13544>

英伟达的驱动版本和性能都不能低,我的是1660 Super系列,还行

三、数据预测

说明:您可以在此处添加要记录在本文中的一般内容。

[En]

Description: here you can add the general content to be recorded in this article.

2.1 梯度下降法

梯度下降法是一种致力于寻找函数极值点的算法。

[En]

The gradient descent method is an algorithm dedicated to finding the extreme point of the function.

地址
什么是梯度下降法? – 知乎 (zhihu.com)

下面看看Tensorflow中对于梯度下降的简单示例,是一元线性回归,数据集大家随便编造,只有两个列,一个是自变量,一个是因变量。

数据集

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BR7teLip-1662906394073)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-梯度下降示例-数据集-1.png)]

import tensorflow as tf
import pandas as pd

data = pd.read_csv(
    'E:/27_Python_Protect/02_ml/01-识别手写数字/hello01.csv'
)
y = data.Education
x = data.Income

model = tf.keras.Sequential()
model.add(

    tf.keras.layers.Dense(1, input_shape=(1,))
)

model.compile(
    optimizer='adam',
    loss='mse'
)

history = model.fit(x, y, epochs=10000)

preTemp = model.predict(pd.Series([23]))

print("结果是 = ",preTemp)

2.2 =激活函数

从激活一词看出,这个函数在某个特定条件下才会被激活使用,通过设置单独的激活层实现,也可以在构造层对象时通过传递 activation 参数实现。


model = tf.keras.Sequential(
    [

        tf.keras.layers.Dense(10, input_shape=(3,), activation='relu'),

        tf.keras.layers.Dense(1)
    ]
)

以下是激活功能的简要列表

[En]

Here is a brief list of the activation functions

(1)softmax

keras.activations.softmax(x, axis=-1)
  • x:张量
  • axis:所作用的维度

返回:softmax变换后的张量。

(2)elu

指数线性单元

keras.activations.elu(x, alpha=1.0)
  • x:张量
  • alpha:一个标量,表示负数部分的斜率

返回:如果 x > 0,返回值为 x;如果 x < 0 返回值为 alpha * (exp(x)-1)

(3)selu

1

(4)softplus

1

(5)softsign

1

(6)relu

线性函数模型,使用默认值时,它返回逐元素的 max(x, 0)

否则,它遵循:

  • 如果 x >= max_valuef(x) = max_value
  • 如果 threshold <= x < max_value< code>&#xFF1A;<code>f(x) = x</code>&#xFF0C;<!--=-->
  • 否则: f(x) = alpha * (x - threshold)
keras.activations.relu(x, alpha=0.0, max_value=None, threshold=0.0)

参数说明x张量alpha负数部分的斜率max_value输出的最大值threshold浮点数,阈值

(7)tanh

1

(8)sigmoid

这是一个概率分布函数。首先看一下公式。

[En]

It’s a probability distribution function. First look at the formula.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6VxAoxDn-1662906394074)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-sigmoid函数的公式示意图-1.png)]

通过对特征列和输入值的计算,得到一个介于0-1之间的概率值,这是逻辑回归求解中常用的概率值。

[En]

After the calculation of the characteristic column and the input value, a probability value between 0-1 is obtained, which is often used in the solution of logical regression.

(9)hard_sigmoid

1

(10)exponential

1

(11)linear

1

1

2.3 =损失函数

损失函数(或目标函数、优化得分函数)是编制模型所需的两个参数之一。

[En]

The loss function (or objective function, optimization score function) is one of the two parameters needed to compile the model.


model.compile(
    optimizer='adam',
    loss='mse'
)

model.compile(loss='mean_squared_error', optimizer='sgd')

from keras import losses
model.compile(loss=losses.mean_squared_error, optimizer='sgd')

下面看看可用的损失函数


mean_squared_error(y_true, y_pred)

mean_absolute_error(y_true, y_pred)

mean_absolute_percentage_error(y_true, y_pred)

mean_squared_logarithmic_error(y_true, y_pred)

squared_hinge(y_true, y_pred)

hinge(y_true, y_pred)

categorical_hinge(y_true, y_pred)

logcosh(y_true, y_pred)

2.4 =优化器

1

2.5 =回调函数

1

2.6 多层感知器

MLP,Multilayer Perceptron,是一种前馈人工神经网络模型,其将输入的 &#x591A;&#x4E2A;&#x6570;&#x636E;&#x96C6;&#x6620;&#x5C04;&#x5230;&#x5355;&#x4E00;&#x7684;&#x8F93;&#x51FA;的数据集上。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FiZZUGB8-1662906394074)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-多层感知器-图解多层感知器-外面的图-1.png)]

如果从代码上看

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JFK515x3-1662906394074)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-多层感知器-图解多层感知器-1.png)]

以下情况实际上是一个具有三个自变量(输入)的多元线性回归模型。

[En]

The following case is actually a multiple linear regression model with three independent variables (inputs).

  • TV
  • Radio
  • Newspaper

因变量(输出)则是一个

  • sales

它们之间存在线性关系。让我们来看看数据集。

[En]

There is a linear relationship between them. Let’s take a look at the data set.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hrxxbaty-1662906394075)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-多层感知器-数据集-1.png)]

代码示例

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv(
    'E:/27_Python_Protect/02_ml/01-识别手写数字/hello02.csv'
)

x = data.iloc[:, 0:-1]
y = data.iloc[:, -1:]

model = tf.keras.Sequential(
    [

        tf.keras.layers.Dense(10, input_shape=(3,), activation='relu'),

        tf.keras.layers.Dense(1)
    ]
)

model.compile(
    optimizer='adam',
    loss='mse'
)

history = model.fit(x, y, epochs=10000)

prediction_data_set = data.iloc[:10, 0:-1]

preTemp = model.predict(prediction_data_set)

print("结果是 = ", preTemp)

2.7 逻辑回归与交叉熵

与线性回归不同的是,逻辑回归指的是是或否的答案,并匹配交叉熵损失函数来刻画实际产出与预期产出之间的距离,从而得到最终答案。

[En]

Different from linear regression, logical regression refers to the answer of yes or no, and matches the cross-entropy loss function to depict the distance between the actual output and the expected output to get the final answer.

首先查看数据集

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zxlaFE4X-1662906394075)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-逻辑回归与交叉熵的数据集简图-1.png)]

从前面的数据中,找出最后一个数据是1还是-1,然后查看代码

[En]

From the previous data, find out whether the last data is 1 or-1, and then look at the code

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.read_csv(
    'E:/27_Python_Protect/02_ml/01-识别手写数字/credit-a.csv', header=None
)

x = data.iloc[:, :-1]
y = data.iloc[:, -1:].replace(-1, 0)

model = tf.keras.Sequential(
    [
        tf.keras.layers.Dense(4, input_shape=(15,), activation='relu'),
        tf.keras.layers.Dense(4, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ]
)

model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['acc']
)

history = model.fit(x, y, epochs=10000)

没太学明白,后面再继续

2.8 待定

1

四、图像识别

说明:您可以在此处添加要记录在本文中的一般内容。

[En]

Description: here you can add the general content to be recorded in this article.

3.1 待定

1

3.2 待定:图像识别分类

这个案例将训练一个神经网络模型来对运动鞋和衬衫等服装图像进行分类。

[En]

This case will train a neural network model to classify clothing images such as sneakers and shirts.

(1)数据准备及处理

首先导入相关的类库和数据集。

[En]

First import the relevant class libraries and datasets.


import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

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

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

机器学习之TensorFlow - 补充学习中20220828

加载数据集会返回四个 NumPy 数组:

  • train_imagestrain_labels 数组是 训练集,即模型用于学习的数据;
  • 测试集test_imagestest_labels 数组会被用来对模型进行测试;

让我们对这些标签做一个简单的分类。

[En]

Let’s make a simple classification of these labels.


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

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


print(train_images.shape)
print(len(train_labels))
print(train_labels)

预处理数据 此时展示的是图像原始像素大小


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

需要将这些值缩小至0到1之间,然后将其馈送到神经网络模型


train_images = train_images / 255.0
test_images = test_images / 255.0

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()

(2)模型构建及训练

构建神经网络前

  1. 配置模型的层;
  2. 编译模型;

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

第一层网络:keras.layers.Flatten,将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。

第二、三层网络:keras.layers.Dense,两层神经元序列。


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

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

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\n 评估准确率 Test accuracy:', test_acc)

(3)预测/最终效果

这里我就偷懒一下吧

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

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')

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-yePQL5B9-1662906394075)(https://csdn-pic-1301850093.cos.ap-guangzhou.myqcloud.com/csdn-pic/tensorflow-图像衣服分类的效果图-1.png)]

(4)完整代码


import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

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

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

train_images = train_images / 255.0
test_images = test_images / 255.0

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

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

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

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\n 评估准确率 Test accuracy:', test_acc)

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

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')

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()

3.3 待定

1

总结

提示:以下是这篇文章的摘要:

[En]

Tip: here is a summary of the article:

例如,这就是我们今天要讨论的问题。

[En]

For example, that is what we are going to talk about today.

Original: https://blog.csdn.net/weixin_48518621/article/details/126456029
Author: lijiamin-
Title: 机器学习之TensorFlow – 补充学习中20220828

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/514166/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球