首页 > 解决方案 > 如何在张量中使用字符串类别作为特征?(如果可能在 tensorflow js 中)

问题描述

我在数据集中有以下类别,其中 Region 和 Years 将用于预测 Salary

Regions: ['Europe', 'North America', 'South America', 'Asia', 'Africa'] 

Data sample:
{region: 'Asia', years: 5, salary: 1000}
{region: 'Asia', years: 3, salary: 700}
{region: 'Asia', years: 1, salary: 300}
{region: 'Europe', years: 5, salary: 3000}

我想使用地区和年份作为 Xs,薪水作为 Ys。

我尝试将区域转换为 tf.oneHot,但无法弄清楚如何将它们与“年”一起使用,因为 oneHot 返回是另一个张量。

indices = tf.tensor1d([0, 1, 2, 3, 4], 'int32');
oneHot = tf.oneHot(indices, 5);
oneHot result -> [[1, 0, 0, 0, 0],...]


xs = tf.tensor2d([[?, 5], [?, 3], [?, 1], [?, 5]]); //[region, years]
ys = tf.tensor1d([1000, 700, 300, 3000]); //[salary]

标签: tensorflowtensorflow.js

解决方案


tf.concat可以使用

indices = tf.tensor1d([0, 1, 2, 3, 4], 'int32');
const oneHot = tf.oneHot(indices, 5);

const xs_add = tf.tensor([5, 3, 1, 5, 4]).reshape([5, 1])

xs = tf.concat([oneHot, xs_add], 1)
xs.print()

推荐阅读