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;
}
随机推荐
- Qt Creator 不能输入中文怎么解决?
Qt Creator 2.7.2不能输入中文怎么解决?之前提的问题自己后来找到解决方法后就忘了, 方法很简单,只要设置一下环境变量就行了export QT_IM_MODULE=ibus qt5.4.r ...
- 10java进阶——IO2
1. Properties类 Properties 类表示了一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串. 特点: Hashtable的子 ...
- Python not and or
刷题时候,有道题目的答案是 return(num and (num % 9 or 9)) 看的有点懵逼,看来解释如下: 1.首先,’and’.’or’.’not’的优先级是not>and> ...
- 使用GDB调试时attach ID不被允许
在进入gdb后,直接使用attach ID,出现下面的情况: Could not attach to process. If your uid matches the uid of the targ ...
- git 使用远程分支覆盖本地分支(重置本地分支)
1 丢弃本地变更 重置为远端分支内容 git reset --hard origin/branchName 如 git reset --hard origin/F_AssetItem
- shell 数组中 @ 跟 * 的区别
关于在shell脚本中数组变量中 “*”跟 “@” 区别 “*”当变量加上“” 会当成一串字符串处理. “@”变量加上“” 依然当做数组处理. 在没有加上“” 的情况下 效果是等效的. #!/bin/ ...
- vue 自定义封装组件 使用 model 选项
自定义组件的 v-model 一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框.复选框等类型的输入控件可能会将 value 特性用于不同 ...
- 微服务+DDD代码结构例子
这是一个基本的微服务+DDD演示例子: 基于 Spring Boot 1.5.6 , Spring Cloud Edgware.SR4 Version 微服务 + DDD,个人觉得应该是首先是从微服务 ...
- WiFi密码新攻击破解方法,黑客攻破只需10秒
近日,中国知名黑客安全组织东方联盟研究人员透露了一种新的WiFi黑客技术,使黑客更容易破解大多数现代路由器的WiFi密码,并且攻破只需要10秒,速度非常快. 方法是利用由流行的密码破解工具Hashca ...
- Linux下统计当前文件夹下的文件个数
Linux下统计当前文件夹下的文件个数 √ ls -l |grep "^-"|wc -l