感知机
单层感知机模型
是对n个输入元素,加权求和,再与阈值进行比较,再经过一个符号函数,得到模型的输出。
感知机模型
H
(
x
)
=
s
i
g
n
(
w
T
x
+
b
)
H(x)=sign(w^Tx+b)
H(x)=sign(wTx+b)训练时要在二维空间中找到一个超平面
S
(
w
T
x
+
b
)
S(w^Tx+b)
S(wTx+b),即一条直线,找到合适的模型参数(w,b)j将样本点正确分为两类。
网络结构:
举个例子:模拟布尔函数的感知机(也就是输入全为0或1)
这样就可以找的一种模型得到结果。
感知机模型的训练:
- 定义一个合适的损失函数
- 最小化损失函数
- 获得模型最优参数
损失函数 L ( w ) = f ( y , y ) L(w)=f(y^,y) L(w)=f(y,y)
最终要使得损失函数最小,使用梯度下降法:
1) 给定初始参数向量W,如随机向量,计算损失函数对w的偏导(即梯度)
2) 沿负梯度方向按照一定的步长(学习率)η调整参数的值,进行迭代,使L(w)的值不断变小。
a.均方差损失函数:
b.交叉熵损失函数:
c.距离损失函数:
损失函数:误分类的点到超平面S的总距离。
感知机在tensorflow框架下的实现代码:
import tensorflow as tf
import numpy as np
x_data = np.array([[0,0],[0,1],[1,0],[1,1]],dtype=np.float32)
y_data = np.array([[0],[1],[1],[1]],dtype=np.float32)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
W = tf.Variable(tf.random_normal([2,1]),name='weight')
b = tf.Variable(tf.random_normal([1]),name='bias')
#感知机模型
hypothesis = tf.sigmoid(tf.matmul(X,W)+b)
#损失函数,二分类
cost = -tf.reduce_mean(Y*tf.log(hypothesis)+(1-Y)*tf.log(1-hypothesis))
#梯度下降训练
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)
#模型输出
predicted = tf.cast(hypothesis>=0.5,dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted,Y),dtype=tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(8001):
sess.run(train,feed_dict={X:x_data,Y:y_data})
if step % 100 ==0:
print(step,sess.run(cost,feed_dict={X:x_data,Y:y_data}),sess.run(W))
h,c,a = sess.run([hypothesis,predicted,accuracy],
feed_dict={X:x_data,Y:y_data})
print("\nHypothesus:",h,"\nCorrect:",c,"\nAccuracy:",a)
输出结果:
Hypothesus: [[0.19380988]
[0.92346996]
[0.9264078 ]
[0.9984199 ]]
Correct: [[0.]
[1.]
[1.]
[1.]]
Accuracy: 1.0
后续补充。