【问题标题】:Converting Python code to a TensorFlow program将 Python 代码转换为 TensorFlow 程序
【发布时间】:2018-10-30 04:24:58
【问题描述】:

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

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 运行它。

【问题讨论】:

  • 目前尚不清楚您期望得到什么样的帮助,但 Stack Overflow 不是免费获得软件编写的地方。
  • 谢谢@Borodin。我想修改矩阵(mat1)条目,但索引在 tensorflow 中不起作用。

标签: python tensorflow machine-learning


【解决方案1】:

首先,您的代码似乎有错误。 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]]

【讨论】:

  • 有没有办法在代码运行时手动输入矩阵“边”的条目,在张量流中?
  • 检查tf.placeholder()
  • 我有一个 Python 上的函数式命令,想学习 tensorflow 编程。有什么建议吗?
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2018-03-31
  • 2018-11-05
  • 1970-01-01
相关资源
最近更新 更多