【发布时间】:2017-10-05 01:00:50
【问题描述】:
更新:
我正在为我的期末项目构建一个神经网络,我需要一些帮助。
我正在尝试构建一个 rnn 来对西班牙语文本进行情感分析。我有大约 200,000 条带标签的推文,我使用带有西班牙语嵌入的 word2vec 对它们进行矢量化
数据集和矢量化:
- 我删除了重复数据并将数据集拆分为训练集和测试集。
- 向量化时应用填充、未知和句尾标记。
- 我将@提及映射到 word2vec 模型中的已知名称。示例:@iamthebest => "约翰"
我的模特:
- 我的数据张量的形状为 = (batch_size, 20, 300)。
- 我有 3 个类别:中性、正面和负面,所以我的目标张量的形状 = (batch_size, 3)
- 我使用 BasicLstm 单元和动态 rnn 构建网络。
- 我使用 Adam Optimizer 和 softmax_cross entropy 进行损失计算
- 我使用 dropout 包装器来减少过度拟合。
上次运行:
- 我尝试了不同的配置,但似乎都不起作用。
- 最后一次设置:2 层,512 批大小,15 个 epoch 和 0.001 的 lr。
我的弱点:
我担心最后一层和dynamic_rnn中最终状态的处理
代码:
# set variables
num_epochs = 15
tweet_size = 20
hidden_size = 200
vec_size = 300
batch_size = 512
number_of_layers= 1
number_of_classes= 3
learning_rate = 0.001
TRAIN_DIR="/checkpoints"
tf.reset_default_graph()
# Create a session
session = tf.Session()
# Inputs placeholders
tweets = tf.placeholder(tf.float32, [None, tweet_size, vec_size], "tweets")
labels = tf.placeholder(tf.float32, [None, number_of_classes], "labels")
# Placeholder for dropout
keep_prob = tf.placeholder(tf.float32)
# make the lstm cells, and wrap them in MultiRNNCell for multiple layers
def lstm_cell():
cell = tf.contrib.rnn.BasicLSTMCell(hidden_size)
return tf.contrib.rnn.DropoutWrapper(cell=cell, output_keep_prob=keep_prob)
multi_lstm_cells = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(number_of_layers)], state_is_tuple=True)
# Creates a recurrent neural network
outputs, final_state = tf.nn.dynamic_rnn(multi_lstm_cells, tweets, dtype=tf.float32)
with tf.name_scope("final_layer"):
# weight and bias to shape the final layer
W = tf.get_variable("weight_matrix", [hidden_size, number_of_classes], tf.float32, tf.random_normal_initializer(stddev=1.0 / math.sqrt(hidden_size)))
b = tf.get_variable("bias", [number_of_classes], initializer=tf.constant_initializer(1.0))
sentiments = tf.matmul(final_state[-1][-1], W) + b
prob = tf.nn.softmax(sentiments)
tf.summary.histogram('softmax', prob)
with tf.name_scope("loss"):
# define cross entropy loss function
losses = tf.nn.softmax_cross_entropy_with_logits(logits=sentiments, labels=labels)
loss = tf.reduce_mean(losses)
tf.summary.scalar("loss", loss)
with tf.name_scope("accuracy"):
# round our actual probabilities to compute error
accuracy = tf.to_float(tf.equal(tf.argmax(prob,1), tf.argmax(labels,1)))
accuracy = tf.reduce_mean(tf.cast(accuracy, dtype=tf.float32))
tf.summary.scalar("accuracy", accuracy)
# define our optimizer to minimize the loss
with tf.name_scope("train"):
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
#tensorboard summaries
merged_summary = tf.summary.merge_all()
logdir = "tensorboard/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
writer = tf.summary.FileWriter(logdir, session.graph)
# initialize any variables
tf.global_variables_initializer().run(session=session)
# Create a saver for writing training checkpoints.
saver = tf.train.Saver()
# load our data and separate it into tweets and labels
train_tweets = np.load('data_es/train_vec_tweets.npy')
train_labels = np.load('data_es/train_vec_labels.npy')
test_tweets = np.load('data_es/test_vec_tweets.npy')
test_labels = np.load('data_es/test_vec_labels.npy')
**HERE I HAVE THE LOOP FOR TRAINING AND TESTING, I KNOW ITS FINE**
【问题讨论】:
-
我想知道您是如何格式化数据的。每条推文有 20 个字。每条推文是否正好有 20 个字?您是否使用了填充?如果是这样,您的准确性和损失必须被填充词掩盖。并且 LSTM 也必须提供一个用于表演的序列长度。让我们知道。
-
推文长度可变。我从数据集中取出每条推文,对单词进行标记,然后使用 word2vec 模型对它们进行向量化,如果单词不在模型词汇表中,我会生成一个与模型形状相同且在区间 (-0.25, 0.25)。我用零向量填充每条推文以达到最大长度(20)。可以吗?
标签: tensorflow lstm sentiment-analysis recurrent-neural-network rnn