【深度学习21天学习挑战赛】备忘篇: from_tensor_slices的作用和用法

​ 活动地址:CSDN21天学习挑战赛

我们在转化数据集时经常会使用这个函数,他的所用是切分传入的 Tensor 的第一个维度,生成相应的 dataset

为什么要转换?
将python的listnumpy数组转换成tensorflowdataset ,才能被model.fit函数训练

场景1:转换

import tensorflow as tf
import numpy as np
x = np.random.uniform(size=(5, 3))
print(x)
print(type(x))
dataset = tf.data.Dataset.from_tensor_slices(x)
print(type(dataset))
for i in dataset:
	print(i)

在这里插入图片描述
在这里插入图片描述
可以看到ndarray 类型的x被在第0维切分成了5个不同tensor也就是5个相应的 dataset

如果传入的不是ndarray,而是list也是一样的
在这里插入图片描述

场景2:组合组队

import tensorflow as tf
import numpy as np
x = np.random.uniform(size=(5, 2))
print(x)
y = [1,2,3,4,5]
print(y)
dataset = tf.data.Dataset.from_tensor_slices((x, y))
for i in dataset:
	print(i)

在这里插入图片描述
可以看到:
x和y均在第0维被切分成了5个tensor,并且相应位置的元素在dataset中组成了一组

这一点很重要,这样就可以实现特征 + 标签dataset

场景3:字典转换

dict_data = dict([('a', [11,22]), ('b', [33, 44]), ('c', [55, 66])])
print(dict_data)
dataset = tf.data.Dataset.from_tensor_slices(dict_data)
for i in dataset:
	print(i)

运行结果:

{'a': [11, 22], 'b': [33, 44], 'c': [55, 66]}
{'a': <tf.Tensor: shape=(), dtype=int32, numpy=11>, 'b': <tf.Tensor: shape=(), dtype=int32, numpy=33>, 'c': <tf.Tensor: shape=(), dtype=int32, numpy=55>}
{'a': <tf.Tensor: shape=(), dtype=int32, numpy=22>, 'b': <tf.Tensor: shape=(), dtype=int32, numpy=44>, 'c': <tf.Tensor: shape=(), dtype=int32, numpy=66>}

由此可知,from_tensor_slices的大概使用方法,和支持的传入数据类型(元组)。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

藏蓝色攻城狮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值