数据集
一个英文评论的数据集,标签是三类,正向负向和中立
引入库
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import re
读入数据
data=pd.read_csv('dataset/Tweets.csv')
data.head()
有很多列数据,只使用其中两列,text,airline_sentiment评论内容以及标签
data=data[['airline_sentiment','text']]
data.head()
处理标签,字符型转化为int类型
data=data.sample(len(data))
def trans_label(label):
if label=='negative':
return 0
elif label=='positive':
return 1
else:
return 2
data['label']=data['airline_sentiment'].apply(trans_label)
del data['airline_sentiment']
处理评论数据
token=re.compile(r'[A-Za-z]+|[!?,.()]')
def reg_text(text):
new_text=token.findall(text)
new_text=[word.lower() for word in new_text]
return new_text
data['text']=data.text.apply(reg_text)
data
每条数据是一个列表,列表中是其每个词
构建词表与转化评论为数字特征
datax=data['text']
y=data['label']
x_train,x_test,y_train,y_test = train_test_split(datax,y,test_size=0.2,random_state=0)
word_set=set()
for text in x_train:
for word in text:
word_set.add(word)
max_word=len(word_set)+2
word_list=list(word_set)
word_index=dict((word,word_list.index(word)+2) for word in word_list)
x_train_data=x_train.apply(lambda x:[word_index.get(word,1) for word in x])
x_test_data=x_test.apply(lambda x:[word_index.get(word,1) for word in x])
max_len=max(len(x) for x in x_train_data)
x_train_data=tf.keras.preprocessing.sequence.pad_sequences(x_train_data.values,maxlen=max_len)
x_test_data=tf.keras.preprocessing.sequence.pad_sequences(x_test_data.values,maxlen=max_len)
模型的构建与训练
model=keras.Sequential([
layers.Embedding(max_word,50,input_length=max_len),
layers.LSTM(64),
layers.Dense(3,activation='softmax')
])
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['acc'])
model.fit(x_train_data,y_train,epochs=10,batch_size=128,validation_data=(x_test_data,y_test))
|