好的,以下是使用Keras构建情感分析模型的代码示例:
首先,需要导入需要的库:
```python
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense
```
接着,读取数据集并进行预处理:
```python
# 读取数据集
data = pd.read_csv('sentiment_analysis.csv')
# 将文本转换为小写
texts = data['text'].apply(lambda x: x.lower())
# 将标签转换为数字:0表示负面情感,1表示正面情感
labels = np.array([0 if label == 'negative' else 1 for label in data['label']])
```
然后,进行单词向量化:
```python
# 将文本转换为单词序列
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
# 对单词序列进行填充,使其长度相同
padded_sequences = pad_sequences(sequences, maxlen=100)
```
接下来,构建模型:
```python
model = Sequential()
# 添加嵌入层
model.add(Embedding(input_dim=5000, output_dim=100, input_length=100))
# 添加1D卷积层
model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))
# 添加全局最大池化层
model.add(GlobalMaxPooling1D())
# 添加全连接层
model.add(Dense(units=64, activation='relu'))
# 添加输出层
model.add(Dense(units=1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
```
最后,训练模型并进行评估:
```python
# 划分训练集和测试集
indices = np.arange(padded_sequences.shape[0])
np.random.shuffle(indices)
padded_sequences = padded_sequences[indices]
labels = labels[indices]
train_size = int(0.8 * padded_sequences.shape[0])
train_X, test_X = padded_sequences[:train_size], padded_sequences[train_size:]
train_y, test_y = labels[:train_size], labels[train_size:]
# 训练模型
model.fit(train_X, train_y, epochs=10, batch_size=64)
# 评估模型
loss, accuracy = model.evaluate(test_X, test_y)
print('Test accuracy:', accuracy)
```
完整的代码示例如下:
```python
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense
# 读取数据集
data = pd.read_csv('sentiment_analysis.csv')
# 将文本转换为小写
texts = data['text'].apply(lambda x: x.lower())
# 将标签转换为数字:0表示负面情感,1表示正面情感
labels = np.array([0 if label == 'negative' else 1 for label in data['label']])
# 将文本转换为单词序列
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
# 对单词序列进行填充,使其长度相同
padded_sequences = pad_sequences(sequences, maxlen=100)
# 构建模型
model = Sequential()
# 添加嵌入层
model.add(Embedding(input_dim=5000, output_dim=100, input_length=100))
# 添加1D卷积层
model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))
# 添加全局最大池化层
model.add(GlobalMaxPooling1D())
# 添加全连接层
model.add(Dense(units=64, activation='relu'))
# 添加输出层
model.add(Dense(units=1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 划分训练集和测试集
indices = np.arange(padded_sequences.shape[0])
np.random.shuffle(indices)
padded_sequences = padded_sequences[indices]
labels = labels[indices]
train_size = int(0.8 * padded_sequences.shape[0])
train_X, test_X = padded_sequences[:train_size], padded_sequences[train_size:]
train_y, test_y = labels[:train_size], labels[train_size:]
# 训练模型
model.fit(train_X, train_y, epochs=10, batch_size=64)
# 评估模型
loss, accuracy = model.evaluate(test_X, test_y)
print('Test accuracy:', accuracy)
```