**
一 单层单输出感知机梯度计算
**
单层感知机指的是输入有多个节点,输出只有一个节点.
其实质为二分类,即将样本的多个特征值作为输入,输出为二分类.
假设输入有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.01