TensorFlow实现逻辑回归-简单案例

import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping

# 生成模拟数据
X = np.random.rand(20000, 2)  # 输入特征,二维向量
y = np.where(X[:, 0] + X[:, 1] > 1.5, 1, 0)  # 输出标签,二分类问题

# 将输入和输出转换为张量
X = tf.convert_to_tensor(X, dtype=tf.float32)
y = tf.convert_to_tensor(y, dtype=tf.float32)

# 定义模型结构
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(2,), activation='sigmoid')  # 全连接层(Dense层)
])

# 编译模型
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])  # 二元交叉熵损失函数 Adam优化器:自适应学习率,对超参数不敏感

# 定义EarlyStopping回调函数
early_stopping = EarlyStopping(monitor='loss', patience=10, min_delta=0.001)

# 训练模型,添加EarlyStopping回调函数
history = model.fit(X, y, epochs=500, batch_size=64, callbacks=[early_stopping])

# 打印训练结果
print("Training accuracy:", max(history.history['accuracy']))
print("Training loss:", min(history.history['loss']))

# 预测新样本
while True:
    x1 = input("x1: ")
    x2 = input("x2: ")

    new_samples = np.array([[float(x1), float(x2)]])
    predictions = model.predict(new_samples)
    threshold = 0.5
    predicted_labels = (predictions >= threshold).astype(int)
    print("Predicted labels for new samples:", predicted_labels)
    print("Predictions for new samples:", predictions)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值