栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

【无标题】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】

使用TENSORFLOW HUB 进行文本分类 1.导入模块
import numpy as np
import tensorflow as tf 
! pip install tfds-nightly
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print('GPU is ','available'  if tf.config.experimental.list_physical_devices('GPU') else 'NOT AVAILABLE')
tf.__version__, tf.executing_eagerly(), hub.__version__
2.下载数据集
train_data, validation, test_data = tfds.load(
name='imdb_reviews',
split=('train[:60%]', 'train[60%:]', 'test'),
as_supervised=True)

运行代码,就会下载数据集:
Downloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to C:UsersAdministratortensorflow_datasetsimdb_reviewsplain_text1.0.0…
Dl Completed…: 0%
0/1 [00:50 Dl Size…: 6%
5/80 [00:50<12:51, 10.29s/ MiB]

来看一下刚下载的数据集:

train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
train_examples_batch

输出如下:
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
…>
再运行一次:

train_examples_batch

输出如下:
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.",
…>

3.构建模型

在本示例中,您使用来自 TensorFlow Hub 的 预训练文本嵌入向量模型,名称为 google/nnlm-en-dim50/2。

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

google/nnlm-en-dim128/2 - 基于与 google/nnlm-en-dim50/2 相同的数据并使用相同的 NNLM 架构进行训练,但具有更大的嵌入向量维度。更大维度的嵌入向量可以改进您的任务,但可能需要更长的时间来训练您的模型。
google/nnlm-en-dim128-with-normalization/2 - 与 google/nnlm-en-dim128/2 相同,但具有额外的文本归一化,例如移除标点符号。如果您的任务中的文本包含附加字符或标点符号,这会有所帮助。
google/universal-sentence-encoder/4 - 一个可产生 512 维嵌入向量的更大模型,使用深度平均网络 (DAN) 编码器训练。
还有很多!在 TFHub 上查找更多文本嵌入向量模型。

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

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()

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

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

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

这并非损失函数的唯一选择,例如,您还可以选择 mean_squared_error。但是,一般来说,binary_crossentropy 更适合处理概率问题,它可以测量概率分布之间的“距离”,或者在我们的用例中,是指真实分布与预测值之间的差距。

稍后,当您探索回归问题(例如,预测房屋价格)时,您将看到如何使用另一个称为均方误差的损失函数。

现在,配置模型来使用优化器和损失函数:

增加优化器与损失函数

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

训练模型
history = model.fig(train_data.shuffle(10000), batch(512),
                   epochs=10,
                   validation_data=validation_data.batch(512),
                   verbose=1)

实在编不下去, 有一个模型下载不到。就到此吧。

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038105.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号