What is one-hot?
SEO:
libtorch 如何 OneHot ?
torch OneHot 源代码 ?
https://www.tensorflow.org/api_docs/python/tf/one_hot
最新的 1.3 版本中已经添加了该函数
#include <torch/torch.h>
#include <c10/util/StringUtil.h>
torch::Tensor one_hot(const torch::Tensor &self, int64_t num_classes) {
AT_CHECK(self.dtype() == torch::kLong, "one_hot is only applicable to index tensor.");
auto shape = self.sizes().vec();
// empty tensor could be converted to one hot representation,
// but shape inference is not possible.
if (self.numel() == 0) {
if (num_classes <= 0) {
AT_ERROR("Can not infer total number of classes from empty tensor.");
}
else {
shape.push_back(num_classes);
return at::empty(shape, self.options());
}
}
// non-empty tensor
AT_CHECK(self.min().item().toLong() >= 0, "Class values must be non-negative.");
if (num_classes == -1) {
num_classes = self.max().item().toLong() + 1;
}
else {
AT_CHECK(num_classes > self.max().item().toLong(), "Class values must be smaller than num_classes.");
}
shape.push_back(num_classes);
torch::Tensor ret = at::zeros(shape, self.options());
ret.scatter_(-1, self.unsqueeze(-1), 1);
return ret;
}
使用示例
torch::TensorOptions options(torch::kLong);
auto tensor = torch::tensor({ 0,1,2 }, options);
std::cout << tensor << std::endl;
try
{
auto one_hot = torch::one_hot(tensor,4);
std::cout << one_hot << std::endl;
}
catch (const c10::Error& watch)
{
std::cout << watch.msg() << std::endl;
}
随机推荐
- c++ sizeof的实现
c++中的sizeof,可以通过以下宏定义实现. #include <stdio.h> #define sizeof_T(T) ((size_t)((T*)0+1)) ///求类型的大小 ...
- Tree命令安装和使用
Tree命令简介 tree是一种递归目录列表命令,产生一个深度缩进列表文件,这是彩色的ALA dircolors如果ls_colors设置环境变量和输出是TTY.树已经被移植和报道以下操作系统下工作: ...
- linux命令中chmod 777 以及drwxr-xr-x分别代表什么意思
最近跟一个运维人员学了点新东西,感觉以前没怎么注意,但现在感觉很有用,特来记录一下. linux使用==ll==命令列出列表的时候,前面总是有一堆drwxr-xr-x ,这些代表什么意思从来还没有去在 ...
- [sql 注入] 注入类型
基于整型的注入: url:http://localhost/?id=12 拼接sql:$sql = "select * from user where id = {$_GET['id']}& ...
- gulp自动化构建工具使用总结
简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快的编写代码 ...
- 美国知名Cloudflare网络公司遭中国顶尖黑客攻击
最近中美贸易战愈演愈烈,美国知名Cloudflare网络公司的客户的分布式拒绝服务攻击今天在恶意流量方面达到了新的高度,黑客并袭击了该公司在欧洲和美国的数据中心.根据Cloudflare首席执行官马修 ...
- java基础复习(四)
---恢复内容开始--- 一.for循环的掌握 语法格式: for( 初始化语句A ; 条件判断B ; 循环后功能语句C){ //循环体D } for的执行流程: 整个for循环结构中 ...
- Java 13 在win10 安装及配置
java 13 SDK 下载 下载地址:https://www.oracle.com/technetwork/java/javase/downloads/jdk13-downloads-5672538 ...
- Sentinel 1.7.0 发布,支持 Envoy 集群流量控制
流控降级中间件Sentinel 1.7.0版本正式发布,引入了 Envoy 集群流量控制支持.properties 文件配置.Consul/Etcd/Spring Cloud Config 动态数据源 ...
- CSS入门基础学习二
我们下午继续学习CSS的入门基础,搬上你的小板凳赶快进入吧! 一.背景(background) Background-color:背景颜色 background-image (背景图片) backgr ...