在张量流中操纵矩阵元素 [英] Manipulating matrix elements in tensorflow

查看:135
本文介绍了在张量流中操纵矩阵元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在tensorflow中执行以下操作?

How can I do the following in tensorflow?

mat = [4,2,6,2,3] #
mat[2] = 0 # simple zero the 3rd element

我不能使用[]括号,因为它只适用于常量而不是在
变量上。我不能使用切片函数,因为它返回一个张量,你不能分配张量。

I can't use the [] brackets because it only works on constants and not on variables. I cant use the slice function either because that returns a tensor and you can't assign to a tensor.

import tensorflow as tf
sess = tf.Session()
var1 = tf.Variable(initial_value=[2, 5, -4, 0])
assignZerosOP = (var1[2] = 0) # < ------ This is what I want to do

sess.run(tf.initialize_all_variables())

print sess.run(var1)
sess.run(assignZerosOP)
print sess.run(var1)



将打印



Will print

[2, 5, -4, 0] 
[2, 5, 0, 0])


推荐答案

你无法改变张量 - 但是,如你所说,你可以更改变量。

You can't change a tensor - but, as you noted, you can change a variable.

您可以使用三种模式来完成您想要的任务:

There are three patterns you could use to accomplish what you want:

(a )使用 tf.scatter_update 直接戳到你想要改变的变量部分。

(a) Use tf.scatter_update to directly poke to the part of the variable you want to change.

import tensorflow as tf

a = tf.Variable(initial_value=[2, 5, -4, 0])
b = tf.scatter_update(a, [1], [9])
init = tf.initialize_all_variables()

with tf.Session() as s:
  s.run(init)
  print s.run(a)
  print s.run(b)
  print s.run(a)




[2 5 -4 0]

[ 2 5 -4 0]

[2 9 -4 0]

[ 2 9 -4 0]

[2 9 -4 0]

[ 2 9 -4 0]

(b)创建两个 tf.slice()张量的s,不包括你要改变的项目,然后 tf.concat(0,[a,0,b])将它们重新组合在一起。

(b) Create two tf.slice()s of the tensor, excluding the item you want to change, and then tf.concat(0, [a, 0, b]) them back together.

(c)创建 b = tf.zeros_like(a),然后使用 tf.select ()选择你想要的 a 中的哪些项目,以及 b 中的哪些零你想要的。

(c) Create b = tf.zeros_like(a), and then use tf.select() to choose which items from a you want, and which zeros from b that you want.

我已经包含了(b)和(c)因为它们适用于普通张量,而不仅仅是变量。

I've included (b) and (c) because they work with normal tensors, not just variables.

这篇关于在张量流中操纵矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆