**
一 单层单输出感知机梯度计算
**
单层感知机指的是输入有多个节点,输出只有一个节点.
其实质为二分类,即将样本的多个特征值作为输入,输出为二分类.
假设输入有5个样本,每个样本有3个特征参数,样本的标签值为[0,1,0,1,0].
那么x的维度为[5,3],y的维度为[5].
其中感知机参数设置为:w的维度为[3,1],b的维度为[3].
由于为单输出,因此输出层可以使用sigmoid激活函数,且在计算损失值时不需要进行one-hot操作.
import tensorflow as tf
x = tf.Variable(tf.random.normal([5,3]))#5个样本,3个特征参数
y = tf.constant([0,1,0,1,0])#实际标签值
w = tf.Variable(tf.random.normal([3,1]))#3维将为1维
b = tf.Variable(tf.zeros([1]))
with tf.GradientTape() as tape:
logits = x@w + b
out = tf.sigmoid(logits)
loss = tf.reduce_mean(tf.losses.MSE(y,out))
grads = tape.gradient(loss,[w,b])
dw = grads[0]
db = grads[1]
print('dw = ' + str(dw))
print('db = ' + str(db))
dw = tf.Tensor(
[[0.01667164]
[0.06867889]
[0.05850799]], shape=(3, 1), dtype=float32)
db = tf.Tensor([0.06933725], shape=(1,), dtype=float32)
**
二 单层多输出感知机梯度计算
**
多输出实际为多分类问题,如输出层为3个,是将输入的样本分类到3类中,其输出为分类到某一类中的概率,因此这个三个概率的和应该为1.
由于为多输出,则在输出层可以使用softmax激活函数,将所有的概率和置于1.并且在计算损失值时需要使用one-hot操作.
import tensorflow as tf
x = tf.Variable(tf.random.normal([5,8]))#5个样本,8个特征参数
y = tf.constant([0,1,2,1,2])#实际标签值,3类
w = tf.Variable(tf.random.normal([8,3]))#8维将为3维
b = tf.Variable(tf.zeros([3]))
with tf.GradientTape() as tape:
logits = x@w + b#shape = [5,3]
out = tf.nn.softmax(logits,axis=1)
loss = tf.reduce_mean(tf.losses.MSE(tf.one_hot(y,depth=3),out))
grads = tape.gradient(loss,[w,b])
dw = grads[0]
db = grads[1]
print('dw = ' + str(dw))
print('db = ' + str(db))
dw = tf.Tensor(
[[-0.01499876 0.03595395 -0.02095522]
[-0.0262058 0.05820055 -0.03199472]
[-0.02989329 0.01921684 0.01067643]
[ 0.02548018 -0.01658636 -0.00889381]
[ 0.00882134 0.0250744 -0.03389573]
[ 0.01041492 0.02402776 -0.03444269]
[-0.02089255 0.02251757 -0.00162502]
[-0.02010499 0.02840729 -0.00830231]], shape=(8, 3), dtype=float32)
db = tf.Tensor([-0.00130461 0.02544518 -0.02414053], shape=(3,), dtype=float32)