TensorFlow2.0:单层感知机梯度计算

**

一 单层单输出感知机梯度计算

**
在这里插入图片描述
单层感知机指的是输入有多个节点,输出只有一个节点.
其实质为二分类,即将样本的多个特征值作为输入,输出为二分类.
假设输入有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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值