4-2 3D images: Volumetric data Representing tabular data

本文所用到的资料下载地址

By stacking individual 2D slices into a 3D tensor, we can build volumetric data representing the 3D anatomy of a
subject. We just have an extra dimension, depth, after the channel dimension, leading to a 5D tensor of shape N × C × D × H × W.

N 表示样本(图片)的数量
C 表示特征通道的数量
D 表示深度维度的大小(例如,对于三维图像,表示图像的深度)
H 表示图像的高度
W 表示图像的宽度
在这里插入图片描述

Let’s load a sample CT scan using the volread function in the imageio module, which takes a directory as an argument and assembles all Digital Imaging and Communications in Medicine (DICOM) files in a series in a NumPy 3D array.

import imageio.v2 as imageio
dir_path = "D:/Deep-Learning/资料/dlwpt-code-master/data/p1ch4/volumetric-dicom/2-LUNG 3.0  B70f-04083"
# volread从文件中读取三维体积数据,返回结果为NumPy数组
vol_arr = imageio.volread(dir_path, 'DICOM')  # DICOM表示要使用的解码器格式,以确保正确解析DICOM文件
vol_arr.shape  # 结果的99表示该三维图像是由99张2维图像从bottom到top叠加得到的

在这里插入图片描述
我们可以使用以下代码打印其中的某张图片,例如第50张

%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(vol_arr[50])

在这里插入图片描述
纵切面

在这里插入图片描述

The layout is different from what PyTorch expects, due to having no channel information. So we’ll have to make room for the channel dimension using unsqueeze:

import torch
vol = torch.from_numpy(vol_arr).float()
vol = torch.unsqueeze(vol, 0)
vol.shape

在这里插入图片描述

The simplest form of data we’ll encounter on a machine learning job is sitting in a spreadsheet, CSV file, or database. Whatever the medium, it’s a table containing one row per sample (or record), where columns contain one piece of information about our sample.

Columns may contain numerical values, like temperatures at specific locations; or labels, like a string expressing an attribute of the sample, like “blue.” Therefore, tabular data is typically not homogeneous: different columns don’t have the same type. We might have a column showing the weight of apples and another encoding their color in a label.

PyTorch tensors, are homogeneous. Information in PyTorch is typically encoded as a number, typically floating-point (though integer types and Boolean are supported as well).

Our first job as deep learning practitioners is to encode heterogeneous, real-world data into a tensor of floating-point numbers, ready for consumption by a neural network.

在这里插入图片描述
The first 11 columns contain values of chemical variables, and the last column contains the sensory quality score from 0 (very bad) to 10 (excellent).A possible machine learning task on this dataset is predicting the quality score from chemical characterization alone.

We have to get the training data from somewhere! As we can see in figure 4.3, we’re hoping to find a relationship between one of the chemical columns in our data and the quality column. Here, we’re expecting to see quality increase as sulfur decreases.

在这里插入图片描述

Let’s load our file and turn the resulting NumPy array into a PyTorch tensor.

import csv
import numpy as np
wine_path = "D:/Deep-Learning/资料/dlwpt-code-master/data/p1ch4/tabular-wine/winequality-white.csv"
wineq_numpy = np.loadtxt(wine_path, dtype=np.float32, delimiter=";",skiprows=1)
# skiprows=1 表示跳过第一行的标题行
wineq_numpy

在这里插入图片描述

We can obtain column names (the first row of data) using this approach.

col_list = next(csv.reader(open(wine_path), delimiter=';'))
col_list

在这里插入图片描述

Let’s check that all the data has been read.

在这里插入图片描述
在这里插入图片描述

and proceed to convert the NumPy array to a PyTorch tensor:

wineq = torch.from_numpy(wineq_numpy)
wineq
wineq.shape, wineq.dtype

在这里插入图片描述
在这里插入图片描述
At this point, we have a floating-point torch.Tensor containing all the columns, including the last, which refers to the quality score.

Continuous, ordinal, and categorical values
continuous values: Stating that package A is 2 kilograms heavier than package B, or that package B came from 100 miles farther away than A has a fixed meaning. If you’re counting or measuring something with units, it’s probably a continuous value.
ordinal values: A good examplenof this is ordering a small, medium, or large drink, with small mapped to the value 1, medium 2, and large 3. The large drink is bigger than the medium, in the same way that 3 is bigger than 2, but it doesn’t tell us anything about how much bigger.
categorical values: Assigning water to 1, coffee to 2, soda to 3, and milk to 4 is a good example.

在处理一个包含scores(即quality)的问题时,可以将评分视为连续变量并进行回归任务,或将其视为标签并尝试从化学分析中猜测标签的分类任务。在这两种方法中,通常会从输入数据的张量中移除scores(下文data),并将其保存在一个单独的张量中(下文target),这样我们可以将score作为真实值使用,而不将其作为模型的输入。

将scores作为分类任务中的标签,而输入数据是基于化学分析的其他特征。这样的任务旨在根据给定的化学分析特征,通过模型预测和分类的方式来推断scores的标签或类别。通过这种方式,我们可以使用模型从输入数据中学习化学特征与评分之间的关联,并进行分类预测。

data = wineq[:, :-1]  # Selects all rows and all columns except the last
data,data.shape

在这里插入图片描述

target = wineq[:, -1]  # Selects all rows and the last column
target, target.shape

在这里插入图片描述

标签张量(Label tensor)是一个包含离散标签值的张量。在分类任务中,我们通常将目标值(target)转换为标签张量,其中每个样本的目标值表示为一个整数,代表样本所属的类别或标签。标签张量的形状通常与输入数据的形状相对应,每个样本都有一个对应的标签值。
例如,如果我们有一个包含10个样本的数据集(可以将其看成表格的第一列),每个样本有3个特征(可以将其看成表格的第一行),而目标是将样本分为3个类别(标签为0、1和2),那么标签张量的形状将是(10,),其中每个元素表示一个样本的类别标签。(简单说,每一列就是一个标签张量)
标签张量在训练和评估模型时起着重要的作用。它用于计算损失函数,评估模型的性能,并与模型的预测进行比较,以确定预测是否正确。

如果我们想把target转换成标签张量,一种方法是简单地将标签视为scores的整数向量:

target = wineq[:, -1].long()
target

在这里插入图片描述

另一种方法是构建分数的one-hot encoding
也就是说,在由10个元素组成的向量中对10个scores进行编码,所有元素都被设置为0(除了1),每个scores的索引都不同。这样,1的score可以映射到向量(1,0,0,0,0,0,0,0,0,0,0,0,0),5的score可以映射到(0,0,0,0,1,0,0,0,0,0),以此类推。

这两种方法有明显的区别。将葡萄酒质量scores保存在scores的整数向量中会对scores进行排序(例如1低于4)。它还能推导出分数之间的某种距离(1到3的距离=2到4的距离)。如果分数是纯粹离散的,就像葡萄品种,one-hot encoding将是一个更好的匹配,因为没有隐含的顺序或距离。

在这里插入图片描述

使用target.shape[0]即可表示样本数量
10表示类别总数
现在我们创建了一个全零张量target_onehot

target_onehot = torch.zeros(target.shape[0], 10)

在这里插入图片描述

我们可以使用scatter_ 方法实现one-hot encoding
名称以下划线结尾,表明该方法将不返回一个新的张量,而是在适当的地方修改张量
第一个参数1表示在维度1(列维度)上进行散布操作
unsqueeze使target从[4898]变为[4898, 1],扩展后的张量就可以作为索引张量,用于指定在维度1上进行散布操作的位置

在这里插入图片描述

1.0表示按照目标标签的索引位置进行散布操作,即每个样本的目标标签对应的位置会被设置为1.0,而其他位置仍保持为0.0

target_onehot.scatter_(1, target.unsqueeze(1), 1.0)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

可以看到,第一行的第6个位置(从0起)被置为1(表示6)
倒数第二行的地7个位置(从0起)被置为1(表示7)

下面进行标准化
首先求各列的均值和标准差

data_mean=torch.mean(data,dim=0)  # 均值
data_mean

在这里插入图片描述

data_var=torch.var(data,dim=0)  # 方差
data_var

在这里插入图片描述

我们可以通过减去均值并除以标准差来标准化数据

data_normalized=(data-data_mean)/torch.sqrt(data_var)
data_normalized

在这里插入图片描述

我们来看看这些数据,是否有一种简单的方法可以一眼就分辨出葡萄酒的好坏。
First, we’re going to determine which rows in target correspond to a score less than or equal to 3:

bad_indexed=target<=3
bad_indexed
print(bad_indexed.shape)
print(bad_indexed.dtype)
print(bad_indexed.sum())

在这里插入图片描述

Note that only 20 of the bad_indexes entries are set to True.
For example,
在这里插入图片描述
The bad_indexes tensor has the same shape as target, with values of False or True depending on the outcome of the comparison between our threshold and each element in the original target tensor:

bad_data=data[bad_indexed]
bad_data

在这里插入图片描述
在这里插入图片描述
Note that the new bad_data tensor has 20 rows, the same as the number of rows with True in the bad_indexes tensor. It retains all 11 columns.

Now we can start to get information about wines grouped into good, middling, and bad categories. Let’s take the .mean() of each column:

bad_data=data[target<=3]
mid_data=data[(target>3)&(target<7)]
good_data=data[target>=7]
bad_mean=torch.mean(bad_data,dim=0)
mid_mean=torch.mean(mid_data,dim=0)
good_mean=torch.mean(good_data,dim=0)

zip函数将col_list、bad_mean、mid_mean和good_mean按索引依次配对,生成一个迭代器,每次迭代输出一个四元组。enumerate函数用于遍历这个迭代器,并返回每个元素及其对应的索引。i是索引,args是一个四元组,分别对应每个列的名称和其对应的坏、中等、好类别的平均值。在遍历过程中,可以使用i和args来处理每一列的数据和平均值。

format方法用于格式化输出字符串。前面输出5个,分别是i和args四元组,使用大括号格式化
‘{:2}’ :使用两个字符的宽度对齐,并且右对齐
‘{:20}’ :使用二十个字符的宽度对齐,并且左对齐。
‘{:6.2f}’ :使用六个字符的宽度对齐,其中两位小数,并且右对齐。

*args用于将四元组中的元素解包作为参数传递给format方法,这样可以按顺序填充格式化字符串中的占位符。通过这种方式,代码将索引、列名和平均值按指定格式输出为表格形式。

for i,args in enumerate(zip(col_list,bad_mean,mid_mean,good_mean)):
    print('{:2} {:20} {:6.2f} {:6.2f} {:6.2f}'.format(i,*args))

在这里插入图片描述

在这里插入图片描述

It looks like we’re on to something here: at first glance, the bad wines seem to have higher total sulfur dioxide, among other differences. We could use a threshold on total sulfur dioxide as a crude criterion for discriminating good wines from bad ones.

torch.lt(x, y) 比较 x 和 y 的每个元素,并返回一个布尔张量。x<y true,否则false
import torch

x = torch.tensor([1, 2, 3, 4, 5])
y = torch.tensor([3, 3, 3, 3, 3])
result = torch.lt(x, y)
print(result) # Output: tensor([ True, True, False, False, False])`

total_sulfur_threshold=141.83  # total sulfur dioxide 的 mid
total_sulfur_data=data[:,6]  # total sulfur dioxide列
predicted_indexes=torch.lt(total_sulfur_data,total_sulfur_threshold)
predicted_indexes

在这里插入图片描述

predicted_indexes.shape,predicted_indexes.dtype,predicted_indexes.sum()

在这里插入图片描述
This means our threshold implies that just over half of all the wines are going to be high quality.
(total sulfur dioxide越小越好,有2727个小于threshold,即我们预测有2727瓶好酒)

Next, we’ll need to get the indexes of the actually good wines:

actual_indexes=target>5
actual_indexes.sum()

在这里插入图片描述

Since there are about 500 more actually good wines than our threshold predicted, we already have hard evidence that it’s not perfect.(之前拿>=7定义好酒,现在又改成5了,emmmm)

Now we need to see how well our predictions line up with the actual rankings. We will perform a logical “and” between our prediction indexes and the actual good indexes (remember that each is just an array of zeros and ones) and use that intersection of wines-in-agreement to determine how well we did:

当我们从一个张量中提取单个元素时,得到的是一个张量,而不是一个标量。这时,如果我们希望得到这个张量的数值值(即标量),可以使用.item() 方法。
x = torch.tensor(3.5)
value = x.item()
print(value) # 输出 3.5

n_matches = torch.sum(actual_indexes & predicted_indexes).item()
n_predicted = torch.sum(predicted_indexes).item()
n_actual = torch.sum(actual_indexes).item()
n_matches, n_matches / n_predicted, n_matches / n_actual

在这里插入图片描述
We got around 2,000 wines right! Since we predicted 2,700 wines, this gives us a 74% chance that if we predict a wine to be high quality, it actually is. Unfortunately, there are 3,200 good wines, and we only identified 61% of them. Well, we got what we signed up for; that’s barely better than random!

Of course, this is all very naive: we know for sure that multiple variables contribute to wine quality, and the relationships between the values of these variables and the outcome (which could be the actual score, rather than a binarized version of it) is likely more complicated than a simple threshold on a single value.

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

[MySQL]MySQL事务特性

[MySQL]MySQL事务 文章目录 [MySQL]MySQL事务1. 事务的概念2. 为什么会出现事务3. 事务的版本支持4. 事务的提交方式5. 事务常见操作方式6. 事务隔离级别事务隔离级别概念查看事务的隔离级别设置事务的隔离级别读未提交&#xff08;Read Uncommitted&#xff09;读提交&#xf…

【力扣算法20】之 8. 找出字符串中第一个匹配项的下标 (python方向)

文章目录 问题描述示例1示例2提示 思路分析代码分析完整代码详细分析运行效果截图调用示例运行结果 完结 问题描述 给你两个字符串 haystack 和 needle &#xff0c;请你在haystack字符串中找出needle字符串的第一个匹配项的下标&#xff08;下标从 0 开始&#xff09;。如果 n…

htmlCSS-----浮动

目录 前言&#xff1a; 浮动 1.浮动的效果 2.浮动的特点 3.浮动的写法 4.浮动的原理 5.浮动的作用 6.案例 7.浮动的缺陷与解决方式 浮动问题 解决方式 8.补充说明 前言&#xff1a; 浮动是html里面重要的一部分&#xff0c;前面我们学习了三种元素的类型&#xff08;…

计科web常见错误排错【HTTP状态404、导航栏无法点开、字符乱码及前后端数据传输呈现、jsp填写的数据传到数据库显示null、HTTP状态500】

web排错记录 在使用javaweb的过程中会出现的一些错误请在下方目录查找。 目录 错误1&#xff1a;HTTP状态404——未找到 错误2&#xff1a;导航栏下拉菜单无法点开的问题 错误3&#xff1a;字符乱码问题 错误4&#xff1a;jsp网页全部都是&#xff1f;&#xff1f;&#x…

Golang并发控制

开发 go 程序的时候&#xff0c;时常需要使用 goroutine 并发处理任务&#xff0c;有时候这些 goroutine 是相互独立的&#xff0c;需要保证并发的数据安全性&#xff0c;也有的时候&#xff0c;goroutine 之间要进行同步与通信&#xff0c;主 goroutine 需要控制它所属的子gor…

Linux系统安装部署MySQL完整教程(图文详解)

前言&#xff1a;最近网上翻阅了大量关于Linux安装部署MySQL的教程&#xff0c;在自己部署的时候总是存在一些小问题&#xff0c;例如&#xff1a;版本冲突&#xff0c;配置失败和启动失败等等&#xff0c;功夫不负有心人&#xff0c;最后还是安装部署成功了&#xff0c;所以本…

Ubuntu 网络配置指导手册

一、前言 从Ubuntu 17.10 Artful开始&#xff0c;Netplan取代ifupdown成为默认的配置实用程序&#xff0c;网络管理改成 netplan 方式处理&#xff0c;不在再采用从/etc/network/interfaces 里固定 IP 的配置 &#xff0c;配置写在 /etc/netplan/01-network-manager-all.yaml 或…

文本预处理——文本处理的基本方法

目录 什么是分词jieba分词特性精确模式分词全模式分词搜索引擎模式分词使用用户自定义词典 命名实体识别词性标注 什么是分词 jieba分词特性 精确模式分词 import jieba content工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作 print(jieba.lcut(co…

一文了解Python中的while循环语句

目录 &#x1f969;循环语句是什么 &#x1f969;while循环 &#x1f969;遍历猜数字 &#x1f969;while循环嵌套 &#x1f969;while循环嵌套案例 &#x1f990;博客主页&#xff1a;大虾好吃吗的博客 &#x1f990;专栏地址&#xff1a;Python从入门到精通专栏 循环语句是什…

SpringBoot创建和使用

1.Spring Boot的优点 快速集成框架&#xff0c;Spring Boot提供了启动添加依赖的功能&#xff0c;用于秒级成各种框架。内置运行容器&#xff0c;无需配备Tomcat等Web容器&#xff0c;直接运行和部署程序。快速部署项目&#xff0c;无需外部容器即可启动并运行项目。可以完全抛…

概率论和随机过程的学习和整理--番外15,如何计算N合1的合成数量问题?

目录 1 目标问题&#xff1a;多阶2合1的合成问题 1.1 原始问题 1.2 合成问题要注意&#xff0c;合成的数量 1.3 合成问题不能用马尔科夫链来解决 2 方案1&#xff1a;用合成公式合成多次能解决吗&#xff1f; --不能&#xff0c;解决不了递归的问题 3 方案2&#xff0c;…

idea2021.安装pojie教程

1、下载ideaIU-2021.3应用包&#xff0c;点击finish 2、先关闭idea窗口&#xff0c;等会激活了脚本再运行打开。 3、双击运行install-current-user.vbs&#xff0c;等待一会会提示运行成功。 4、运行后&#xff0c;在文件中会多出一条配置 5、打开运行idea,输入激活码&#x…

如何使用curl下载github代码

首先通过chrome打开想要下载的源文件 如图&#xff0c;有那个下载图标时表示不需要鉴权即可下载&#xff0c;一般仓库都会开放只读权限&#xff0c;所以很大概率都有 比如我想下载这个crc32.c文件 那么我就需要知道它在哪个IP中&#xff0c;按下F12打开网络&#xff0c;点击下载…

pytorch安装GPU版本 (Cuda12.1)教程

使用本教程前&#xff0c;默认您已经安装并配置好了python3以上版本 1. 去官网下载匹配的Cuda Cuda下载地址 当前最高版本的Cuda是12.1 我安装的就是这个版本 小提示&#xff1a;自定义安装可以只选择安装Cuda Runtime。Nvidia全家桶不必全部安装。把全家桶全部安装完直接系统…

ChatGPT助力校招----面试问题分享(十二)

1 ChatGPT每日一题&#xff1a;运算放大器与比较器的区别 问题&#xff1a;运算放大器与比较器的区别 ChatGPT&#xff1a;运算放大器和比较器都是电子电路中常用的模拟电路元件&#xff0c;但它们的设计和应用略有不同。下面是两者的主要区别&#xff1a; 功能不同&#xf…

Java集合之List

ArrayLsit集合 ArrayList集合的特点 ArrayList集合的一些方法 ①.add(Object element) 向列表的尾部添加指定的元素。 ②.size() 返回列表中的元素个数。 ③.get(int index) 返回列表中指定位置的元素&#xff0c;index从0开始。 public class Test {public static void m…

【Vue】day03-VueCli(脚手架)

day03 一、今日目标 1.生命周期 生命周期介绍 生命周期的四个阶段 生命周期钩子 声明周期案例 2.综合案例-小黑记账清单 列表渲染 添加/删除 饼图渲染 3.工程化开发入门 工程化开发和脚手架 项目运行流程 组件化 组件注册 4.综合案例-小兔仙首页 拆分模块-局部…

有名管道(FIFO)的学习笔记

文章目录 有名管道介绍有名管道的使用创建 注意事项 有名管道介绍 有名管道的使用 创建 命令&#xff0c; mkfifo name函数&#xff0c;int mkfifo(const char *pathname, mode_t mode); 设置错误号&#xff1b; 向管道中写数据&#x1f447;&#xff1a; 从管道读数据&am…

前端Web实战:从零打造一个类Visio的流程图拓扑图绘图工具

前言 大家好&#xff0c;本系列从Web前端实战的角度&#xff0c;给大家分享介绍如何从零打造一个自己专属的绘图工具&#xff0c;实现流程图、拓扑图、脑图等类Visio的绘图工具。 你将收获 免费好用、专属自己的绘图工具前端项目实战学习如何从0搭建一个前端项目等基础框架项…

log4j--动态打印日志文件到指定文件夹

文章目录 log4j--动态打印日志文件到指定文件夹1、添加Maven依赖2、配置文件 log4j.properties3、编写日志打印工具类 LogUtil4、工具类调用 log4j–动态打印日志文件到指定文件夹 1、添加Maven依赖 <!-- log4j日志相关坐标 --><dependency><groupId>org.s…
最新文章