【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)
相关推荐
故事和你9117 小时前
sdut-程序设计基础Ⅰ-实验五一维数组(8-13)
开发语言·数据结构·c++·算法·蓝桥杯·图论·类和对象
像污秽一样17 小时前
算法与设计与分析-习题4.2
算法·排序算法·深度优先·dfs·bfs
Storynone18 小时前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
明明如月学长19 小时前
AI 更新太快学不过来?我用OpenClaw打造专属AI学习工作流
算法
黎阳之光19 小时前
【黎阳之光:以无线专网与视频孪生,赋能智慧广电与数字中国】
算法·安全·智慧城市·数字孪生
刀法如飞20 小时前
Agentic AI时代,程序员必备的算法思想指南
人工智能·算法·agent
刀法如飞20 小时前
Agentic AI时代程序员必备算法思想详解(附实战案例)
算法·ai编程·编程开发·agentic
飞Link21 小时前
告别盲目找Bug:深度解析 TSTD 异常检测中的预测模型(Python 实战版)
开发语言·python·算法·bug
记忆多21 小时前
c++名字空间 函数模版 左右值
开发语言·c++·算法
三伏52221 小时前
控制理论前置知识——相平面数学基础2(示例部分)
算法·平面·控制