【LR逻辑回归】原理以及tensorflow实现

LR 将所有输入特征进行线性组合,通过 Sigmoid 函数将结果压缩到 (0, 1) 区间,输出概率

LR 仅做了一阶特征的线性加权,特征之间是相互独立的

python 复制代码
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 1. 模拟生成推荐场景的点击数据
def generate_mock_data(n_samples=5000, n_features=20):
    # 随机生成特征矩阵 X
    X = np.random.randn(n_samples, n_features)
    # 模拟一个真实的线性关系加上一点随机扰动
    # 假设真实的权重是固定的,y = sigmoid(X * weights + bias)
    true_weights = np.random.randn(n_features, 1)
    logits = np.dot(X, true_weights) + 0.5
    # 将连续值转为 0/1 标签(点击或未点击)
    y = (1 / (1 + np.exp(-logits)) > 0.5).astype(int)
    return X, y

# --- 准备数据 ---
X, y = generate_mock_data()
# 划分训练集和测试集(80% 训练,20% 测试)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# 特征标准化(工程必备:让梯度下降更平稳)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 2. 构建模型 (The "Body")
model = tf.keras.Sequential([
    # input_shape 对应特征维度
    tf.keras.layers.Dense(units=1, activation='sigmoid', input_shape=(20,))
])
#unit为输出的节点数,w的形状为(20,1)

# 3. 编译模型 (The "Soul")
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
    loss='binary_crossentropy',
    metrics=['accuracy', tf.keras.metrics.AUC(name='auc')]
)

# 4. 启动训练 (The "Action")
# fit 函数会让数据在计算图中循环运行
print("--- 开始训练 ---")
history = model.fit(
    X_train, y_train, 
    epochs=20,           # 整个数据集跑 20 遍
    batch_size=32,       # 每次喂 32 条数据进行梯度更新
    validation_split=0.1 # 从训练集里抽 10% 做实时监控
)

# 5. 测试与评估 (The "Audit")
print("\n--- 测试集评估 ---")
results = model.evaluate(X_test, y_test)
print(f"测试集准确率: {results[1]:.4f}, AUC: {results[2]:.4f}")

# 6. 预测 (The "Prediction")
# 模拟对前 5 个新用户进行点击率预测
sample_preds = model.predict(X_test[:5])
print("\n前5个样本的点击预测概率:\n", sample_preds)
相关推荐
OOJO11 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
别或许13 小时前
1、高数----函数极限与连续(知识总结)
算法
田梓燊13 小时前
code 560
数据结构·算法·哈希算法
笨笨饿13 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu13 小时前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
weixin_4130632113 小时前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
会编程的土豆14 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
炘爚14 小时前
深入解析printf缓冲区与fork进程复制机制
linux·运维·算法
迈巴赫车主15 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
6Hzlia15 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode