cnn对文本进行情感极性分析,告诉我代码,我有正面情感词语和负面情感词语
时间: 2023-06-16 07:07:13 浏览: 64
好的,下面是一个基于CNN的文本情感极性分析代码示例,使用了正面和负面情感词语:
```
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
# 定义正面和负面情感词语
pos_words = ['good', 'great', 'fantastic', 'love', 'like']
neg_words = ['bad', 'terrible', 'awful', 'hate', 'dislike']
# 构建词汇表
vocab = set(pos_words + neg_words)
# 转换文本为数字序列
def text_to_sequence(text):
seq = []
for word in text.lower().split():
if word in vocab:
if word in pos_words:
seq.append(1)
else:
seq.append(0)
return seq
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Embedding(len(vocab) + 1, 128, input_length=100),
tf.keras.layers.Conv1D(64, 5, activation='relu'),
tf.keras.layers.GlobalMaxPooling1D(),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
x_train = pad_sequences([text_to_sequence("This movie is great"),
text_to_sequence("I hate this book")], maxlen=100)
y_train = np.array([1, 0])
model.fit(x_train, y_train, epochs=10, batch_size=1)
# 预测新的文本
def predict_sentiment(text):
x = pad_sequences([text_to_sequence(text)], maxlen=100)
pred = model.predict(x)[0]
if pred > 0.5:
return "Positive"
else:
return "Negative"
print(predict_sentiment("This book is fantastic"))
print(predict_sentiment("I dislike this movie"))
```
这个示例代码实现了一个简单的基于CNN的文本情感极性分析模型。模型的输入是一个数字序列,其中正面情感词语对应的数字是1,负面情感词语对应的数字是0。模型的输出是一个二元分类结果,表示文本的情感极性是正面还是负面。在训练过程中,我们使用了两个样本来训练模型。在预测新的文本时,我们将文本转换成数字序列,并将其输入到模型中进行预测。模型的输出值大于0.5表示预测为正面情感,小于等于0.5表示预测为负面情感。