将Python代码转换为TensorFlow程序

时间:2018-05-20 08:51:11

标签: python tensorflow machine-learning

我想将以下Python代码转换为TensorFlow程序,但无法访问/修改矩阵元素(我在Jupiter笔记本上运行代码)。

edges = np.matrix('0 0 0 1; 0 0 1 0; 1 0 0 0; 0 0 1 0')
mat1 = np.matrix('0 0 0 0; 0 0 0 0; 0 0 0 0; 0 0 0 0')
for i in range(0,4):    
  for j in range(0,4):
    if edges[i,j]==1 or (edges[i,0]==1 and edges[0,j]==1):
        mat1[i,j]=1
    else:
        mat1[i,j]=1            
print(mat1)

请帮助代码,以便我可以使用TensorFlow运行它。

1 个答案:

答案 0 :(得分:0)

首先,您的代码中似乎存在错误。 ifelse条件都将mat1[i,j]设置为1 ...假设您的代码实际上是:

for i in range(0,4):
  for j in range(0,4):
    if edges[i,j]==1 or (edges[i,0]==1 and edges[0,j]==1):
        mat1[i,j]=1

然后Tensorflow解决方案是:

import tensorflow as tf

edges = tf.constant([[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 1, 0]], dtype=tf.int32)
mat1 = tf.zeros((4, 4), dtype=tf.int32)

# Building the edge condition matrix:
edges_bool = tf.equal(edges, 1)  # edges[:, :] == 1

edges_cond_i = edges_bool[:, 0]  # edges[:, 0] == 1
edges_cond_i = tf.tile(tf.expand_dims(edges_cond_i, 1), (1, 4))
edges_cond_j = edges_bool[0, :]  # edges[0, :] == 1
edges_cond_j = tf.tile(tf.expand_dims(edges_cond_j, 0), (4, 1))
edges_cond_ij = tf.logical_and(edges_cond_i, edges_cond_j)  
# edges[:, 0] == 1 and edges[0, :] == 1
edges_cond = tf.logical_or(edges_bool, edges_cond_ij)  
# edges[:, :] == 1 or (edges[:, 0] == 1 and edges[0, :] == 1)

# Applying the condition to mat1:
ones = tf.ones((4, 4), dtype=tf.int32)
mat1 = tf.where(edges_cond, ones, mat1)

# Displaying results:
with tf.device('/cpu:0'), tf.Session() as sess:
    res = sess.run(mat1)
    print(res)
# [[0 0 0 1]
#  [0 0 1 0]
#  [1 0 0 1]
#  [0 0 1 0]]