tensorflow系列教程之八:逻辑回归-分类

In [30]:
#导入相应的包
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

#定义sigmod函数
def sigmoid(x):
    return 1. / (1. + np.exp(-x))
#定义红色分类的点
red_x = np.random.normal(2, 1, 1000)
red_y = np.random.normal(3, 1, 1000)
#定义绿色分类的点
green_x = np.random.normal(8, 1, 1000)
green_y = np.random.normal(9, 1, 1000) 
x1s = np.append(red_x, green_x)
x2s = np.append(red_y, green_y)
ys = np.asarray([0.] * len(red_x) + [1.] * len(green_x))

X1 = tf.placeholder(tf.float32, shape=(None,), name="x1") 
X2 = tf.placeholder(tf.float32, shape=(None,), name="x2") 
Y = tf.placeholder(tf.float32, shape=(None,), name="y") 
w = tf.Variable([0., 0., 0.], name="w", trainable=True)

learning_rate = 0.1#学习率
training_epochs = 2000#训练次数
#定义模型
y_model = tf.sigmoid(w[2] * X2 + w[1] * X1 + w[0]) 
#定义损失函数
cost = tf.reduce_mean(-tf.log(y_model * Y + (1 - y_model) * (1 - Y)))
#定义训练模型
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 
with tf.Session() as sess:
    #初始化变量
    sess.run(tf.global_variables_initializer())
    prev_err = 0 
    for epoch in range(training_epochs):
        err, _ = sess.run([cost, train_op], {X1: x1s, X2: x2s, Y: ys}) 
#         print(epoch, err) 
        if abs(prev_err - err) < 0.0001: 
            break
        prev_err = err 
    w_val = sess.run(w, {X1: x1s, X2: x2s, Y: ys})

x1_boundary, x2_boundary = [], [] 
for x1_test in np.linspace(0, 10, 100): 
    for x2_test in np.linspace(0, 10, 100): 
        z = sigmoid(-x2_test*w_val[2] - x1_test*w_val[1] - w_val[0]) 
        if abs(z - 0.5) < 0.01: 
            x1_boundary.append(x1_test) 
            x2_boundary.append(x2_test)

plt.scatter(x1_boundary, x2_boundary, c='b', marker='o', s=20) 
plt.scatter(red_x, red_y, c='r', marker='x', s=20)
plt.scatter(green_x, green_y, c='g', marker='1', s=20) 
plt.show()