tensorflow进行情感分析 python代码
时间: 2023-07-22 10:25:26 浏览: 45
以下是使用TensorFlow进行情感分析的Python代码示例:
```python
import tensorflow as tf
from tensorflow.keras import layers
# 准备数据
train_text = ['example text 1', 'example text 2', 'example text 3']
train_labels = [0, 1, 1] # 标签为0或1
# 创建tokenizer
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=10000)
tokenizer.fit_on_texts(train_text)
# 将文本转换为序列
train_sequences = tokenizer.texts_to_sequences(train_text)
# 对序列进行填充
train_padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(train_sequences, maxlen=50, padding='post')
# 构建模型
model = tf.keras.Sequential([
layers.Embedding(10000, 16, input_length=50),
layers.GlobalAveragePooling1D(),
layers.Dense(16, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
# 编译模型
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(train_padded_sequences, train_labels, epochs=10)
# 预测新数据
test_text = ['example text 4']
test_sequences = tokenizer.texts_to_sequences(test_text)
test_padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(test_sequences, maxlen=50, padding='post')
predictions = model.predict(test_padded_sequences)
# 输出预测结果
if predictions[0] > 0.5:
print('Positive')
else:
print('Negative')
```
这个代码示例使用了与上一个示例相同的模型结构和数据预处理过程,只是使用了不同的标签。你可以根据自己的需求修改训练数据和标签,并对模型进行调整来适应不同的情感分析任务。