(21)tensorflow误差计算

误差计算

均方差误差MSE

M S E ( y , o ) = 1 n ∑ i = 1 n ( y i − o i ) 2 MSE(y,o)=\cfrac{1}{n}\displaystyle\sum_{i=1}^n(y_i-o_i)^2\\ MSE(y,o)=n1i=1n(yioi)2

import tensorflow as tf
o = tf.random.normal([2,10])
y = tf.constant([1,3])
print(y)
y = tf.one_hot(y,depth=10)
print(y)
loss = tf.keras.losses.mse(y,o)#按照样本计算
print(loss)
loss = tf.reduce_mean(loss)
print(loss)

out:
tf.Tensor([1 3], shape=(2,), dtype=int32)
tf.Tensor(
[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]], shape=(2, 10), dtype=float32)
tf.Tensor([1.4299054 1.1418271], shape=(2,), dtype=float32)
tf.Tensor(1.2858663, shape=(), dtype=float32)
#类方法
import tensorflow as tf
o = tf.random.normal([2,10])
y = tf.constant([1,3])
print(y)
y = tf.one_hot(y,depth=10)
print(y)
loss = tf.keras.losses.MeanSquaredError()
mse = loss(y,o)
print(mse)

out:
tf.Tensor([1 3], shape=(2,), dtype=int32)
tf.Tensor(
[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]], shape=(2, 10), dtype=float32)
tf.Tensor(0.6200963, shape=(), dtype=float32)

交叉熵误差

H ( p ∣ ∣ q ) = − l o g 2 ( o i ) H(p||q)=-log_2(o_i) H(pq)=log2(oi)

  • 其中𝑖为 One-hot 编码中为 1 的索引号,也是当前输入的真实类别。可以看到, H只与真实类别𝑖上的概率𝑜𝑖有关, 对应概率𝑜𝑖越大, 𝐻(𝑝||𝑞)越小。 当对应类别上的概率为 1 时, 交叉熵𝐻(𝑝||𝑞)取得最小值 0,此时网络输出𝒐与真实标签𝒚完全一致,神经网络取得最优状态。
posted @ 2020-09-05 11:05  kuanleung  阅读(17)  评论(0)    收藏  举报  来源