TensorFlow 分类模型

在这里插入图片描述

TensorFlow 构建模型与训练

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import pandas as pd
import os
import sys
import time
import tensorflow as tf
from tensorflow_core.python import keras
from sklearn.preprocessing import StandardScaler

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
assert tf.__version__.startswith('2.')

# 0.打印导入模块的版本
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, sklearn, pd, tf, keras:
    print("%s version:%s" % (module.__name__, module.__version__))

# 1.加载fashion_mnist数据集
fashion_mnist = keras.datasets.fashion_mnist
(x_train_all, y_train_all), (x_test, y_test) = fashion_mnist.load_data()

# 2.拆分验证集, 训练集
x_valid, x_train = x_train_all[:5000], x_train_all[5000:]
y_valid, y_train = y_train_all[:5000], y_train_all[5000:]

# 3.打印 验证集, 训练集, 测试集
print(x_train.shape, y_train.shape)
print(x_valid.shape, y_valid.shape)
print(x_test.shape, y_test.shape)

# 4.数据集初始化
scaler = StandardScaler()

x_train_scaled = scaler.fit_transform(
    x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_valid_scaled = scaler.transform(
    x_valid.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_test_scaled = scaler.transform(
    x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)


def plot_learning_curves(history):
    """显示学习过程图

    :param history: 训练历史信息
    """

    # 显示数据
    pd.DataFrame(history.history).plot(figsize=(8, 5))

    plt.grid(True)
    # 显示Y轴范围
    plt.gca().set_ylim(0, 1)
    plt.show()


def main():

    # 1.网络模型构建
    model = keras.Sequential()
    model.add(keras.layers.Flatten(input_shape=[28, 28]))
    model.add(keras.layers.Dense(300, activation="relu"))
    model.add(keras.layers.Dense(100, activation="relu"))
    model.add(keras.layers.Dense(10, activation="softmax"))
	
	# 激活函数公式
    # relu: y = max(0, x)
	# softmax x = [x1, x2, x3]
	#         y = [e^x1/sum, e^x2/sum, e^x3/sum]
	#         sum = e^x1 + e^x2 + e^x3

    # 2.编译模型
    # reason for sparse: y->index => y->one_hot->[]
    # sparse_categorical_crossentropy  y->index  数据是索引模式
    # categorical_crossentropy y->one_hot        数据是one_hot模式
    model.compile(loss="sparse_categorical_crossentropy",  # 损失函数
                  optimizer="adam",                        # 模型优化方法
                  metrics=["accuracy"])                    # 指标 准确度

    # 3.打印模型
    print(model.layers)
    model.summary()

    # 4.训练模型
    # [None, 784] * w + b ->[None, 100] w.shape[784, 300], b = [300]
    history = model.fit(x_train_scaled, y_train, # 训练集数据
    					epochs=10, # 循环次数
                        validation_data=(x_valid_scaled, y_valid)) # 验证集数据

    # 5.训练结果显示
    print(type(history))
    plot_learning_curves(history)


if __name__ == '__main__':
    main()

学习过程显示结果

loss:损失函数结果
accuracy: 正确率
val_loss 验证损失函数结果
val_accuracy:验证集损失函数结果

在这里插入图片描述

显示图片

def show_images(n_rows, n_cols, x_data, y_data, class_names):
    assert len(x_data) == len(y_data)
    assert n_rows * n_cols < len(x_data)
    plt.figure(figsize=(n_cols * 1.4, n_rows * 1.6))
    for row in range(n_rows):
        for col in range(n_cols):
            index = n_cols * row + col
            plt.subplot(n_rows, n_cols, index + 1)
            plt.imshow(x_data[index], cmap="binary",
                       interpolation='nearest')
            plt.axis('off')
            plt.title(class_names[y_data[index]])
    plt.show()

# 类型名字
class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress',
               'Coat', 'Sandal', 'Shirt', 'Sneaker',
               'Bag', 'Ankle boot']
# 显示图片
show_images(3, 5, x_train, y_train, class_names)

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
TensorFlow C模型是指使用C语言编写的、基于TensorFlow开发的模型TensorFlow是一个用于机器学习和深度学习的强大框架,它提供了许多工具和函数,以简化模型的开发和部署过程。 使用TensorFlow C模型可以实现许多机器学习任务,包括图像分类、目标检测、自然语言处理等。将模型使用C语言编写可以使得模型在嵌入式设备、移动设备等资源有限的环境中运行,具有较小的资源占用和高效的计算能力。 TensorFlow C模型开发的过程主要包括以下几个步骤: 1. 准备数据集:根据任务需求,收集合适的数据集,并进行数据预处理,使其适合训练和测试模型。 2. 模型设计与训练:使用TensorFlow提供的接口和函数,搭建并训练模型。可以选择合适的网络结构、优化算法和损失函数等,以提高模型的性能和效果。 3. 模型导出:通过TensorFlow的保存机制,将训练好的模型导出为.pb文件,以便于后续在C语言环境中加载和使用。 4. C语言部署:使用C语言编写代码,加载导出的模型文件,并对新的数据进行预测。可以利用TensorFlow C API提供的接口,针对具体的需求进行封装和优化。 5. 模型优化和调试:根据实际情况,对模型进行进一步优化和调试,以提高准确率和速度。 总之,TensorFlow C模型是使用C语言开发的基于TensorFlow的机器学习模型。它具有高效的计算能力和较小的资源占用,适用于嵌入式设备和移动设备等资源有限的环境。使用TensorFlow C模型可以实现各种机器学习任务,并通过C语言编写的代码进行部署和应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

廷益--飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值