对Fashion._mnist进行10分类ipynb

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'#设置tensorflow的日志级别
from tensorflow.python.platform import build_info

import tensorflow as tf

# 列出所有物理GPU设备  
gpus = tf.config.list_physical_devices('GPU')  
if gpus:  
    # 如果有GPU,设置GPU资源使用率  
    try:  
        # 允许GPU内存按需增长  
        for gpu in gpus:  
            tf.config.experimental.set_memory_growth(gpu, True)  
        # 设置可见的GPU设备(这里实际上不需要,因为已经通过内存增长设置了每个GPU)  
        # tf.config.set_visible_devices(gpus, 'GPU')  
        print("GPU可用并已设置内存增长模式。")  
    except RuntimeError as e:  
        # 虚拟设备未就绪时可能无法设置GPU  
        print(f"设置GPU时发生错误: {e}")  
else:  
    # 如果没有GPU  
    print("没有检测到GPU设备。")

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

fashion_mnist = tf.keras.datasets.fashion_mnist

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

# 将数据保存到 npz 文件中  
np.savez_compressed('./datasets/fashion_mnist.npz',  
                      train_images=train_images,  
                      train_labels=train_labels,  
                      test_images=test_images,  
                      test_labels=test_labels)

data=np.load('./datasets/fashion_mnist.npz')

train_images = data['train_images']  
train_labels = data['train_labels']  
test_images = data['test_images']  
test_labels = data['test_labels']

print(train_images.shape,train_labels.shape,np.unique(train_labels))

print(train_images.max(),train_images.min())

#数字标签对应的类别
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

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):#展示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()

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=((28,28))),
    tf.keras.layers.Flatten(),#扁平化处理成行向量
    tf.keras.layers.Dense(128, activation='relu'),#线性转换层
    tf.keras.layers.Dense(10)#输出层,10个分值,对应模型对于输入数据应该属于这10个类别的置信度
])

model.summary()

#优化器,损失函数,指标,这个损失会对标签做类似one-hot的处理
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('\nTest accuracy:', test_acc)

#模型训练好后可以加一个概率层把logits转换成概率
probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])

predictions = probability_model.predict(test_images)

np.argmax(predictions[0])#获取其中最大值对应的索引下标

test_labels[0]

def plot_image(i, predictions_array, true_label, img):
  true_label, img = 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):
  true_label = 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')

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

i = 12
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]
print(img.shape)

#在0轴增加1个维度
img = (np.expand_dims(img,0))
print(img.shape)

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)
plt.show()

np.argmax(predictions_single[0])

test_labels[1]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/796433.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django -- 报错

通过终端命令来创建新的 app 时报错 执行命令: python manage.py startapp mysite04 具体报错内容如下: Traceback (most recent call last):File "mysite\manage.py", line 22, in <module>main()File "mysite\manage.py", line 18, in mainexecut…

汽车疲劳测试试验平台技术要求(北重厂家)

汽车疲劳测试试验平台技术要求通常包括以下几个方面&#xff1a; 车辆加载能力&#xff1a;测试平台需要具备足够的承载能力&#xff0c;能够同时测试多种车型和不同重量的车辆。 动力系统&#xff1a;测试平台需要具备稳定可靠的动力系统&#xff0c;能够提供足够的力和速度来…

[高考] 数理化

借助前些天总结的热乎劲&#xff1a;[高考] 数学题的一般解题思路。再总结一下数理化的一般认识。在高中分班的时候&#xff0c;还是建议选择理科。后续的路子会更广一些。 这三科与语文/英语的区别也是非常明显。当然也有类似的地方。英语和语文&#xff0c;这两个是语言类学…

设计模式之建造者模式:灵活可扩展的对象创建过程

目录 一、什么是建造者模式 二、建造者模式的应用场景 三、建造者模式的优缺点 3.1. 优点 3.2. 缺点 四、建造者模式示例 4.1. 问题描述 4.2. 问题分析 4.3. 代码实现 五、建造者模式的另一种实现方式 六、总结 一、什么是建造者模式 建造者模式&#xff08;Builder…

C# 分布式自增ID算法snowflake(雪花算法)

文章目录 1. 概述2. 结构3. 代码3.1 IdWorker.cs3.2 IdWorkerTest.cs (测试) 1. 概述 分布式系统中&#xff0c;有一些需要使用全局唯一ID的场景&#xff0c;这种时候为了防止ID冲突可以使用36位的UUID&#xff0c;但是UUID有一些缺点&#xff0c;首先他相对比较长&#xff0c…

.NET 设计模式—适配器模式(Adapter Pattern)

简介 适配器模式&#xff08;Adapter Pattern&#xff09;&#xff1a;就是将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。 在计算机编程中&#xff0c;适配器模式&#xff08;有时候也称包装样式或者…

ThreadLocal加切面实现线程级别的方法缓存

1、实现效果 当一个请求线程多次请求A方法时,只会触发一次A方法的实际调用,会将方法结果缓存起来,避免多次调用。 2、实现过程 1. 需要一个注解ThreadLocalCache,在需要缓存的方法上加上该注解 2. 需要一个切面,借助ThreadLocal,将结果缓存起来,利用环绕通知来实现方法拦截从…

vue项目使用element ui

目录 1、创建一个vue项目 2、找到element官网&#xff0c;点击指南&#xff0c;找到安装栏 3、 找到使用包管理器&#xff0c;复制命令 4、在main.js中引入element 5、使用element ui 6、找到App.vue&#xff0c;导入Button.vue文件&#xff0c;保存启动项目 1、创建一个vu…

MySQL复制拓扑1

文章目录 主要内容一.安装MySQL服务器1.MySQL 安装程序和其它文件保存在下发的 mysql8-files.iso 镜像文件中&#xff0c;可以使用虚拟光驱来提取到 Linux 文件系统。代码如下&#xff08;示例&#xff09;: 2.将 MySQL8.0 程序解压到 /opt 目录&#xff0c;再创建到 MySQL 默认…

阿里巴巴Java开发 单元测试和安全规约

目录 前言 1.单元测试 2.安全规约 前言 单元测试和安全规约依次分为【重要】、【建议】、【参考】,整理单元测试和安全规约为了更好处理代码中bug,使得代码更加安全。 1.单元测试 1.【重要】好的单元测试必须遵守 AIR 原则。 说明:单元测试在线上运行时,感觉像空气(…

闪站侠洗护管理系统,洗衣洗鞋小程序软件定制,干洗连锁店软件系统搭建;

闪站侠洗护管理系统&#xff0c;洗衣洗鞋小程序软件定制&#xff0c;干洗连锁店软件系统搭建&#xff1b; 为了让每一个洗衣洗鞋工厂与门店的连接更加高效便捷&#xff0c;送洗流程更加简单轻松&#xff0c;拽牛科技倾心打造洗衣洗鞋管理软件。我们的目标是通过高效和优质的服务…

双指针(复习)

基本概念 双指针:在区间操作时&#xff0c;利用两个下标同时遍历&#xff0c;进行高效操作 双指针利用区间性质可以把0(n2)时间降低到0(n) 蓝桥532 import os import sys# 请在此输入您的代码 w int(input()) n int(input()) b [] ans 0 for i in range(n):b.append(int(…

复现chatgpt_ros,需要openapi key

&#xff11;&#xff0e; 前置工作&#xff1a; 现在&#xff55;buntu系统是20.04ros1&#xff0c;现在用docker新建并安装ros2&#xff1a; 最简单的&#xff0c;用大佬的一键安装&#xff1a; wget http://fishros.com/install -O fishros && . fishros 其次自己装…

基于沙漏 Tokenizer 的高效三维人体姿态估计框架HoT

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 摘要Abstract文献阅读&#xff1a;基于沙漏 Tokenizer 的高效三维人体姿态估计框架HoT1、研究背景2、提出方法3、模块详细3.1、什么是HoT3.2、HoT 框架3.3、Token 剪…

应用性能分析工具CPU Profiler

简介 本文档介绍应用性能分析工具CPU Profiler的使用方法&#xff0c;该工具为开发者提供性能采样分析手段&#xff0c;可在不插桩情况下获取调用栈上各层函数的执行时间&#xff0c;并展示在时间轴上。 开发者可通过该工具查看TS/JS代码及NAPI代码执行过程中的时序及耗时情况…

JDK安全剖析之安全处理入门

0.前言 Java 安全包括大量 API、工具以及常用安全算法、机制和协议的实现。Java 安全 API 涵盖了广泛的领域&#xff0c;包括加密、公钥基础设施、安全通信、身份验证和访问控制。Java 安全技术为开发人员提供了编写应用程序的全面安全框架&#xff0c;还为用户或管理员提供了…

WebSocketServer后端配置,精简版

首先需要maven配置 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><version>2.1.3.RELEASE</version></dependency> 然后加上配置类 这段代码是一个Spri…

Matlab中的参数定义

Matlab中的参数定义 文章目录 Matlab中的参数定义写在前面参数量验证实际使用数组有效性检查被检查数据类型有效数据类型有效属性举例说明文本有效性检查举例说明参考写在前面 Matlab是一种非类型化语言,大多数函数都不需要参数声明或验证。但是为了保证程序的通用性和按照预…

0204克拉默法则-矩阵及其运算-线性代数

含有n个未知数 x 1 , x 2 , ⋯ , x n x_1,x_2,\cdots,x_n x1​,x2​,⋯,xn​的n个线性方程的方程组 { a 11 x 1 a 12 x 2 ⋯ a 1 n x n b 1 , a 21 x 1 a 22 x 2 ⋯ a 2 n x n b 2 , ⋯ ⋯ , a n 1 x 1 a n 2 x 2 ⋯ a n n x n b n , \begin{cases} a_{11}x_1a_{1…

以Kotti项目为例使用pytest测试项目

在维护和构建大型项目时&#xff0c;单独一个一个手工测试代码已经不适用了&#xff0c;这时候就要用专门的测试框架进行测试。让我们以Kotti项目为例&#xff0c;用pytest这个测试框架进行实践测试吧。 使用python3.10 Ubuntu 系统 准备工作 下载和安装kotti库 pip install…