tensorflow基础:tf.data.Dataset.from_tensor_slices()

tf.data.Dataset.from_tensor_slices()的用法 将输入数据(张量、数组、元组、字典等)按第一个维度切片,生成数据集元素‌。‌:输入为元组或字典时,所有元素的第一个维度必须相同,切片后每个样本的。特征和标签一一对应‌。 阅读详情

tf.data.Dataset.from_tensor_slices()

语义解释:from_tensor_slices,从张量的切片读取数据。

工作原理:将输入的张量的第一个维度看做样本的个数,沿其第一个维度将tensor切片,得到的每个切片是一个样本数据。实现了输入张量的自动切片。

输入数据格式/要求:

        1)可以是numpy格式,也可以是tensorflow的tensor的格式,函数会自动将numpy格式转为tensorflow的tensor格式

        2)输入可以是一个tensor

                                   或   一个tensor字典(字典的每个key对应的value是一个tensor,要求各tensor的第一个维度相等)

                                   或    一个tensor  tuple(tuple 的每个元素是一个tensor,要求各tensor的第一个维度相等)。

示例代码:


import tensorflow as tf
import numpy as np

## 测试1: 输入是一个 tensor,函数将样本个数识别为8,然后对张量切片,每个样本的维度是(100)
dataset_tensor = tf.data.Dataset.from_tensor_slices(tf.random_uniform([8,100]))
print("dataset_tensor.output_shapes = ",dataset_tensor.output_shapes)

## 测试2: 输入是一个 numpy
dataset_numpy = tf.data.Dataset.from_tensor_slices(np.random.randn(8,100))
print("dataset_numpy.output_shapes = ",dataset_numpy.output_shapes)


## 测试3: 输入是一个 dict:当不同的value-tensor的第一个维度不同时,会报错,无法对各张量统一切片
dataset_dict = tf.data.Dataset.from_tensor_slices(
    {"a":tf.random_uniform([8,100]),
     "b":tf.random_uniform([8,1000])})
print("dataset_dict.output_shapes = ",dataset_dict.output_shapes)

## 测试4: 输入是一个 tuple:当不同的 tensor元素的第一个维度不同时,会报错,无法对各张量统一切片
dataset_tuple = tf.data.Dataset.from_tensor_slices(
    (tf.ones([8,10]),tf.zeros([8,100]),tf.random_uniform([8,15,100]))
)
print("dataset_tuple.output_shapes = ",dataset_tuple.output_shapes)

 

[Tensorflow2.0入坑指南]from_tensors和from_tensor_slices的区别 tf.data.Dataset.from_tensor_slices() 将输入的tensors中的每一个element按行进行划分,然后存入dataset import numpy import tensorflow as tf data = np.array([[1,2],[3,4]]) dataset = tf.data.Dataset.from_tensor_slices(data) # [1, 2], [3, 4] print(dataset) # <TensorSliceDataset s 阅读详情

相关推荐

tf.data.Dataset.from_tensor_slices详解

tf.data.Dataset.from_tensor_slices详解

qq_19069557的博客 1365

tf.data.Dataset.from_tensor_slices

数组转换成tensorflow的dataset,因为只有dataset才能被model.fit函数训练。进行切分,生成该tensor的切片数据集dataset。被在第0维切分成了5个不同tf.Tensor。对传入的tensor在第一个。ndarray类型的。将python列表和。...

Fwuyi的博客 3304

tensorflow2.x学习笔记十四:tf.data.Dataset.from_tensor_slices以及Dataset部分属性的使用方法

一、tf.data.Dataset.from_tensor_slices,它有三种用法,可以传入tensor、元组以及字典。下面就举几个例子: 直接传入tensor,有一点需要注意的是,它是按照传入的tensor的第0维进行划分以产生数据集 传入元组 传入字典 二、使用from_tensor_slices生成的dataset的一些属性方法,apply、as_numpy_iterator、...

耐心的小黑的博客 3746

tensorflow 加载数据集

tf.data.Dataset.from_tensor_slices: 使用tf.data.Dataset.from_tensor_slices五步加载数据集 import tensorflow as tf from tensorflow import keras def load_dataset(): # Step0 准备数据集, 可以是自己动手丰衣足食, 也可以从 tf.keras.datasets 加载需要的数据集(获取到的是numpy数据) # 这里以 mnist 为例 (x, y),

踩坑记录 1080

Isograph Reliability Workbench 14实战:从零构建故障树分析模型

本文以“马达不转”为例,手把手教你使用Isograph Reliability Workbench 14从零构建故障树分析模型。内容涵盖创建工程、定义顶事件、添加逻辑门与基础事件等核心步骤,并介绍了模型检查与定性定量分析,帮助你系统掌握这一强大的可靠性工程工具。

weixin_29309213的博客 363

机器学习——笔记整理(原理、python代码)——反反复复,出精活!

回顾知识,检查自我,开拓新域。 机器学习1.监督学习 机器学习简介: 机器学习是实现人工智能的手段,其主要研究内容是如何利用数据或经验进行学习,改善具体算法的性能。 多领域交叉,涉及概率论、统计学,算法复杂度理论等多门学科 广泛应用于网络搜索、垃圾邮件过滤、推荐系统、广告投放、信用评价、欺诈检测、股票交易和医疗诊断等应用。 机器学习分类: 机器学习一般分为下面几种类别 监督学习 ( Supervised Learning) 无监督学习 ( Unsupervised Learning) 强化学习(

weixin_45666566的博客 6487

tensorflow基础:tf.data.Dataset.from_tensor_slices() 与 tf.data.Dataset.from_generator()的异同

tf.data.Dataset.from_tensor_slices(tensor): -->将tensor沿其第一个维度切片,返回一个含有N个样本的数据集(假设tensor的第一个维度为N). -->得到的数据集是一个类对象,具有“迭代器”等函数,方便遍历数据集中的样本。 -->缺点:需要将整个数据集整体传入,然后切片建立数...

wzg2016的博客 8579

OpenWrt南京电信PPPoE IPv6配置:从零搭建稳定双栈网络

本文详细指导如何在南京电信PPPoE宽带环境下,为OpenWrt路由器配置稳定的IPv6双栈网络。核心在于正确设置WAN6接口为DHCPv6客户端,并请求/60前缀,同时配置LAN口分发地址并放行防火墙关键流量,确保内网设备获得原生IPv6连接。

water的专栏 1340

tf.data.Dataset.from_tensor_slices的用法

tf.data.Dataset.from_tensor_slices 该函数是dataset核心函数之一,它的作用是把给定的元组、列表和张量等数据进行特征切片。切片的范围是从最外层维度开始的。如果有多个特征进行组合,那么一次切片是把每个组合的最外维度的数据切开,分成一组一组的。 假设我们现在有两组数据,分别是特征和标签,为了简化说明问题,我们假设每两个特征对应一个标签。之后把特征和标签组合成一个...

Dr_jiabin的博客 5万+

别再瞎调参数了!分子动力学模拟新手必看的力场选择与验证实战指南

本文为分子动力学模拟新手提供力场选择与验证的实战指南,详细解析主流力场特性及适用场景,并通过水分子案例演示完整的验证流程。文章重点对比SPC/E、TIP3P和OPLS-AA三种力场在GROMACS中的表现,帮助读者避免常见参数调整误区,提升模拟准确性。

weixin_26934905的博客 426

HTPA 32x32d热成像传感器实战指南:从替代MLX90640到精准测温

本文为HTPA 32x32d热成像传感器提供了从硬件连接到精准测温的完整实战指南。针对MLX90640替代需求,详细解析了HTPA传感器的核心优势、IIC通信要点、EEPROM校准数据读取与解析、独特的块数据读取模式,并逐步拆解了五大温度补偿计算流程,旨在帮助开发者克服高开发门槛,实现稳定可靠的非接触式测温应用。

weixin_29279101的博客 314

tensorflow学习笔记:tf.data.Dataset,from_tensor_slices(),shuffle(),batch()的用法

tf.data.Dataset.from_tensor_slices: 它的作用是切分传入Tensor的第一个维度,生成相应的dataset。 例1: dataset = tf.data.Dataset.from_tensor_slices(np.random.uniform(size=(5, 2))) 传入的数值是一个矩阵,它的形状为(5, 2),tf.data.Dataset.from...

Rookiekk 1万+

【计算机组成原理】实验4:单周期CPU(Verilog)中海大

【计算机组成原理】实验4:单周期CPU

m0_63023532的博客 3660

使用tf.data.Dataset.from_tensor_slices五步加载数据集

tensorflow2 简单的数据加载5步法

rainweic的博客 3万+

Google antigravity 不支持你所在地区?手把手教你把账号改成支持地区

Google antigravity功能火爆,但国内老账号根本用不了🤬本文分享几种有效的账号国家地区切换方法,最快几分钟就能让antigravity直接亮起🔥

XiaoqiangClub的博客 2万+

Megatron-LM中的TP、PP、DP、SP、CP并行

SP主要优化的是激活内存,它沿序列维度切分部分激活,适用于较短序列并行。CP主要解决的是长序列的显存问题,它沿序列维度切分所有激活和输入,并且对注意力机制也进行并行处理。二者可以组合使用,特别是当 TP > 1 并且需要处理长序列时,通过启用 SP 和 CP 可以最大化地优化内存使用和加速计算。

u013250861的博客 861

tensorFlow2.1下的tf.data.Dataset.from_tensor_slices()和batch()的用法

1、tf.data.Dataset.from_tensor_slices 它的作用是切分传入Tensor的第一个维度,生成相应的dataset。 将输入的张量的第一个维度看做样本的个数,沿其第一个维度将tensor切片,得到的每个切片是一个样本数据。实现了输入张量的自动切片。 可以是numpy格式,也可以是tensorflow的tensor的格式,函数会自动将numpy格式转为tensorflo...

进击的Explorer 5136

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

tensorflow2中的tf.data.Dataset.from_tensor_slices()

tf.data.Dataset.from_tensor_slices()函数的参数是tensor。 该函数的作用是接收tensor,对tensor的第一维度进行切分,并返回一个表示该tensor的切片数据集 以minist训练集为例: x的shape为(60000,28,28),将x作为参数传递给tf.data.Dataset.from_tensor_slices(), 将返回一个含有60000个...

喜欢企鹅的博客 3489

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

tf.data.Dataset.from_tensor_slices()

函数原型: tf.data.Dataset.from_tensor_slices(tensors) 作用是切分传入tensor的第一个维度,生成相应的dataset 实例一 import tensorflow as tf import numpy as np x = np.random.uniform(size=(5, 2)) print(x) dataset = tf.data.Dataset.from_tensor_slices(x) for ele in dataset: print(ele)

胡图图的博客 3267

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

tf.data基础API使用(tf.data.Dataset.from_tensor_slices(),repeat,batch,interleave)

在这里主要绍tf.data基础API的使用。 1、tf.data.Dataset.from_tensor_slices: @staticmethod from_tensor_slices( tensors ) 创建一个数据集,其元素是给定张量的切片 请注意,如果张量包含NumPy数组,并且没有启用eager execution,则这些值将作为一个或多个tf.constant...

兰钧的博客 1139

【Python-Tensorflow】tf.data.Dataset的解析与使用

1 作用 dataset = tf.data.Dataset…() 构建和处理数据集。包括三种类型的操作。 根据输入数据创建源数据集。 应用数据集转换以预处理数据。 遍历数据集并处理元素。 2 tf.data.Dataset的函数 2.1 from_generator() 通过生成器去创建dataset,该函数的参数用于传生成器 # 定义生成器 def gen(): ragged_tensor = tf.ragged.constant([[1, 2], [3]]) yield 42, r

BetterBench的博客 1万+

Tensorflow2.0 tf.data.Dataset.from_tensor_slices 自定义图像数据集 (一)

Pytorch 标准二级目录名为类别的图像存储格式数据,采用Pytorch自带API db = torchvision.datasets.ImageFolder(root='dir', transform=preprocess) Tensorflow 标准二级目录名为类别的图像存储格式数据,采用Pytorch自带API db = torchvision.datasets.ImageFolder(...

Forrest97的博客 3186

tensorflow:tf.data.Dataset用法解析和模型实战

以一个特征和标签数据输入为例通过from_tensor_slices将python的元组,字段对象转化为DatasetV1Adapter对象,batch操作将数据拓展一维,make_one_shot_iterator将DatasetV1Adapter转化为tensorflow可迭代对象,通过get_next获取管道数据,输出是一个元组或者字典形式的tensorflow的Tensor。因为这个行业不同于其他行业,知识体系实在是过于庞大,知识更新也非常快。

2401_85327249的博客 958

Tensorflow2.0入门教程10:tf.data.Dataset使用介绍, my write

1: 准备要加载的数据(numpy,tensor2: 使用tf.data.Dataset.from_tensor_slices() 函数进行加载3: 使用shuffle()打乱数据4: 使用map()函数进行预处理5: 使用batch()函数设置 batch size 值6: 根据需要使用repeat()设置是否循环迭代数据集Keras 支持使用 tf.data.Dataset 直接作为输入。

小硕算法工程师 1224

TensorFlow:tf.data.Dataset.from_tensor_slices 函数笔记

这个函数就是将输入的张量,按第一维度切分成多个小的张量。代码如下: import tensorflow as tf b = tf.random.normal([3, 1, 2, 1]) bb = tf.data.Dataset.from_tensor_slices(b) print(bb) print('-----------------------') for i in bb: ...

wenkao123456的博客 806
上一篇: tensorflow 基础: static shape VS Dynamic shape, get_shape VS tf.shape() , reshape VS set_shape
下一篇: tensorflow基础:tf.data.Dataset.from_tensor_slices() 与 tf.data.Dataset.from_generator()的异同
wzg2016
博客等级 码龄10年 539粉丝 493原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值