发布于 2026-01-06 1 阅读
0

使用 React 检测文本毒性

使用 React 检测文本毒性

我在之前的文章中解释了如何开始使用 TensorFlow.js,从创建简单的线性回归模型到使用预训练模型(例如 PoseNet)。我强烈建议您阅读这篇文章,以了解它的工作原理。

在今天的文章中,我想向您展示,即使没有任何机器学习方面的知识,使用文本毒性检测模型也是多么容易。

什么是文本毒性检测?

毒性检测功能可以检测包含有害内容的文本,例如威胁性语言、侮辱性语言、淫秽语言、基于身份的仇恨言论或露骨的性语言。

文本毒性示例

图 1:文本透明度示例

在浏览器中安装此功能后,可以更容易地阻止不必要的评论/意见,并加快这些内容的审核过程。

不过,这看起来好复杂……别担心,好消息!你不需要成为机器学习专家也能使用这个模型。让我们来看看怎么做。

钩子

我编写了一个 React Hook 来简化它的使用方式,这样您只需一行代码即可使用该 Hook 获取文本预测结果:

import useTextToxicity from 'react-text-toxicity'

// Usage inside your component or custom hook
const predictions = useTextToxicity('This is an example')
/*
  {
    "label": "identity_attack",
    "match": false,
    "probability": "3.40%",
    "probabilities": [0.9659664034843445, 0.03403361141681671],
  },
  {
    "label": "insult",
    "match": true,
    "probability": "91.8%",
    "probabilities": [0.08124706149101257, 0.9187529683113098],
  },
  ...
*/
Enter fullscreen mode Exit fullscreen mode

我已经上传了 npm 包,您可以通过以下方式使用它:

yarn add react-text-toxicity
Enter fullscreen mode Exit fullscreen mode

GitHub 代码库 👉 https://github.com/aralroca/react-text-toxicity

我们可以通过以下方式将useTextToxicity挂钩连接到:state

const [value, setValue] = useState("");
const predictions = useTextToxicity(value);

//...
<textarea
  value={value}
  onChange={(e) => setValue(e.target.value)}
/>
Enter fullscreen mode Exit fullscreen mode

这样,每次数值发生变化时,预测结果都会更新(我们可以“即时”预测)。

以下是图 1的完整示例代码

import React, { Fragment, useState } from "react";
import useTextToxicity from "react-text-toxicity";

function Toxicity({ predictions }) {
  const style = { margin: 10 };

  if (!predictions) return <div style={style}>Loading predictions...</div>;

  return (
    <div style={style}>
      {predictions.map(({ label, match, probability }) => (
        <div style={{ margin: 5 }} key={label}>
          {`${label} - ${probability} - ${match ? "🤢" : "🥰"}`}
        </div>
      ))}
    </div>
  );
}

export default function Index() {
  const [value, setValue] = useState("");

  // predictions are updated every time the value is updated
  const predictions = useTextToxicity(value);

  return (
    <div style={{ display: "flex" }}>
      <div>
        <div>Write something</div>
        <textarea
          style={{ width: 300, height: 200 }}
          value={value}
          onChange={(e) => setValue(e.target.value)}
        />
      </div>
      {value && <Toxicity predictions={predictions} />}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

在“钩子”下

其底层使用了Tensorflow.js毒性模型:

如果您需要在 React 之外实现相同的功能,可以使用这个仓库。

结论

有时我们一听到机器学习和/或TensorFlow,就会觉得难以理解,觉得太复杂了。然而,其实有很多预训练模型可以轻松使用。

使用 React hooks 可以简化操作,只需一行简单的代码即可利用预训练模型进行数据预测。

现在,我鼓励大家尝试使用这些 TensorFlow 模型,或者开始在你们的项目中使用它们!

文章来源:https://dev.to/aralroca/detect-text-toothity-using-react-2d46