import tensorflow as tf
import numpy as np
tf.set_random_seed(777)
获取数据
x_data = np.array([[0,0,1],[1,0,1],[1,1,1],[0,1,1]])
y_data = np.array([[0],[1],[1],[0]])
测试数据
test_x = [[1,0,0],[0,1,0]]
x = tf.placeholder(tf.float32, [None, 3])
y = tf.placeholder(tf.float32, [None, 1])
w1 = tf.Variable(tf.random_normal([3, 1]), name=‘w1’)
b1 = tf.Variable(tf.random_normal([1]), name=‘b1’)
前向传播
z1 = tf.matmul(x, w1)+b1
a1 = tf.sigmoid(z1)
代价函数
cost = -tf.reduce_mean(y*tf.log(a1)+(1-y)*tf.log(1-a1))
反向传播
dz = a1-y
dw = tf.matmul(tf.transpose(x), dz)/tf.cast(tf.shape(x)[0], tf.float32)
db = tf.reduce_mean(dz, axis=0)
alpha = 0.1
update = [
tf.assign(w1, w1-alphadw),
tf.assign(b1, b1-alphadb)
]
执行会话
sess = tf.Session()
sess.run(tf.global_variables_initializer())
history = []
for i in range(10001):
cost_var, _ = sess.run([cost, update], feed_dict={x:x_data, y:y_data})
if i % 500 == 0:
print(i, cost_var)
history.append(cost_var)
import matplotlib.pyplot as plt
plt.plot(history[1:])
plt.show()
预测值
predict = sess.run(a1, feed_dict={x:test_x})
print(predict)