python-3.x - python tensorflow文本分类中的稀疏矩阵

标签 python-3.x tensorflow text-classification

我一直在尝试使用 python 中的 tensorflow 包实现文本分类例程。我已经有一个成功的感知器版本在 scikit-learn 环境中工作,但 scikit-learn 没有多层神经网络(除了一些我似乎无法在任何地方找到/安装的神秘版本 0.18 之外)。

我认为最好先在 tensorflow 中尝试一些更简单的东西,以了解该包的工作原理以及它能做什么和不能做什么,所以我选择了最近的邻居。到目前为止一切顺利,除了我无法找到一种方法将词汇矩阵的稀疏版本(文本的词袋矢量化)提供给 tensorflow 中的占位符(在 scikit-learn 中这根本没有问题).将词汇矩阵转换为密集矩阵可以解决问题,但会严重降低算法速度并阻塞 RAM。

有什么办法解决这个问题吗?从我在网上发现的情况来看,tensorflow 似乎对稀疏对象的支持非常有限(只有某些操作会接受它们作为输入),但我希望我是错的。

附言是的,我读了this线程,它没有解决我的问题。是的,我知道我可以坚持使用 scikit-learn 的感知器或选择其他包,但这是我将根据我在此处获得的答案做出的决定。

最佳答案

使用 TensorFlow 1.0.1,我可以这样做:

a = sparse.csr_matrix([[0, 1, 2], [5, 0, 0], [0, 0, 5],
                       [10, 1, 0], [0, 0, 4]])
# w = np.arange(6, dtype=np.float32).reshape([3, 2])
a = a.tocoo()

a_ = tf.sparse_placeholder('float32')
w_ = tf.Variable(tf.random_normal([3, 2], stddev=1.0))

a_sum = tf.sparse_reduce_sum(a_, 1)
a_mul = tf.sparse_tensor_dense_matmul(a_, w_)

# Initializing the variables
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    indices = np.array(zip(a.row, a.col), dtype=np.int32)
    values = np.array(a.data, dtype=np.float32)
    shape = np.array(a.shape, dtype=np.int32)

    print sess.run(a_mul, feed_dict={a_: tf.SparseTensorValue(indices, values, shape)})
    w = sess.run(w_)
    print np.dot(a.todense(), w)

您可以从 API 页面找到代码:sparse placeholder .第一层之后,神经网络的其他层将是密集矩阵。

关于python-3.x - python tensorflow文本分类中的稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36041112/

相关文章:

python - DataFrame - 来自嵌套字典的表中的表

python-3.x - 无法将 numpy dtypes 转换为其 native python 类型(int64 到 int)

python - 这种切片行为是否已定义?

python - 桑尼 : installing tensorflow and importing it

machine-learning - 文本分类对于提前输入搜索来说是否足够快?

python-3.x - 执行 popen 并超时

python-3.x - Ubuntu python 使用 sudo 导入tensorflow错误

tensorflow 2 : Customized Loss Function works differently from the original Keras SparseCategoricalCrossentropy

python - 当一个主题太宽泛而另一个主题非常狭窄时,如何平衡主题、两类数据集?

python - 在字典上使用标签编码器