import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt 
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
x = np.array([1.0,2.0,3.0,4.0])
w = tf.Variable(1.)
b = tf.Variable(1.)
print(1/(1+tf.exp(-(w*x+b))))

y = np.array([0,0,1,1])
pred = np.array([0.1,0.2,0.8,0.49])
Loss = -tf.reduce_sum(y*tf.math.log(pred)+(1-y)*tf.math.log(1-pred))
ar_Loss = -tf.reduce_mean(y*tf.math.log(pred)+(1-y)*tf.math.log(1-pred))
print('loss: ',Loss)
print('arevage loss: ',ar_Loss)

# tf.where(condition, a, b) ab形状相同,省略ab则返回满足条件的下标
print('where: ',tf.where(pred<0.5, 0,1))
# 四舍五入
print('round: ',tf.round(pred))
# 按位比较
print('equal: ',tf.equal(tf.round(pred), y))
# 转化为整形
print('cast to int: ',tf.cast(tf.equal(tf.round(pred), y), tf.int8))
# 取均值
print('get mean: ',tf.reduce_mean(tf.cast(tf.equal(tf.round(pred), y), tf.float32)))
# 分界线
print('-'*50)
# ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
 
# 引入数据
x = np.array([137.97,104.50,100.00,142.32,79.20,99.00,124.00,114.00,106.96,139.02,53.75,46.91,68.00,63.02,81.26,86.21, 100.00])
y = np.array([1,1,0,1,0,1,1,0,0,1,0,0,0,0,0,0,1])
# print(len(x),len(y))
# plt.figure()
# plt.scatter(x,y)
x_train = x-np.mean(x)
y_train = y
# plt.figure()
# plt.scatter(x_train, y_train)
# plt.show()

learn_rate = 0.005
iter=50
display_step = 1

# 获取初始模型参数
np.random.seed(612)
w = tf.Variable(np.random.randn())
b = tf.Variable(np.random.randn())

# 用于绘制使用初始模型参数的曲线
x_ = range(-80,80)
y_ = 1/(1+tf.exp(-(w*x_+b)))

plt.figure()
plt.scatter(x_train, y_train) # 绘制样本点
plt.plot(x_, y_, color='red',linewidth=3,label='begin line')
plt.legend()

cross_train = [] # 存放交叉熵损失
acc_train = [] # 存放分类准确率

for i in range(0, iter+1):
    with tf.GradientTape() as tape:
        pred_train = 1/(1+tf.exp(-(w*x_train+b)))
        # 计算loss,公式见笔记
        Loss_train = -tf.reduce_mean(y_train*tf.math.log(pred_train)+(1-y_train)*tf.math.log(1-pred_train))
        # 计算准确度
        Acc_train = tf.reduce_mean(tf.cast(tf.equal(tf.where(pred_train<0.5, 0, 1),y_train),tf.float32))

    cross_train.append(Loss_train)
    acc_train.append(Acc_train)

    # 获取偏导
    dl_dw, dl_db = tape.gradient(Loss_train , [w, b]) 

    # 更新模型参数
    w.assign_sub(learn_rate*dl_dw)
    b.assign_sub(learn_rate*dl_db)

    if i % display_step == 0:
        print('i:%i, train loss: %f, accuracy: %f'%(i, Loss_train, Acc_train))
        y_ = 1/(1+tf.exp(-(w*x_+b))) # 用于绘制使用变化中的模型参数的曲线
        plt.plot(x_, y_)
        
plt.show()
结果: