🎉 TensorFlow NLP 情感分析代码示例

情感分析基础

使用TensorFlow进行情感分析通常包括以下步骤:

  1. 数据准备 - 加载带标签的文本数据(如IMDB评论)
  2. 文本向量化 - 通过Tokenizer将文本转换为序列
  3. 模型构建 - 使用LSTM/Transformer等架构处理序列数据
  4. 训练与评估 - 计算准确率/损失函数优化

代码实现示例

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences


texts = ["这部电影太棒了!", "剧情一般,演员表现欠佳"]
labels = [1, 0]  # 1为正面,0为负面

# 文本向量化
tokenizer = Tokenizer(num_words=1000)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
padded = pad_sequences(sequences, maxlen=10)

# 构建模型
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(1000, 64, input_length=10),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

# 训练模型
model.fit(padded, labels, epochs=10)

扩展阅读

想要深入了解TensorFlow NLP实践?可以参考我们的官方教程获取更多示例代码和最佳实践指南。

情感分析流程