tensorflow 实现汽车评论情感极性分析:简单神经网络

一. 获取数据

import numpy as np
import pandas as pd
import jieba

# 1. 读取数据,数据预处理
comment_path = "G:\\myLearning\\pythonLearning201712\\carComments\\01\\myCleanedComments.CSV"
comment_df = pd.read_csv(comment_path, engine = 'python')
print(comment_df.head())

del comment_df['ID']
del comment_df['title']
del comment_df['sumUp']
del comment_df['sup_num']

# 2.读入停用词
# 也可使用open(filename).readlines()获取停用词
stopwords_path = "G:\\myLearning\\pythonLearning201712\\myDicts\\新建文件夹\\综合stopword.txt"
stopwords = pd.read_csv(stopwords_path,names = ['stopwords'], sep = 'aaa',encoding = 'utf-8', engine = 'python')

# 3.自定义分词函数
import re
def my_cut_func(my_str):
    my_str = re.sub('[a-zA-Z]*','',my_str)  # 去除字母
    my_str = re.sub('\d|\s','',my_str)     # 去除数字和空格stopwords_path
    my_str_list = jieba.cut(my_str)
    # 去除停用词和长度为1的词
    my_str_list = [word for word in my_str_list if word not in stopwords and len(word) > 1] 
    return my_str_list

# 4.加载搜狗汽车词典: 原文件必须为utf-8格式
jieba.load_userdict('G:\\myLearning\\sougou词库\\汽车词汇大全【官方推荐】.txt') 

# 5.将所有文本合并为一个大字符串
pos_comments = list(comment_df['advance'])
pos_comments = [str(item) for item in pos_comments]
all_pos_comments = ''.join(pos_comments)

neg_comments = list(comment_df['disadvance'])
neg_comments = [str(item) for item in neg_comments]
all_neg_comments = ''.join(neg_comments)


二. 获取词频矩阵:基于bow

# 1. 基于词袋模型(unigram, bigram 和 trigram等)
# (1)读取数据
pos_comment_df = pd.DataFrame()
neg_comment_df = pd.DataFrame()
pos_comment_df['txt'] = comment_df.advance
pos_comment_df['tag'] = 1.0
neg_comment_df['txt'] = comment_df.disadvance
neg_comment_df['tag'] = 0.0
df0 = pos_comment_df.append(neg_comment_df)

# (2)分词和预处理

# 加载搜狗汽车词典: 原文件必须为utf-8格式
jieba.load_userdict('G:\\myLearning\\sougou词库\\汽车词汇大全【官方推荐】.txt') 
# 读入停用词
# 也可使用open(filename).readlines()获取停用词
stopwords_path = "G:\\myLearning\\pythonLearning201712\\myDicts\\新建文件夹\\综合stopword.txt"
stopwords = pd.read_csv(stopwords_path,names = ['stopwords'], sep = 'aaa',encoding = 'utf-8', engine = 'python')

# 自定义分词函数
import re
def cuttxt(my_str):
    my_str = re.sub('[a-zA-Z0-9]*','',str(my_str))  # 去除字母和字母
    my_str = re.sub('\s','',my_str)            # 去除空格、换行符等。
    my_str_list = jieba.cut(my_str)
    # 去除停用词和长度为1的词
    my_str_list = [word for word in my_str_list if word not in stopwords and len(word) > 1] 
    return ' '.join(my_str_list)

df0['cleantxt'] = df0.txt.apply(cuttxt)
df0.head()

# (3) 利用sklearn中的CountVectorizer生成词频的稀疏矩阵
from sklearn.feature_extraction.text import CountVectorizer
countvec = CountVectorizer(min_df = 10)          # 在10个以上的文档中出现过才收入,此处的min_df是可调整优化的参数

wordmtx = countvec.fit_transform(df0.cleantxt)       # 生成稀疏矩阵
wordmtx

<1x4266 sparse matrix of type '<class 'numpy.int64'>'
	with 6 stored elements in Compressed Sparse Row format>


三. 利用神经网络进行情感分析

import tensorflow as tf
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(sparse=True)    # 默认是稀疏矩阵, 设置为False时返回标准矩阵


# 1.获取训练和测试数据集
nn_X_data = wordmtx.todense()
nn_y_data = np.mat(df0.tag).reshape([-1,1])
ohe_y_data = ohe.fit_transform(nn_y_data)           # 默认是稀疏矩阵
ohe_y_data = ohe_y_data.todense()
m,n = wordmtx.shape

from sklearn.model_selection import train_test_split
nn_X_train,nn_X_test,nn_y_train,nn_y_test = train_test_split(nn_X_data, ohe_y_data, test_size = 0.3, random_state = 1)

# 2.定义placeholder
X_place = tf.placeholder(tf.float32, [None, n])
y_place = tf.placeholder(tf.float32, [None, 2])

# 权值初始化
def weight_variable(shape):
    # 用正态分布来初始化权值
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    # 本例中用relu激活函数,所以用一个很小的正偏置较好
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

# 3.定义FC1
# with tf.name_scope('conv1') as scope:
W_fc1 = weight_variable([n, 128])
b_fc1 = bias_variable([128])
h_fc1 = tf.nn.relu(tf.matmul(X_place, W_fc1) + b_fc1)
# 4.定义FC2
with tf.name_scope('conv2') as scope:
    W_fc2 = weight_variable([128, 2])
    b_fc2 = bias_variable([2])
    y_pred = tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)
    y_pred = tf.clip_by_value(y_pred, 1e-10, 1.0)           # 可防止计算tf.log(y_pred)时出现溢出的情况
# 5.定义损失函数
cross_entropy = -tf.reduce_sum(y_place * tf.log(y_pred))
trian_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)

correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.arg_max(y_place, 1))  
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# 6. 建立模型
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(101):        # 迭代101次
        sess.run(train_step, feed_dict={X_place:nn_X_train, y_place:nn_y_train})
        
        if i%10 == 0:
#             print(i, sess.run(cross_entropy, feed_dict={X_place:nn_X_train, y_place:nn_y_train} ))
        
            print(i,sess.run(accuracy, feed_dict={X_place:nn_X_test, y_place:nn_y_test} ))  
    print(sess.run(y_pred,  feed_dict={X_place:nn_X_test}))


四. 注意事项

     1.  训练时易出现loss为nan的情况,解决办法有:

  (1)、对输入数据进行归一化处理;

    (2)、对于层数较多的情况,各层都做batch_nomorlization;

    (5)、减小学习率lr。

    2.  语句y_pred = tf.clip_by_value(y_pred, 1e-10, 1.0) 可防止计算tf.log(y_pred)时出现溢出迭代情况。当y_pred中有0值时,计算tf.log(y_pred)溢出,会返回nan.  

    3.  尝试改变学习率或者使用AdamOptimizer等优化器。

### 回答1: TensorFlow是一个开源的机器学习框架,可以用来构建各种深度学习模型,其中包括LSTM模型。LSTM是一种循环神经网络,可以用来处理序列数据,比如自然语言文本。情感分析是一种文本分类任务,旨在确定文本的情感极性,如正面、负面或中性。使用TensorFlow LSTM模型进行情感分析可以有效地处理文本序列数据,从而实现准确的情感极性分类。 ### 回答2: TensorFlow是一个开源的机器学习框架,可以用于构建各种深度学习模型,如循环神经网络(Recurrent Neural Network,RNN)。其中,长短期记忆网络(Long Short-Term Memory,LSTM)是一种特殊类型的RNN,被广泛应用于情感分析任务。 情感分析是一种在文本中识别和分析情感倾向、情感极性的任务。通过对文本进行情感分析,可以帮助人们了解公众对某一主题的态度、观点以及情感变化趋势。 使用TensorFlow实现LSTM情感分析的步骤大致如下: 1. 数据准备:获取情感分析的训练数据集,并进行数据预处理,如分词、去除停用词等。 2. 构建词向量模型:使用TensorFlow中的工具(如word2vec)将文本中的每个词转化为一个向量,以便模型可以更好地处理文本数据。 3. 构建LSTM模型:使用TensorFlow的LSTM层和其他神经网络层来构建一个情感分析模型。可以根据数据集的特点和任务需求来调整模型的结构和参数。 4. 模型训练:使用训练数据对LSTM模型进行训练,通过反向传播算法进行参数更新,使模型逐渐学习到文本数据的情感分析能力。 5. 模型评估:使用验证集或测试集对训练好的模型进行评估,计算模型的准确率、精确度、召回率等指标,以评估模型的性能。 6. 模型应用:使用训练好的LSTM情感分析模型对新的文本进行情感分析,预测出文本的情感倾向,并根据需求做进一步的处理和应用。 通过以上步骤,我们可以使用TensorFlow实现LSTM情感分析,并得到一个具有一定准确性的情感分析模型。这个模型可以应用于各种领域,如社交媒体情感分析、产品评论情感分析等。 ### 回答3: TensorFlow 是一个开源的机器学习框架,支持多种算法和模型的实现。其中,LSTM(长短期记忆网络)是一种常用的循环神经网络,广泛应用于自然语言处理任务中的序列建模。 情感分析是一种文本分类任务,旨在自动判断一段文本的情感倾向,例如积极或消极。使用 TensorFlow 和 LSTM 实现情感分析可以通过以下步骤完成: 1. 数据准备:首先,需要准备情感分析的训练数据集。该数据集应包括具有标记情感(如积极或消极)的文本样本。 2. 文本预处理:对训练数据集进行预处理,包括词汇表构建、文本分词、文本向量化等步骤。可以使用 TensorFlow 提供的文本处理工具或其他第三方库来完成这些任务。 3. 构建 LSTM 模型:在 TensorFlow 中,可以使用 LSTM 层作为模型的一部分,通过堆叠多个 LSTM 层来构建深度 LSTM 网络。同时,可以添加一些全连接层和激活函数以增加模型的表达能力。 4. 模型训练:使用准备好的训练数据集来训练构建的 LSTM 模型。选择适当的优化器、损失函数和评估指标,并进行适当的超参数调优。 5. 模型评估:使用测试数据集评估训练好的模型的性能。可以使用准确率、精确度、召回率等指标来评估模型的效果。 6. 模型使用:经过训练和评估后,可以使用构建的 LSTM 模型对新的文本进行情感分析。将新的文本经过预处理后输入到模型中,通过模型预测输出的情感倾向。 总结来说,使用 TensorFlow 和 LSTM 实现情感分析需要进行数据准备、文本预处理、构建 LSTM 模型、模型训练、模型评估和模型使用等步骤。通过这些步骤,可以构建一个准确的情感分析模型,用于预测文本的情感倾向。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值