表 2-2. 张量基本数值类型
类型 | 变量 | 描述 |
---|---|---|
int | kInt8,kInt16,kInt32,kInt64 缩写(kI8,kI16,kI32,kI64) | 整数 |
uint | kUInt8 缩写(kU8) | 无符号整数 |
float | kFloat16,kFloat32,kFloat64 缩写(kF16,kF32,kF64) | 浮点数 |
bool | kBool | 布尔类型 |
例2-2:张量基本数值类型
#include <torch/torch.h>
#include <torch/script.h>
#include <opencv2/opencv.hpp>
int main() {
auto a = torch::tensor({ {1,2,3},{-4,-5,-6} }, torch::kI8);
auto b = torch::tensor({ {1,2,3},{4,5,6} }, torch::kU8);
auto c = torch::tensor({ 1.2,1.3,20.159 }, torch::kF32); //kF32是kFloat32缩写
auto d = torch::tensor({ 0,1,2 }, torch::kBool);
std::cout << "a:\n" << a << std::endl;
std::cout << "b:\n" << b << std::endl;
std::cout << "c:\n" << c << std::endl;
std::cout << "d:\n" << d << std::endl;
return 0;
}
结果:
a:
1 2 3
-4 -5 -6
[ CPUCharType{2,3} ]
b:
1 2 3
4 5 6
[ CPUByteType{2,3} ]
c:
1.2000
1.3000
20.1590
[ CPUFloatType{3} ]
d:
0
1
1
[ CPUBoolType{3} ]
例2-3:kU8的取值范围
#include <torch/torch.h>
int main() {
auto a = torch::tensor({ {1,2,3},{254,255,0} }, torch::kU8);
auto b = torch::tensor({ {-255,-254,-253},{-2,-1,0} }, torch::kU8);
std::cout << "a:\n" << a << std::endl;
std::cout << "b:\n" << b << std::endl;
return 0;
结果:
a:
1 2 3
254 255 0
[ CPUByteType{2,3} ]
b:
1 2 3
254 255 0
[ CPUByteType{2,3} ]
注意:kU8取值超出-255到255的范围会报错,其中-1表示255。