德国面试官-单层神经网络

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-alpha
db)
]

执行会话

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值