用tensorflow写逻辑回归的代码
时间: 2023-12-17 18:12:36 浏览: 62
import tensorflow as tf
import numpy as np
# 定义训练数据及标签
train_data = np.array([[0,0],[0,1],[1,0],[1,1]])
train_label = np.array([[0],[0],[0],[1]])
# 定义模型
x = tf.placeholder(tf.float32, shape=[None, 2])
y = tf.placeholder(tf.float32, shape=[None, 1])
W = tf.Variable(tf.zeros([2, 1]))
b = tf.Variable(tf.zeros([1]))
pred = tf.sigmoid(tf.matmul(x, W) + b)
# 定义损失函数
cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred) + (1 - y) * tf.log(1 - pred), axis=1))
# 定义优化器
optimizer = tf.train.GradientDescentOptimizer(0.1).minimize(cost)
# 进行训练
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(1000):
_, c = sess.run([optimizer, cost], feed_dict={x: train_data, y: train_label})
if epoch % 100 == 0:
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
pred_y = sess.run(pred, feed_dict={x: train_data})
correct_prediction = tf.equal(tf.round(pred_y), y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: train_data, y: train_label}))
阅读全文