使用 tensorflow,可以创建一个深度学习模型,该模型一旦经过训练就可以用于预测输入单词的类别。
假设这是数据集:
let data = [{description: 'just something', label: '1'}, {description: 'something else', label: '2'}]
在文本分类中首先要做的就是将文本编码为张量。可以使用许多算法,前提是它们在给定感兴趣的领域时能带来良好的准确性。特别是,universal-sentence encoder 会将每个句子转换为大小为 512 的一维张量。
const useModel = await use.load()
let features = data.map(d => useModel.embed(d.description))
features = tf.stack(features) // create a 2d tensor from the array of 1d tensor
let labels = tf.oneHot([0, 1], 2) // encode it as oneHot
// more details on labels encoding in this answer
// https://stackoverflow.com/questions/59127861/how-may-i-define-my-own-labels-in-tensorflow-js/59128300#59128300
第二件事是为分类创建一个模型。虽然可以使用 FCNN,但对于 NLP 处理,主要使用 LSTM 或双向 LSTM,因为在将输出转发到其他层时,单元格会考虑数据的上下文。这是此类模型的示例
const model = tf.sequential({
layers: [
tf.layers.lstm({ inputShape: [1, 512], units: 16, activation: "relu", returnSequences: true }),
tf.layers.lstm({ units: 16, activation: "relu", returnSequences: true }),
tf.layers.lstm({ units: 16, activation: "relu", returnSequences: false }),
tf.layers.dense({ units: numberOfCategories, activation: "softmax" }),
]
}) // in this example of the numberOfCategories is 2
[n, 512] 的 inputShape 用于指示模型将一次输入n 句子。如果句子数量可变,则 inputShape 将为[null, 512]。
模型将被训练
model.compile({
optimizer: "adam",
loss: "categoricalCrossentropy",
metrics: ["accuracy"]
})
model.fit(features, labels, {
epochs: number,// as needed to have a good accuracy
callbacks: {
onBatchEnd(batch, logs) {
console.log(logs.acc)
}
}
})
模型训练完成后,对于每个传入的单词,都会有一个预测。但传入的单词需要首先转换为上述张量 a。
let prediction = model.predict( await useModel.embed('newWord').reshape([1, 1, -1])).argMax([-1])
prediction.print() // will print the index of the label
如果训练数据还没有被标记(意味着对象没有标签属性),数据应该被聚类。 tensorflow.js 中还没有聚类算法。
对于文本聚类,我们首先需要创建标记。 use 包有分词器;还有包natural。标记化后,node-kmeans 可用于标记数据集。从这一步开始,可以使用第一种方法。
另一种方法可能是使用标记化的句子来训练模型。但是由于所有句子的形状都不相同,因此需要使用tf.pad添加填充