tensorflow--平均二乗誤差(MSE、平均二乗誤差)表現方法
Tensorflow Mean Square Error Mse
次のように、2つの3×3アレイを検討します。これは2つの3×3画像として理解できます。
a = tf.constant([[4.0, 4.0, 4.0], [3.0, 3.0, 3.0], [1.0, 1.0, 1.0]]) b = tf.constant([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]) print(a) print(b)
上に印刷された結果は次のとおりです。
Tensor('Const_16:0', shape=(3, 3), dtype=float32) Tensor('Const_17:0', shape=(3, 3), dtype=float32)
特定の配列のような値を取得する場合は、sess.runを使用する必要があります。
with tf.Session() as sess: print(sess.run(a)) print(sess.run(b))
取得する:
[[4. 4. 4.] [3. 3. 3.] [1. 1. 1.]] [[1. 1. 1.] [1. 1. 1.] [2. 2. 2.]]
以下では、3つの方法を使用して、これら2つの配列の平均二乗誤差(MSE、平均二乗誤差)を計算します。具体的な式は、次のとおりです。
1. tf.square()とtf.reduce_mean()の組み合わせ
c = tf.square(a - b) mse = tf.reduce_mean(c) with tf.Session() as sess: print(sess.run(c)) print(sess.run(mse))
[[9. 9. 9.] [4. 4. 4.] [1. 1. 1.]] 4.6666665
上記は、cテンソルの配列結果です。 mseの結果は4.6666665です。 42の合計を手動で計算し、それを要素の数で割ります。結果もこれです。
tf.square(a-b)は、配列aから配列bを減算した後、取得した配列のすべての要素を2乗することです。 tf.reduce_mean(c)、ディメンションが指定されていない場合は、すべての要素を平均します。具体的な使用法は次のとおりです。 https://blog.csdn.net/qq_32166627/article/details/52734387
2.tf.nn.l2_loss()
tf.nn.l2_loss(t)の具体的な計算は、sum(t ** 2)/ 2であり、これはtf.square(t)の2倍に相当します。次に、mseを計算するための使用法は次のとおりです。
mse1 = (2.0/9)*tf.nn.l2_loss(a - b) # sum(t ** 2) / 2 with tf.Session() as sess: print(sess.run(mse1))
結果は4.6666665になることもあります。
3. tf.losses.mean_squared_error()
tf.losses.mean_squared_error()は、mse値を直接計算するためのものです。
mse2 = tf.losses.mean_squared_error(a, b) with tf.Session() as sess: print(sess.run(mse2))
結果は4.6666665です。