【人工智能】利用TensorFlow.js在浏览器中实现一个基本的情感分析系统

简介: 使用TensorFlow.js在浏览器中进行情感分析是一个非常实用的应用场景。TensorFlow.js 是一个用于在JavaScript环境中训练和部署机器学习模型的库,使得开发者能够在客户端直接运行复杂的机器学习任务。对于情感分析,我们可以使用预先训练好的模型来识别文本中的积极、消极或中性情感。

使用TensorFlow.js在浏览器中进行情感分析是一个非常实用的应用场景。TensorFlow.js 是一个用于在JavaScript环境中训练和部署机器学习模型的库,使得开发者能够在客户端直接运行复杂的机器学习任务。对于情感分析,我们可以使用预先训练好的模型来识别文本中的积极、消极或中性情感。

下面我会给你一个简化的项目计划,包括原理和方法、技术栈的选择、模型的设计,以及一个简单的示例代码,来演示如何使用TensorFlow.js实现一个基本的情感分析器。

一、项目原理和方法

1.情感分析原理

  • 特征提取:将文本转换成数值特征,常见的方法有词袋模型、TF-IDF 和词嵌入(如Word2Vec、GloVe)。
  • 模型训练:使用监督学习算法,如逻辑回归、支持向量机、递归神经网络 (RNN) 或者长短期记忆网络 (LSTM) 来分类文本情感。
  • 模型部署:将训练好的模型部署到生产环境,在本例中是在浏览器中使用TensorFlow.js。

2.使用的方法

  • 预训练模型:可以使用预训练的模型,例如使用BERT或其他Transformer模型进行情感分类。
  • 自定义模型:也可以从头开始训练一个简单的模型,例如使用LSTM进行文本分类。

二、技术栈

  • 前端:HTML, CSS, JavaScript
  • 后端(可选):Node.js + Express
  • 机器学习库:TensorFlow.js
  • 模型训练:TensorFlow.js 或 TensorFlow (Python) 进行模型训练,然后转换为TensorFlow.js格式

三、架构设计

  • 模型训练:在服务器端或本地训练一个简单的情感分析模型。
  • 模型部署:将模型导出为TensorFlow.js格式,并通过HTTP服务提供给客户端。
  • 前端应用:用户输入文本,前端调用TensorFlow.js API进行预测,并显示结果。

四、示例代码

在这个示例中,我们将使用一个简单的LSTM模型来进行情感分析。首先,我们需要创建一个简单的模型并在服务器端训练它,然后将其转换为TensorFlow.js格式,并部署到一个简单的前端应用中。

4.1 训练模型 (Python)

首先,我们需要在Python环境中训练一个模型。这里我们假设已经有一个预处理过的数据集 sentiment_data.csv,其中包含两列:textlabel(0表示负面,1表示正面)。

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import pandas as pd
# 加载数据
data = pd.read_csv('sentiment_data.csv')
texts = data['text'].values
labels = data['label'].values
# 分词器
tokenizer = Tokenizer(num_words=10000, oov_token="<OOV>")
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
# 序列填充
padded_sequences = pad_sequences(sequences, padding='post', maxlen=128)
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(padded_sequences, labels, test_size=0.2)
# 定义模型
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(10000, 16, input_length=128),
    tf.keras.layers.LSTM(64, return_sequences=True),
    tf.keras.layers.LSTM(32),
    tf.keras.layers.Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test), verbose=2)
# 导出模型
model.save('sentiment_model.h5')

image.gif

4.2 转换模型到TensorFlow.js

使用TensorFlow.js Converter将模型转换为TensorFlow.js格式。

tensorflowjs_converter --input_format keras sentiment_model.h5 models/sentiment_model

image.gif

4.3 前端应用

创建一个简单的HTML文件,使用TensorFlow.js进行预测。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sentiment Analysis with TensorFlow.js</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c6d4d8c1f2819c8b9c82">[email protected]/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5a4146594a5d5c4e43025c4a415b4a414c4a024a414c404b4a5d6f1b011e011f">[email protected]/dist/index.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; }
    #output { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>Sentiment Analysis Demo</h1>
  <textarea id="inputText" rows="4" cols="50">Enter text here...</textarea>
  <button onclick="analyzeSentiment()">Analyze Sentiment</button>
  <div id="output"></div>
  <script>
    // Load the model
    const modelUrl = 'models/sentiment_model/model.json';
    let model;
    async function loadModel() {
      model = await tf.loadLayersModel(modelUrl);
    }
    // Analyze the sentiment of the input text
    async function analyzeSentiment() {
      const inputText = document.getElementById('inputText').value;
      const encodedText = await universalSentenceEncoder.embed(inputText);
      const prediction = model.predict(encodedText.expandDims());
      const sentiment = prediction.dataSync()[0];
      
      const outputDiv = document.getElementById('output');
      outputDiv.innerHTML = `Sentiment Score: ${sentiment.toFixed(2)}<br />`;
      if (sentiment > 0.5) {
        outputDiv.innerHTML += "The sentiment is positive.";
      } else {
        outputDiv.innerHTML += "The sentiment is negative.";
      }
    }
    // Load the model when the page loads
    window.onload = loadModel;
  </script>
</body>
</html>

image.gif

4.4 注意事项

  • 在这个示例中,我们使用了Universal Sentence Encoder来将文本编码为向量,这简化了模型的复杂度。但在实际应用中,你可能需要使用相同的分词器和序列填充策略来确保输入的一致性。
  • 如果你的模型使用了不同的预处理步骤,你需要确保前端能够正确地复制这些步骤。
  • 这个示例假设你已经有了一定规模的标注数据集。在实际应用中,你可能需要收集和标记更多的数据。

五、完善项目

上面我们已经完成了情感分析的基本框架,接下来我们可以进一步完善这个项目,使其更加完整和实用。这包括以下几个方面:

  1. 增强前端界面:添加更多的交互元素和样式,提升用户体验。
  2. 优化模型:考虑使用更先进的模型,比如BERT,以及对模型进行微调以提高准确性。
  3. 集成API:为模型提供一个RESTful API接口,方便其他应用程序调用。
  4. 部署到服务器:将前端和后端部署到云服务器上,使其对外界可用。

1. 增强前端界面

让我们先来改进前端界面,增加一些交互元素,比如按钮、进度条和结果展示区等,以提升用户体验。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sentiment Analysis with TensorFlow.js</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f286949881b2c1dccbdcc2">[email protected]/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a1babda2b1a6a7b5b8f9a7b1baa0b1bab7b1f9b1bab7bbb0b1a694e0fae5fae4">[email protected]/dist/index.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; }
    #inputText { width: 100%; height: 150px; }
    #output { margin-top: 20px; }
    #progressBar { display: none; width: 100%; height: 20px; background-color: #ddd; }
    #progressBar .progress-bar { height: 100%; background-color: #4caf50; }
  </style>
</head>
<body>
  <h1>Sentiment Analysis Demo</h1>
  <textarea id="inputText" placeholder="Enter text here..."></textarea>
  <button onclick="analyzeSentiment()">Analyze Sentiment</button>
  <div id="progressBar">
    <div class="progress-bar"></div>
  </div>
  <div id="output"></div>
  <script>
    // Load the model
    const modelUrl = 'models/sentiment_model/model.json';
    let model;
    async function loadModel() {
      model = await tf.loadLayersModel(modelUrl);
    }
    // Analyze the sentiment of the input text
    async function analyzeSentiment() {
      const inputText = document.getElementById('inputText').value.trim();
      if (!inputText) {
        alert("Please enter some text to analyze.");
        return;
      }
      showProgressBar();
      const encodedText = await universalSentenceEncoder.embed(inputText);
      const prediction = model.predict(encodedText.expandDims());
      const sentiment = prediction.dataSync()[0];
      hideProgressBar();
      const outputDiv = document.getElementById('output');
      outputDiv.innerHTML = `Sentiment Score: ${sentiment.toFixed(2)}<br />`;
      if (sentiment > 0.5) {
        outputDiv.innerHTML += "The sentiment is positive.";
      } else {
        outputDiv.innerHTML += "The sentiment is negative.";
      }
    }
    function showProgressBar() {
      const progressBar = document.getElementById('progressBar');
      const progress = progressBar.querySelector('.progress-bar');
      progressBar.style.display = 'block';
      progress.style.width = '0%';
      const intervalId = setInterval(() => {
        let width = parseFloat(progress.style.width);
        if (width >= 100) {
          clearInterval(intervalId);
          progress.style.width = '100%';
          setTimeout(() => {
            hideProgressBar();
          }, 500);
        } else {
          progress.style.width = `${width + 10}%`;
        }
      }, 50);
    }
    function hideProgressBar() {
      const progressBar = document.getElementById('progressBar');
      progressBar.style.display = 'none';
    }
    // Load the model when the page loads
    window.onload = loadModel;
  </script>
</body>
</html>

image.gif

2. 优化模型

我们可以考虑使用更先进的模型,比如BERT。BERT是一个基于Transformer的预训练模型,它在多种自然语言处理任务上取得了非常好的效果。这里我们使用TensorFlow.js的@tensorflow-models/bert库来加载一个预训练的BERT模型,并进行微调。

2.1 更新模型训练代码 (Python)

由于BERT模型的训练较为复杂,我们在这里只提供一个概览。你可以在Python环境中训练一个基于BERT的模型,并将其转换为TensorFlow.js格式。

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_text as text
from official.nlp import optimization  # to create AdamW optimizer
import tensorflow_datasets as tfds
import os
# Load BERT model and tokenizer
bert_preprocess_model = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")
bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4")
# Define model architecture
def create_model():
    text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text')
    preprocessing_layer = hub.KerasLayer(bert_preprocess_model, name='preprocessing')
    encoder_inputs = preprocessing_layer(text_input)
    encoder = hub.KerasLayer(bert_encoder, trainable=True, name='BERT_encoder')
    outputs = encoder(encoder_inputs)
    net = outputs['pooled_output']
    net = tf.keras.layers.Dropout(0.1)(net)
    net = tf.keras.layers.Dense(1, activation=None, name='classifier')(net)
    return tf.keras.Model(text_input, net)
# Compile the model
model = create_model()
loss = tf.keras.losses.BinaryCrossentropy(from_logits=True)
metrics = tf.metrics.BinaryAccuracy()
epochs = 5
steps_per_epoch = tf.data.experimental.cardinality(list(train_data)).numpy()
num_train_steps = steps_per_epoch * epochs
num_warmup_steps = int(0.1*num_train_steps)
optimizer = optimization.create_optimizer(init_lr=3e-5,
                                          num_train_steps=num_train_steps,
                                          num_warmup_steps=num_warmup_steps,
                                          optimizer_type='adamw')
model.compile(optimizer=optimizer,
              loss=loss,
              metrics=metrics)
# Train the model
model.fit(x=train_data,
          y=train_labels,
          validation_data=(val_data, val_labels),
          epochs=epochs)
# Save the model
model.save('sentiment_bert_model.h5')

image.gif

2.2 转换模型到TensorFlow.js

使用TensorFlow.js Converter将模型转换为TensorFlow.js格式。

tensorflowjs_converter --input_format keras sentiment_bert_model.h5 models/sentiment_bert_model

image.gif

2.3 更新前端应用

更新前端应用以使用BERT模型进行预测。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sentiment Analysis with TensorFlow.js (BERT)</title>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4c0d2dec7f4879a8d9a84">[email protected]/dist/tf.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/%3Ca%20href="https://developer.aliyun.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfdddacdcbff8e918f918f">[email protected]/dist/index.min.js"></script>
  <style>
    /* ... existing styles ... */
  </style>
</head>
<body>
  <!-- ... existing HTML elements ... -->
  <script>
    // Load the model
    const modelUrl = 'models/sentiment_bert_model/model.json';
    let model;
    async function loadModel() {
      model = await tf.loadLayersModel(modelUrl);
    }
    // Analyze the sentiment of the input text
    async function analyzeSentiment() {
      const inputText = document.getElementById('inputText').value.trim();
      if (!inputText) {
        alert("Please enter some text to analyze.");
        return;
      }
      showProgressBar();
      // Use BERT to encode the input text
      const encoder = new BertEncoder('uncased_L-12_H-768_A-12');
      const encodedText = await encoder.encode(inputText);
      const prediction = model.predict(encodedText);
      const sentiment = prediction.dataSync()[0];
      hideProgressBar();
      const outputDiv = document.getElementById('output');
      outputDiv.innerHTML = `Sentiment Score: ${sentiment.toFixed(2)}<br />`;
      if (sentiment > 0.5) {
        outputDiv.innerHTML += "The sentiment is positive.";
      } else {
        outputDiv.innerHTML += "The sentiment is negative.";
      }
    }
    // ... existing functions ...
    // Load the model when the page loads
    window.onload = loadModel;
  </script>
</body>
</html>

image.gif

3. 集成API

为了让其他应用程序能够调用情感分析模型,我们可以创建一个RESTful API。

3.1 创建API (Node.js + Express)

const express = require('express');
const bodyParser = require('body-parser');
const tf = require('@tensorflow/tfjs-node');
const { BertEncoder } = require('@tensorflow-models/bert');
const app = express();
app.use(bodyParser.json());
// Load the model
let model;
async function loadModel() {
  model = await tf.loadLayersModel('file://./models/sentiment_bert_model/model.json');
}
loadModel().then(() => {
  console.log('Model loaded successfully.');
});
// Analyze sentiment endpoint
app.post('/analyze', async (req, res) => {
  const { text } = req.body;
  if (!text) {
    return res.status(400).send({ error: 'Missing text' });
  }
  const encoder = new BertEncoder('uncased_L-12_H-768_A-12');
  const encodedText = await encoder.encode(text);
  const prediction = model.predict(encodedText);
  const sentiment = prediction.dataSync()[0];
  res.json({ sentimentScore: sentiment, isPositive: sentiment > 0.5 });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

image.gif

4. 部署到服务器

你可以将前端和后端分别部署到云服务器上,例如使用Heroku或AWS。这里就不详细展开部署过程了,但你可以参考各个云服务商的文档来进行部署。

通过这些步骤,你将能够构建一个功能完整的情感分析应用,其中包括了用户友好的前端界面、先进的BERT模型以及一个可被其他应用程序调用的API。希望这个项目对你有所帮助!如果有任何疑问或需要进一步的帮助,请随时告诉我。

目录
相关文章
|
3月前
|
机器学习/深度学习 人工智能 测试技术
EdgeMark:嵌入式人工智能工具的自动化与基准测试系统——论文阅读
EdgeMark是一个面向嵌入式AI的自动化部署与基准测试系统,支持TensorFlow Lite Micro、Edge Impulse等主流工具,通过模块化架构实现模型生成、优化、转换与部署全流程自动化,并提供跨平台性能对比,助力开发者在资源受限设备上高效选择与部署AI模型。
417 9
EdgeMark:嵌入式人工智能工具的自动化与基准测试系统——论文阅读
|
6月前
|
JavaScript Linux 内存技术
Debian 11系统下Node.js版本更新方法详解
本指南详细介绍在Linux系统中安装和管理Node.js的步骤。首先检查现有环境,包括查看当前版本和清除旧版本;接着通过NodeSource仓库安装最新版Node.js并验证安装结果。推荐使用nvm(Node Version Manager)进行多版本管理,便于切换和设置默认版本。同时,提供常见问题解决方法,如权限错误处理和全局模块迁移方案,以及版本回滚操作,确保用户能够灵活应对不同需求。
589 0
|
2月前
|
人工智能 IDE 开发工具
拔俗人工智能辅助评审系统:如何用技术为“把关”提效
人工智能辅助评审系统融合大模型、提示工程与业务流程,实现上下文深度理解、场景化精准引导与无缝集成。通过自动化基础审查,释放专家精力聚焦核心决策,提升评审效率与质量,构建人机协同新范式。(239字)
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
拔俗AI人工智能评审管理系统:用技术为决策装上“智能导航”
AI评审系统融合NLP、知识图谱与机器学习,破解传统评审效率低、标准不一难题。通过语义解析、智能推理与风险预判,构建标准化、可复用的智能评审流程,助力项目质量与效率双提升。(238字)
|
6月前
|
JavaScript Linux 内存技术
Debian 11系统下Node.js版本更新方法
Debian 11更新Node.js主要就是这三种方式,无论你是初涉其中的新手还是找寻挑战的专家,总有一种方式能满足你的需求。现在,你已经是这个
708 80
|
8月前
|
人工智能 自然语言处理 API
MCP与A2A协议比较:人工智能系统互联与协作的技术基础架构
本文深入解析了人工智能领域的两项关键基础设施协议:模型上下文协议(MCP)与代理对代理协议(A2A)。MCP由Anthropic开发,专注于标准化AI模型与外部工具和数据源的连接,降低系统集成复杂度;A2A由Google发布,旨在实现不同AI代理间的跨平台协作。两者虽有相似之处,但在设计目标与应用场景上互为补充。文章通过具体示例分析了两种协议的技术差异及适用场景,并探讨了其在企业工作流自动化、医疗信息系统和软件工程中的应用。最后,文章强调了整合MCP与A2A构建协同AI系统架构的重要性,为未来AI技术生态系统的演进提供了方向。
1291 62
|
9月前
|
人工智能 监控 数据可视化
Agent TARS:一键让AI托管电脑!字节开源PC端多模态AI助手,无缝集成浏览器与系统操作
Agent TARS 是一款开源的多模态AI助手,能够通过视觉解析网页并无缝集成命令行和文件系统,帮助用户高效完成复杂任务。
4072 13
Agent TARS:一键让AI托管电脑!字节开源PC端多模态AI助手,无缝集成浏览器与系统操作
|
8月前
|
编解码 JavaScript 前端开发
【Java进阶】详解JavaScript的BOM(浏览器对象模型)
总的来说,BOM提供了一种方式来与浏览器进行交互。通过BOM,你可以操作窗口、获取URL、操作历史、访问HTML文档、获取浏览器信息和屏幕信息等。虽然BOM并没有正式的标准,但大多数现代浏览器都实现了相似的功能,因此,你可以放心地在你的JavaScript代码中使用BOM。
267 23
|
9月前
|
机器学习/深度学习 人工智能 算法
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
害虫识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了12种常见的害虫种类数据集【"蚂蚁(ants)", "蜜蜂(bees)", "甲虫(beetle)", "毛虫(catterpillar)", "蚯蚓(earthworms)", "蜚蠊(earwig)", "蚱蜢(grasshopper)", "飞蛾(moth)", "鼻涕虫(slug)", "蜗牛(snail)", "黄蜂(wasp)", "象鼻虫(weevil)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Djan
573 1
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
|
10月前
|
前端开发 JavaScript Java
【03】Java+若依+vue.js技术栈实现钱包积分管理系统项目-若依框架搭建-服务端-后台管理-整体搭建-优雅草卓伊凡商业项目实战
【03】Java+若依+vue.js技术栈实现钱包积分管理系统项目-若依框架搭建-服务端-后台管理-整体搭建-优雅草卓伊凡商业项目实战
558 13
【03】Java+若依+vue.js技术栈实现钱包积分管理系统项目-若依框架搭建-服务端-后台管理-整体搭建-优雅草卓伊凡商业项目实战