如何使用 Tensorflow 用 Python 对 stackoverflow 问题数据集相关的文本数据进行矢量化?
Tensorflow 是 Google 提供的机器学习框架。它是一个开源框架,与 Python 结合使用,用于实现算法、深度学习应用程序等。它用于研究和生产目的。它具有优化技术,有助于快速执行复杂的数学运算。
这是因为它使用 NumPy 和多维数组。这些多维数组也称为"张量"。该框架支持使用深度神经网络。它具有高度可扩展性,并附带许多流行的数据集。它使用 GPU 计算并自动管理资源。它附带大量机器学习库,并且得到良好的支持和记录。该框架能够运行深度神经网络模型、对其进行训练,并创建预测相应数据集相关特征的应用程序。
可以使用以下代码行在 Windows 上安装 ‘tensorflow’ 包 −
pip install tensorflow
Tensor 是 TensorFlow 中使用的数据结构。它有助于连接流程图中的边缘。此流程图称为"数据流图"。张量不过是一个多维数组或列表。
我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,并且不需要任何配置,并且可以免费访问 GPU(图形处理单元)。 Colaboratory 是在 Jupyter Notebook 上构建的。
示例
以下是用于矢量化文本数据的代码片段 −
print("The vectorize function is defined") def int_vectorize_text(text, label): text = tf.expand_dims(text, -1) return int_vectorize_layer(text), label print(" A batch of the dataset is retrieved") text_batch, label_batch = next(iter(raw_train_ds)) first_question, first_label = text_batch[0], label_batch[0] print("Question is : ", first_question) print("Label is : ", first_label) print("'binary' vectorized question is :", binary_vectorize_text(first_question, first_label)[0]) print("'int' vectorized question is :", int_vectorize_text(first_question, first_label)[0])
代码来源 − https://www.tensorflow.org/tutorials/load_data/text
输出
The vectorize function is defined A batch of the dataset is retrieved Question is : tf.Tensor(b'"function expected error in blank for dynamically created check box when it is clicked i want to grab the attribute value.it is working in ie 8,9,10 but not working in ie 11,chrome shows function expected error..<input type=checkbox checked=\'checked\' id=\'symptomfailurecodeid\' tabindex=\'54\' style=\'cursor:pointer;\' onclick=chkclickevt(this); failurecodeid=""1"" >...function chkclickevt(obj) { . alert(obj.attributes(""failurecodeid""));.}"\n', shape=(), dtype=string) Label is : tf.Tensor(2, shape=(), dtype=int32) 'binary' vectorized question is : tf.Tensor([[1. 1. 1. ... 0. 0. 0.]], shape=(1, 10000), dtype=float32) 'int' vectorized question is : tf.Tensor( [[ 37 464 65 7 16 12 879 262 181 448 44 10 6 700 3 46 4 2085 2 473 1 6 156 7 478 1 25 20 156 7 478 1 499 37 464 1 1846 1666 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]], shape=(1, 250), dtype=int64)
解释
二进制模式返回一个数组,指示标记的存在情况。
在 int 模式下,每个标记都由一个整数替换。
这样,顺序将被保留。
定义了 vectorize 函数。
对数据样本进行矢量化,并在控制台上显示 ‘binary’ 和 ‘int’ 矢量化模式
可以使用该特定层上的 ‘get_vocabulary’ 方法查找字符串。