python - 字符串到 Tensorflow 中的 one_hot 张量
问题描述
我在 tensorflow doc 中找到了以下函数来计算词汇表并将其应用于字符串张量,但它仍在使用tf.session
,我无法使其工作tf.function
:
import tensorflow as tf
import tensorflow_transform as tft
@tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.string),))
def string_to_one_hot(labels):
codes = tft.compute_and_apply_vocabulary(labels)
return tf.one_hot(codes, depth=tf.cast(tf.reduce_max(codes), tf.int32))
test_labels = tf.constant(['a', 'b', 'a', 'c'])
test_one_hot = string_to_one_hot(test_labels)
> tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'compute_and_apply_vocabulary/vocabulary/Placeholder' with dtype string
[[node compute_and_apply_vocabulary/vocabulary/Placeholder (defined at /Users/clementwalter/.pyenv/versions/keras_fsl/lib/python3.6/site-packages/tensorflow_transform/analyzer_nodes.py:102) ]] [Op:__inference_string_to_one_hot_52]
编辑
我已经能够通过直接使用哈希工具来构建这样的功能。但是我不得不使用硬编码的 bucket_size/depth 参数。有任何想法吗?
@tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.string),))
def string_to_one_hot(labels):
one_hot = tf.one_hot(tf.strings.to_hash_bucket_fast(labels, 1024), depth=1024)
return tf.boolean_mask(one_hot, tf.reduce_sum(one_hot, axis=0) > 0, axis=1)
解决方案
好的,我想我找到了正确的答案:
def string_to_one_hot(labels):
colnames, codes = tf.unique(support_labels_name)
return colnames, tf.one_hot(codes, depth=tf.size(colnames))
推荐阅读
- php - 使用 Mikrotik API 更改 Mikrotik 中 PPP 秘密的配置文件
- macos - 强制 NSTabView 在 MacOS 上加载选项卡的新实例
- webpack - Vue延迟加载不起作用
- templates - 如何使用未来的解析器在人偶模板中包含子模板
- bash - 在bash中获取后台进程的退出状态
- python - pip 存在,表示没有名为 pip 的模块
- android - 更改 AOSP 并在移动设备上刷入
- angular - 输入字段更改时更改单选按钮的值
- javascript - 启用“use strict”后,为什么我可以在使用 prompt() 时不让 let 分配变量
- javascript - pre html - M-BM- bash 脚本在网络上突出显示语法 - 删除字节序列 0xc2 0xa0 的 ASCII 表示