我正在嘗試將 Numpy 中的以下代碼轉換為 Tensorflow,以便我可以在我的神經網路中使用該代碼。可悲的是,由于錯誤,我還沒有做到這一點,Tensorflow 不支持專案分配,我需要這個代碼才能作業。
# Create zeros matrices
l_bbox = np.zeros((6,6), np.float32)
l_score = np.zeros((1,6,6), np.float32)
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
l_score[:, y1:y2, x1:x2] = 1.
l_score
"""
array([[[0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]], dtype=float32)
"""
# Assign varying values to l_bbox
for yy in range(y1, y2):
l_bbox[yy, x1:x2] = yy - y1
l_bbox
"""
array([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 2., 2., 2., 2., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]], dtype=float32)
"""
我曾嘗試先在回圈中執行此操作,然后使用 將串列堆疊起來tf.stack,但這似乎是一種非常非張量流的方式(并且它在 GPU 上不起作用)。我想要的是一種在 Tensorflow 中對幾個批量大小進行上述轉換的方法。這個答案建議使用tf.where,但我也不知道如何在特定情況下利用它。我將不勝感激任何幫助。
uj5u.com熱心網友回復:
假設您擁有的邏輯如圖所示簡單,您可以像這樣切片并直接分配。但是還有其他功能可以做到這一點。
import numpy as np
import tensorflow as tf
tfl_bbox = tf.Variable(tf.zeros([6, 6]))
tfl_score = tf.Variable(tf.zeros([1, 6, 6]))
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
tfl_score[:, y1:y2, x1:x2].assign(tf.ones_like(tf.constant(1,shape=(1,y2-y1,x2-x1)), dtype=tf.float32))
# Create zeros matrices
l_bbox = np.zeros((6,6), np.float32)
l_score = np.zeros((1,6,6), np.float32)
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
l_score[:, y1:y2, x1:x2] = 1.
print(l_score)
print(tfl_score)
"""
array([[[0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]], dtype=float32)
"""
# Assign varying values to l_bbox
for yy in range(y1, y2):
l_bbox[yy, x1:x2] = yy - y1
tfl_bbox[yy, x1:x2].assign(tf.constant(yy - y1,shape=(x2-x1), dtype=tf.float32))
print(l_bbox)
print(tfl_bbox)
"""
array([[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 0.],
[0., 2., 2., 2., 2., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]], dtype=float32)
"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448998.html
上一篇:多維字典到資料框python
下一篇:樹型結構
