現在來思考另一個問題:計算一個 0-1 張量,標識輸入張量的每一行的最大元素。
# Input tensor
scores = [[0.7, 0.2, 0.1],
[0.4, 0.5, 0.1],
[0.4, 0.4, 0.2],
[0.3, 0.4, 0.3],
[0.0, 0.0, 1.0]]
# Output tensor
top_scores = [[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]有一點需要注意,如果同一最大元素在一行內多次出現,比如 scores 的第三行,那麼只需要標記第一個此類最大元素,讓 top_scores 的每一行正好有一個 1 的條目。
與上一個問題不同,沒有單個 TensorFlow 函數可以執行此計算。如果在文檔中搜索「max」,可能會發現 tf.reduce_max、tf.argmax 和 tf.maximum 都是相關的,但是應該使用哪一個呢?tf.reduce_max 輸出 [0.7, 0.5, 0.4, 0.4, 1.0],tf.argmax 輸出 [0, 1, 0, 1, 2],而 tf.maximum 不合適,因為它需要兩個參數。這些都不是我們期望的輸出。
TF-Coder 可以幫助解決此類難題。您可以把問題編寫為輸入 - 輸出示例的形式:
# Input-output example
inputs = {
'scores': [[0.7, 0.2, 0.1],
[0.4, 0.5, 0.1],
[0.4, 0.4, 0.2],
[0.3, 0.4, 0.3],
[0.0, 0.0, 1.0]],
}
output = [[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]TF-Coder 組合 tf.one_hot 和 tf.argmax 為這一問題提供了簡潔的解決方案:
tf.cast(tf.one_hot(tf.argmax(scores, axis=1), 3), tf.int32)TF-Coder 詳細搜索 TensorFlow 運算組合後,經常能夠找到這樣的優雅解決方案,讓您的 TensorFlow 程序更精簡、更快速。