python - (为了防止内存错误)如何使用 Tokenize 类在 Keras 中将单词列表热编码为 INTEGER 8 矩阵

标签 python text keras nltk tokenize

AS FLOAT64 占用更多内存,这是标记化矩阵的默认数据类型,我希望它是 INT8 类型,从而节省空间。

link to documentation

这就是我所说的方法,

texts_to_matrix(texts):
Return: numpy array of shape (len(texts), num_words).
Arguments:
    texts: list of texts to vectorize.
    mode: one of "binary", "count", "tfidf", "freq" (default: "binary").

最佳答案

看源码,创建了结果矩阵here使用不带 dtype 关键字参数的 np.zeros() 会导致 dtype 被设置为 function definition 中设置的默认值这是 float 。我认为选择这种数据类型是为了支持所有形式的转换,例如 tfidf ,这会导致非整数输出。 所以我认为你必须选择:

<强>1。更改源代码 您可以将关键字参数添加到 texts_to_matrix 的定义中,例如 dtype 并更改 the line创建矩阵的位置

x = np.zeros((len(sequences), num_words), dtype=dtype)

2.使用其他工具进行预处理: 您可以使用其他工具预处理文本,然后将其输入 keras 网络。例如,您可以使用 scikit learn 的 CountVectorizer像:

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(dtype=np.int8, ...)
matrix = cv.fit_transform(texts).toarray()

关于python - (为了防止内存错误)如何使用 Tokenize 类在 Keras 中将单词列表热编码为 INTEGER 8 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263269/

相关文章:

python - 从数据库中提取十进制数据并存储在数组中

python - Flask-Login:user_callback 函数在登录后重置为 None

javascript 禁用/启用输入文本表单

html - 隐藏文本的特殊 unicode/转义字符?

python - Keras 包安装

python - 分类 : What happens if one class has 4 times as much data as the other class?

Tensorflow ResNet 模型加载使用 **~5 GB 的 RAM** - 而从权重加载仅使用~200 MB

python - 如何使用Api Key而不直接在python代码中使用它?

python - 如何正确地对 FileNotFoundError 进行单元测试

c# - 在 .NET 中用文本 block 初始化字符串的语法是什么?