使用Keras和Tensorflow Hub对电影评论进行文本分类

本指南使用tf.keras(一个在TensorFlow中用于构建和训练模型的高级API)和tensorflow_hub(一个用于在一行代码中从TFHub加载训练模型的库)。

# 首先我们要在Anaconda3 Prompt()中激活tensorflow环境然后再进行安装hub和基本数据集$pip install tensorflow-hub
$pip install tensorflow-datasets
  File "C:\Users\61628\AppData\Local\Temp/ipykernel_11092/1129299395.py", line 3$pip install tensorflow-hub^
SyntaxError: invalid syntax
import numpy as np
import tensorflow as tf
!pip install tensorflow-hub
!pip install tfds-nightly
import tensorflow_hub as hub
import tensorflow_datasets as tfdsprint('Version: ',tf.__version__)
print('Eager node: ', tf.executing_eagerly())
print('Hub version: ', hub.__version__)
print('GPU is', 'available' if tf.config.experimental.list_physical_devices("GPU")else 'NOT AVAILABLE')
Requirement already satisfied: tensorflow-hub in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (0.12.0)
Requirement already satisfied: numpy>=1.12.0 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tensorflow-hub) (1.22.2)
Requirement already satisfied: protobuf>=3.8.0 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tensorflow-hub) (3.19.4)
Requirement already satisfied: tfds-nightly in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (4.5.2.dev202203060044)
Requirement already satisfied: tqdm in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (4.63.0)
Requirement already satisfied: etils[epath-no-tf] in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (0.4.0)
Requirement already satisfied: numpy in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (1.22.2)
Requirement already satisfied: tensorflow-metadata in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (1.7.0)
Requirement already satisfied: promise in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (2.3)
Requirement already satisfied: dill in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (0.3.4)
Requirement already satisfied: protobuf>=3.12.2 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (3.19.4)
Requirement already satisfied: termcolor in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: requests>=2.19.0 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (2.27.1)
Requirement already satisfied: six in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (1.16.0)
Requirement already satisfied: absl-py in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (1.0.0)
Requirement already satisfied: toml in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tfds-nightly) (0.10.2)
Requirement already satisfied: idna<4,>=2.5 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from requests>=2.19.0->tfds-nightly) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from requests>=2.19.0->tfds-nightly) (1.26.8)
Requirement already satisfied: charset-normalizer~=2.0.0 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from requests>=2.19.0->tfds-nightly) (2.0.12)
Requirement already satisfied: certifi>=2017.4.17 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from requests>=2.19.0->tfds-nightly) (2021.10.8)
Requirement already satisfied: importlib_resources in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from etils[epath-no-tf]->tfds-nightly) (5.4.0)
Requirement already satisfied: zipp in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from etils[epath-no-tf]->tfds-nightly) (3.7.0)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tensorflow-metadata->tfds-nightly) (1.55.0)
Requirement already satisfied: colorama in d:\programdata\anaconda3\envs\tensorflow\lib\site-packages (from tqdm->tfds-nightly) (0.4.4)D:\ProgramData\Anaconda3\envs\tensorflow\lib\site-packages\tqdm\auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.htmlfrom .autonotebook import tqdm as notebook_tqdmVersion:  2.8.0
Eager node:  True
Hub version:  0.12.0
GPU is available

下载IMDB数据集

IMDB数据集可以在Tensorflow数据集处获取。以下代码将IMDB数据集下载到我们计算机中:

#将15000个训练数据集分为四六等分用来训练,
#10000个样例用来作为验证集,25000个样本作为测试集
train_data, validation_data, test_data = tfds.load(name='imdb_reviews',split=('train[:60%]','train[60%:]','test'),as_supervised=True)

探索数据

我们了解数据格式。每个样本都是一个代表电影评论的句子和一个相应的标签。句子未经过任何处理。标签是一个整数值(0或1),其中0表示负面评价,而1表示正面评价。我们打印前10个样本

train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
train_examples_batch
<tf.Tensor: shape=(10,), dtype=string, numpy=
array([b"This was an absolutely terrible movie. Don't be lured in by Christopher Walken or Michael Ironside. Both are great actors, but this must simply be their worst role in history. Even their great acting could not redeem this movie's ridiculous storyline. This movie is an early nineties US propaganda piece. The most pathetic scenes were those when the Columbian rebels were making their cases for revolutions. Maria Conchita Alonso appeared phony, and her pseudo-love affair with Walken was nothing but a pathetic emotional plug in a movie that was devoid of any real meaning. I am disappointed that there are movies like this, ruining actor's like Christopher Walken's good name. I could barely sit through it.",b'I have been known to fall asleep during films, but this is usually due to a combination of things including, really tired, being warm and comfortable on the sette and having just eaten a lot. However on this occasion I fell asleep because the film was rubbish. The plot development was constant. Constantly slow and boring. Things seemed to happen, but with no explanation of what was causing them or why. I admit, I may have missed part of the film, but i watched the majority of it and everything just seemed to happen of its own accord without any real concern for anything else. I cant recommend this film at all.',b'Mann photographs the Alberta Rocky Mountains in a superb fashion, and Jimmy Stewart and Walter Brennan give enjoyable performances as they always seem to do. <br /><br />But come on Hollywood - a Mountie telling the people of Dawson City, Yukon to elect themselves a marshal (yes a marshal!) and to enforce the law themselves, then gunfighters battling it out on the streets for control of the town? <br /><br />Nothing even remotely resembling that happened on the Canadian side of the border during the Klondike gold rush. Mr. Mann and company appear to have mistaken Dawson City for Deadwood, the Canadian North for the American Wild West.<br /><br />Canadian viewers be prepared for a Reefer Madness type of enjoyable howl with this ludicrous plot, or, to shake your head in disgust.',b'This is the kind of film for a snowy Sunday afternoon when the rest of the world can go ahead with its own business as you descend into a big arm-chair and mellow for a couple of hours. Wonderful performances from Cher and Nicolas Cage (as always) gently row the plot along. There are no rapids to cross, no dangerous waters, just a warm and witty paddle through New York life at its best. A family film in every sense and one that deserves the praise it received.',b'As others have mentioned, all the women that go nude in this film are mostly absolutely gorgeous. The plot very ably shows the hypocrisy of the female libido. When men are around they want to be pursued, but when no "men" are around, they become the pursuers of a 14 year old boy. And the boy becomes a man really fast (we should all be so lucky at this age!). He then gets up the courage to pursue his true love.',b"This is a film which should be seen by anybody interested in, effected by, or suffering from an eating disorder. It is an amazingly accurate and sensitive portrayal of bulimia in a teenage girl, its causes and its symptoms. The girl is played by one of the most brilliant young actresses working in cinema today, Alison Lohman, who was later so spectacular in 'Where the Truth Lies'. I would recommend that this film be shown in all schools, as you will never see a better on this subject. Alison Lohman is absolutely outstanding, and one marvels at her ability to convey the anguish of a girl suffering from this compulsive disorder. If barometers tell us the air pressure, Alison Lohman tells us the emotional pressure with the same degree of accuracy. Her emotional range is so precise, each scene could be measured microscopically for its gradations of trauma, on a scale of rising hysteria and desperation which reaches unbearable intensity. Mare Winningham is the perfect choice to play her mother, and does so with immense sympathy and a range of emotions just as finely tuned as Lohman's. Together, they make a pair of sensitive emotional oscillators vibrating in resonance with one another. This film is really an astonishing achievement, and director Katt Shea should be proud of it. The only reason for not seeing it is if you are not interested in people. But even if you like nature films best, this is after all animal behaviour at the sharp edge. Bulimia is an extreme version of how a tormented soul can destroy her own body in a frenzy of despair. And if we don't sympathise with people suffering from the depths of despair, then we are dead inside.",b'Okay, you have:<br /><br />Penelope Keith as Miss Herringbone-Tweed, B.B.E. (Backbone of England.) She\'s killed off in the first scene - that\'s right, folks; this show has no backbone!<br /><br />Peter O\'Toole as Ol\' Colonel Cricket from The First War and now the emblazered Lord of the Manor.<br /><br />Joanna Lumley as the ensweatered Lady of the Manor, 20 years younger than the colonel and 20 years past her own prime but still glamourous (Brit spelling, not mine) enough to have a toy-boy on the side. It\'s alright, they have Col. Cricket\'s full knowledge and consent (they guy even comes \'round for Christmas!) Still, she\'s considerate of the colonel enough to have said toy-boy her own age (what a gal!)<br /><br />David McCallum as said toy-boy, equally as pointlessly glamourous as his squeeze. Pilcher couldn\'t come up with any cover for him within the story, so she gave him a hush-hush job at the Circus.<br /><br />and finally:<br /><br />Susan Hampshire as Miss Polonia Teacups, Venerable Headmistress of the Venerable Girls\' Boarding-School, serving tea in her office with a dash of deep, poignant advice for life in the outside world just before graduation. Her best bit of advice: "I\'ve only been to Nancherrow (the local Stately Home of England) once. I thought it was very beautiful but, somehow, not part of the real world." Well, we can\'t say they didn\'t warn us.<br /><br />Ah, Susan - time was, your character would have been running the whole show. They don\'t write \'em like that any more. Our loss, not yours.<br /><br />So - with a cast and setting like this, you have the re-makings of "Brideshead Revisited," right?<br /><br />Wrong! They took these 1-dimensional supporting roles because they paid so well. After all, acting is one of the oldest temp-jobs there is (YOU name another!)<br /><br />First warning sign: lots and lots of backlighting. They get around it by shooting outdoors - "hey, it\'s just the sunlight!"<br /><br />Second warning sign: Leading Lady cries a lot. When not crying, her eyes are moist. That\'s the law of romance novels: Leading Lady is "dewy-eyed."<br /><br />Henceforth, Leading Lady shall be known as L.L.<br /><br />Third warning sign: L.L. actually has stars in her eyes when she\'s in love. Still, I\'ll give Emily Mortimer an award just for having to act with that spotlight in her eyes (I wonder . did they use contacts?)<br /><br />And lastly, fourth warning sign: no on-screen female character is "Mrs." She\'s either "Miss" or "Lady."<br /><br />When all was said and done, I still couldn\'t tell you who was pursuing whom and why. I couldn\'t even tell you what was said and done.<br /><br />To sum up: they all live through World War II without anything happening to them at all.<br /><br />OK, at the end, L.L. finds she\'s lost her parents to the Japanese prison camps and baby sis comes home catatonic. Meanwhile (there\'s always a "meanwhile,") some young guy L.L. had a crush on (when, I don\'t know) comes home from some wartime tough spot and is found living on the street by Lady of the Manor (must be some street if SHE\'s going to find him there.) Both war casualties are whisked away to recover at Nancherrow (SOMEBODY has to be "whisked away" SOMEWHERE in these romance stories!)<br /><br />Great drama.',b'The film is based on a genuine 1950s novel.<br /><br />Journalist Colin McInnes wrote a set of three "London novels": "Absolute Beginners", "City of Spades" and "Mr Love and Justice". I have read all three. The first two are excellent. The last, perhaps an experiment that did not come off. But McInnes\'s work is highly acclaimed; and rightly so. This musical is the novelist\'s ultimate nightmare - to see the fruits of one\'s mind being turned into a glitzy, badly-acted, soporific one-dimensional apology of a film that says it captures the spirit of 1950s London, and does nothing of the sort.<br /><br />Thank goodness Colin McInnes wasn\'t alive to witness it.',b'I really love the sexy action and sci-fi films of the sixties and its because of the actress\'s that appeared in them. They found the sexiest women to be in these films and it didn\'t matter if they could act (Remember "Candy"?). The reason I was disappointed by this film was because it wasn\'t nostalgic enough. The story here has a European sci-fi film called "Dragonfly" being made and the director is fired. So the producers decide to let a young aspiring filmmaker (Jeremy Davies) to complete the picture. They\'re is one real beautiful woman in the film who plays Dragonfly but she\'s barely in it. Film is written and directed by Roman Coppola who uses some of his fathers exploits from his early days and puts it into the script. I wish the film could have been an homage to those early films. They could have lots of cameos by actors who appeared in them. There is one actor in this film who was popular from the sixties and its John Phillip Law (Barbarella). Gerard Depardieu, Giancarlo Giannini and Dean Stockwell appear as well. I guess I\'m going to have to continue waiting for a director to make a good homage to the films of the sixties. If any are reading this, "Make it as sexy as you can"! I\'ll be waiting!',b'Sure, this one isn\'t really a blockbuster, nor does it target such a position. "Dieter" is the first name of a quite popular German musician, who is either loved or hated for his kind of acting and thats exactly what this movie is about. It is based on the autobiography "Dieter Bohlen" wrote a few years ago but isn\'t meant to be accurate on that. The movie is filled with some sexual offensive content (at least for American standard) which is either amusing (not for the other "actors" of course) or dumb - it depends on your individual kind of humor or on you being a "Bohlen"-Fan or not. Technically speaking there isn\'t much to criticize. Speaking of me I find this movie to be an OK-movie.'],dtype=object)>

我们在再打印下前十个标签。

train_labels_batch
<tf.Tensor: shape=(10,), dtype=int64, numpy=array([0, 0, 0, 1, 1, 1, 0, 0, 0, 0], dtype=int64)>

构建模型

神经网络由堆叠的层来构建,这需要从三个主要的方面来进行体系结构决策:

·如何表示文本

·模型里有多少层?

·每个层里有多少个隐层单元(hidden units)?
本示例中,输入数据由句子组成。预测标签为0或者1.

表示文本的一种方式是将句子转换为嵌入向量。表示文本的一种方式是将句子转换为嵌入向量。使用一个预训练文本嵌入向量作为首层,浙江具有三个优点:

·不必担心文本预处理

·可以从迁移学习中受益

·嵌入具有固定长度,更易于处理
在本示例中,使用的是来自Tensorflow Hub的预训练文本嵌入向量模型,名称为google/nnim-en-dim50/2

本教程中还可以使用来自TFHub的许多其他预训练文本嵌入向量;

·google/nnlm-en-dim 128/2 基于与google/nnim-en-dim50/2相同数据并使用相同的NNLM架构进行训练,但具有更大的嵌入向量维度。更大的嵌入向量可以改经我们的任务,但是可能需要更长的时间来进行训练我们的模型。

·google/nnlm-en-dim 125-with-normalization/2与google/nnlm-en-dim 128/2 相同,但具有额外的文本归一化,例如移除标点符号。若文本中包含字符或者标点符号,这会有所帮助。

·google/universal-sentence-encoder/4-一个可产生512维嵌入向量的更大模型,使用深度平均网络(DAN)编码器训练。

我们首先创建一个使用Tensorflow Hub模型嵌入(embed)语句的Keras层,并在几个输入样本中进行尝试。无论样本输入文本的长度如何,嵌入(embeddings)输出的形状都是:(num_examples, embedding_dimension).

hub_layer = hub.KerasLayer("https://hub.tensorflow.google.cn/google/nnlm-en-dim50/2", input_shape=[],dtype=tf.string,trainable=True)
hub_layer(train_examples_batch[:3])
<tf.Tensor: shape=(3, 50), dtype=float32, numpy=
array([[ 0.5423195 , -0.0119017 ,  0.06337538,  0.06862972, -0.16776837,-0.10581174,  0.16865303, -0.04998824, -0.31148055,  0.07910346,0.15442263,  0.01488662,  0.03930153,  0.19772711, -0.12215476,-0.04120981, -0.2704109 , -0.21922152,  0.26517662, -0.80739075,0.25833532, -0.3100421 ,  0.28683215,  0.1943387 , -0.29036492,0.03862849, -0.7844411 , -0.0479324 ,  0.4110299 , -0.36388892,-0.58034706,  0.30269456,  0.3630897 , -0.15227164, -0.44391504,0.19462997,  0.19528408,  0.05666234,  0.2890704 , -0.28468323,-0.00531206,  0.0571938 , -0.3201318 , -0.04418665, -0.08550783,-0.55847436, -0.23336391, -0.20782952, -0.03543064, -0.17533456],[ 0.56338924, -0.12339553, -0.10862679,  0.7753425 , -0.07667089,-0.15752277,  0.01872335, -0.08169781, -0.3521876 ,  0.4637341 ,-0.08492756,  0.07166859, -0.00670817,  0.12686075, -0.19326553,-0.52626437, -0.3295823 ,  0.14394785,  0.09043556, -0.5417555 ,0.02468163, -0.15456742,  0.68333143,  0.09068331, -0.45327246,0.23180096, -0.8615696 ,  0.34480393,  0.12838456, -0.58759046,-0.4071231 ,  0.23061076,  0.48426893, -0.27128142, -0.5380916 ,0.47016326,  0.22572741, -0.00830663,  0.2846242 , -0.304985  ,0.04400365,  0.25025874,  0.14867121,  0.40717036, -0.15422426,-0.06878027, -0.40825695, -0.3149215 ,  0.09283665, -0.20183425],[ 0.7456154 ,  0.21256861,  0.14400336,  0.5233862 ,  0.11032254,0.00902788, -0.3667802 , -0.08938274, -0.24165542,  0.33384594,-0.11194605, -0.01460047, -0.0071645 ,  0.19562712,  0.00685216,-0.24886718, -0.42796347,  0.18620004, -0.05241098, -0.66462487,0.13449019, -0.22205497,  0.08633006,  0.43685386,  0.2972681 ,0.36140734, -0.7196889 ,  0.05291241, -0.14316116, -0.1573394 ,-0.15056328, -0.05988009, -0.08178931, -0.15569411, -0.09303783,-0.18971172,  0.07620788, -0.02541647, -0.27134508, -0.3392682 ,-0.10296468, -0.27275252, -0.34078008,  0.20083304, -0.26644835,0.00655449, -0.05141488, -0.04261917, -0.45413622,  0.20023568]],dtype=float32)>

现在让我们构建完整模型:

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))model.summary()
Model: "sequential"
_________________________________________________________________Layer (type)                Output Shape              Param #
=================================================================keras_layer (KerasLayer)    (None, 50)                48190600  dense (Dense)               (None, 16)                816       dense_1 (Dense)             (None, 1)                 17        =================================================================
Total params: 48,191,433
Trainable params: 48,191,433
Non-trainable params: 0
_________________________________________________________________

层按照顺序堆叠以构建分类器:

1.第一层是TensorFlow Hub层。此层使用预期训练的SaveModel将句子映射到其嵌入向量。我们使用的是预训练文本嵌入向量模型(google/nnlm-en-dim50/2)可将句子拆分为词例,嵌入每个词例,然后组合嵌入向量。生成的维度是:(num_examples,embedding_dimension).对于此NNLM模型,embedding_dimension是50。
2.该定长输出向量通过一个有16个隐藏层单元的全连接层(Dense)进行传输。
3.最后一层与单个输出节点紧密相连。使用Sigmoid激活函数,其中函数值介于0与1之间的浮点数,表示概率或置信水平

损失函数与优化器

一个模型需要一个损失函数和一个优化器来训练。由于这是一个二元分类问题,并且模型输出logit(具有线性激活单元的单一单元层),因此我们使用binary_crossentropy损失函数。现在,配置模型来使用优化器和损失函数。

model.compile(optimizer='adam',loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),metrics=['accuracy'])

训练模型

使用包含512个样本的mini-batch对模型进行10个周期的训练,也就是x_train和y_train张量中对所有样本进行10次迭代。在训练时,检测模型在验证集的10000个样本上的损失和准确率:

history = model.fit(train_data.shuffle(10000).batch(512), epochs=10, validation_data=validation_data.batch(512),verbose=1)
Epoch 1/10
30/30 [==============================] - 4s 101ms/step - loss: 0.6454 - accuracy: 0.5513 - val_loss: 0.5901 - val_accuracy: 0.6513
Epoch 2/10
30/30 [==============================] - 3s 93ms/step - loss: 0.5225 - accuracy: 0.7143 - val_loss: 0.4842 - val_accuracy: 0.7760
Epoch 3/10
30/30 [==============================] - 3s 95ms/step - loss: 0.3942 - accuracy: 0.8287 - val_loss: 0.3917 - val_accuracy: 0.8252
Epoch 4/10
30/30 [==============================] - 3s 93ms/step - loss: 0.2849 - accuracy: 0.8916 - val_loss: 0.3389 - val_accuracy: 0.8475
Epoch 5/10
30/30 [==============================] - 3s 94ms/step - loss: 0.2074 - accuracy: 0.9271 - val_loss: 0.3143 - val_accuracy: 0.8655
Epoch 6/10
30/30 [==============================] - 3s 94ms/step - loss: 0.1517 - accuracy: 0.9539 - val_loss: 0.3046 - val_accuracy: 0.8667
Epoch 7/10
30/30 [==============================] - 3s 94ms/step - loss: 0.1110 - accuracy: 0.9698 - val_loss: 0.3055 - val_accuracy: 0.8734
Epoch 8/10
30/30 [==============================] - 3s 93ms/step - loss: 0.0801 - accuracy: 0.9815 - val_loss: 0.3108 - val_accuracy: 0.8726
Epoch 9/10
30/30 [==============================] - 3s 94ms/step - loss: 0.0573 - accuracy: 0.9897 - val_loss: 0.3196 - val_accuracy: 0.8719
Epoch 10/10
30/30 [==============================] - 3s 95ms/step - loss: 0.0412 - accuracy: 0.9940 - val_loss: 0.3315 - val_accuracy: 0.8713

评估模型

我们来看一下模型的变现如何。将返回两个值。损失值(loss)(一个表示误差数字,值越低越好)与准确率(accuracy)。

results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):print("%s : %.3f" %(name,value))
49/49 - 2s - loss: 0.3593 - accuracy: 0.8541 - 2s/epoch - 36ms/step
loss : 0.359
accuracy : 0.854

这种方法得到了约为85%的准确率(accuracy)。若采用更好的方法,模型的准确率应当还会增加。

4.使用Keras和Tensorflow Hub对电影评论进行文本分类相关推荐

  1. python电影评论情感分析_20行Tensorflow代码实现电影评论情感分析

    原标题:20行Tensorflow代码实现电影评论情感分析 背景 情感分析有很多的应用场景,比如做一个电商网站,卖家需要时刻关心用户对于商品的评论是否是正面的.再比如做一个电影的宣传和策划,电影在键盘 ...

  2. 使用逻辑回归和词向量进行(英文)电影评论情感(二)分类

    问题描述:对电影评论进行情感分类,类型一共有两种:正面评价 (pos) 和负面评价 (neg). 训练数据集:英文电影评论及对应的分类标签,保存在工作路径下.样本举例如下: 使用的算法:sklearn ...

  3. 电影影评的文本分类——基于tensorflow

    一.绪论 我们将用来自互联网电影数据库的IMDB数据集,其中包含50,000个电影影评的文本.这里将要将其分为25,000个用于训练,25,000个用于测试.训练集和数据集是平衡的,这意味着他们包含相 ...

  4. 基于tensorflow+CNN的新浪新闻文本分类

    2018年10月4日笔记 tensorflow是谷歌google的深度学习框架,tensor中文叫做张量,flow叫做流. CNN是convolutional neural network的简称,中文 ...

  5. 基于tensorflow+RNN的新浪新闻文本分类

    2018年10月11日笔记 tensorflow是谷歌google的深度学习框架,tensor中文叫做张量,flow叫做流. RNN是recurrent neural network的简称,中文叫做循 ...

  6. tensorflow多层卷积网络实现CNN文本分类

    1.实验数据获取: 这里的实验数据是本人自己提取的,具体方式是: (大家可以根据自己喜好进行如下步骤) 1.选取3个不同类别的文本,每类500篇,共1500篇. 2.使用TF-IDF或词频等方式,从每 ...

  7. 自然语言处理——对电影评论的文本情感分析

    题目(来自阿里云天池):数据主要包括IMDB网站上的电影评论文本数据. 数据分为训练数据和测试数据,分别保存在train.csv和test_noLabel.csv两个文件中. 字段说明如下: (1)I ...

  8. 基于Keras的IMDB数据集电影评论情感二分类

    原创不易,如果有转载需要的话,请在首行附上本文地址,谢谢. 第一步加载IMDB数据集,如若加载不成功,这里提供一种解决方法:点开IMDB数据下载链接(喜欢的话给个小星星和follow一下),fork到 ...

  9. TensorFlow 2官方教程 . Keras机器学习基础知识 . 使用TF Hub进行文本分类

    写在前面 此篇博客转载自tensorflow官方教程中文翻译版: https://www.tensorflow.org/tutorials/keras/text_classification_with ...

最新文章

  1. sqlplus可以连接plsql连接不上_为什么有的iPhone/iPad连接不上电脑?
  2. internetreadfile读取数据长度为0_Datax3.0的安装和基本使用
  3. spring mvc @ModelAttribute 基本类型 自定义对象解析流程
  4. 如何在VC中创建动态数组
  5. TLS/SSL握手过程
  6. Spring Boot的自动化配置原理
  7. 【洛谷 P3304】[SDOI2013]直径(树的直径)
  8. BZOJ4653: [Noi2016]区间(线段树 双指针)
  9. oracle exp(dmp)命令带过滤条件?
  10. 时间复杂度o(n^0.5)_算法基础1.1:算法复杂度计算(二)
  11. windows弹出窗体
  12. vbb论坛(vBulletin)后台获取webshell
  13. c语言调用数学函数根号,不调用库函数求根号x的计算方法(二分/三分/牛顿迭代法)...
  14. 统信UOS使用wine安装“方正ApabiReader_4.5.2.1790(ceb阅读器)”并解决安装过程中文显示成方块问题
  15. python+django+mysql教室实验室预约系统毕业设计毕设开题报告
  16. 信息系统项目管理师知识记忆口诀
  17. python连通域提取 原理_连通域的原理与Python实现
  18. 译:Dataiku 白皮书之《在银行和保险行业应用数据科学》
  19. 饿了么el-upload上传图片限制图片尺寸、大小、格式
  20. matlab加停顿,求高手解释下这段程序,实在是搞不懂了,要死的节奏了。。。。...

热门文章

  1. Windows计算器:%号的作用
  2. 用python处理excel数据、求线性回归方程的r值_python实现简单的单变量线性回归方法...
  3. 流行和声(6)mMaj7和弦
  4. 爱因斯坦经典逻辑推理题
  5. jquery.form.js在ie8下提示下载文件
  6. 百度移动应用安卓_第三方渠道之殇:继PP助手后,百度下线91与安卓市场渠道 | 游戏茶馆...
  7. nginx 配置格式化工具
  8. android Cannot access com.xxx
  9. RK3188的wifi无法切换4G上网问题
  10. 掌握主动权妈妈最需要的人生成长课