Logistic Regression

Logistic Regression

import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset

%matplotlib inline
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()

展示图片

# Example of a picture
index = 100
plt.imshow(train_set_x_orig[index])
print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") +  "' picture.")

张量train_set_x_orig的形状:

(m_train, num_px, num_px, 3)
用例数量*x方向像素数*y方向像素数*3(RGB)

数据集相关信息

### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
### END CODE HERE ###

print ("Number of training examples: m_train = " + str(m_train))
print ("Number of testing examples: m_test = " + str(m_test))
print ("Height/Width of each image: num_px = " + str(num_px))
print ("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print ("train_set_x shape: " + str(train_set_x_orig.shape))
print ("train_set_y shape: " + str(train_set_y.shape))
print ("test_set_x shape: " + str(test_set_x_orig.shape))
print ("test_set_y shape: " + str(test_set_y.shape))

压平+标准化

train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0],-1).T
test_set_x_flatten = test_set_x_orig.reshape(m_test,-1).T

train_set_x = train_set_x_flatten/255.
test_set_x = test_set_x_flatten/255.

sigmoid函数

def sigmoid(z):
	#z为向量
    s = 1/(1+np.exp(-z))
    return s

初始化函数
初始化w,b
dim为图片向量的维数即nx
w为一个nx维的向量,b为一个实数,二者初始化均为0

def initialize_with_zeros(dim):
    w =np.zeros((dim,1))
    b = 0
    assert(w.shape == (dim, 1))
    assert(isinstance(b, float) or isinstance(b, int))
    return w, b

正向传播函数:
参数:
w,b为神经元参量
X矩阵为m组测试用例的合集
Y是答案向量(0/1),用于和Y_hat进行比对
返回:
向量w的变化率dw
b的变化率db
与真实值的差距cost

def propagate(w, b, X, Y):
    m = X.shape[1]#m组用例(nx=X.shape[0])
    A = sigmoid(np.dot(w.T,X)+b)                                    
    cost = 1/(-m)*np.sum(Y*np.log(A)+(1-Y)*np.log(1-A))                              
    dw = 1/m*np.dot(X,(A-Y).T)
    db = 1/m*np.sum(A-Y)
    
    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)
    assert(cost.shape == ())
    grads = {"dw": dw,
             "db": db}
    
    return grads, cost

迭代更新函数

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):
    """
    X -- data of shape (num_px * num_px * 3, number of examples)
    Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
    print_cost -- True to print the loss every 100 steps
    
    Returns:
    params -- dictionary containing the weights w and bias b
    grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
    costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
    """
    
    costs = []
    for i in range(num_iterations):
        grads, cost = propagate(w,b,X,Y)
        dw = grads["dw"]
        db = grads["db"]
        
        w = w-learning_rate*dw
        b = b-learning_rate*db
        
        if i % 100 == 0:
            costs.append(cost)
        
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))
    
    params = {"w": w,
              "b": b}
    
    grads = {"dw": dw,
             "db": db}
    
    return params, grads, costs

预测函数

def predict(w, b, X):
    '''
    Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
    
    Arguments:
    w -- weights, a numpy array of size (num_px * num_px * 3, 1)
    b -- bias, a scalar
    X -- data of size (num_px * num_px * 3, number of examples)
    
    Returns:
    Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
    '''
    
    m = X.shape[1]#m用例个数
    Y_prediction = np.zeros((1,m))#生成一个m维的预测结果行向量
    w = w.reshape(X.shape[0], 1)
    
    A = sigmoid(np.dot(w.T,X)+b)

    for i in range(A.shape[1]):
    #若<=0.5则视为不是猫的图片
        if A[0,i]<=0.5:
            Y_prediction[0,i]=0
        else:
            Y_prediction[0,i]=1
    assert(Y_prediction.shape == (1, m)
    return Y_prediction#返回预测结果向量

完整模型
Builds the logistic regression model by calling the function you’ve implemented previously

Arguments:
X_train -- 训练集矩阵,training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- 训练集答案行向量,training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- 测试集矩阵,test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- 测试集答案行向量,test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- 迭代次数,hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- 学习率,hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations

Returns:
d -- dictionary containing information about the model.
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):
    # 初始化参量
    w, b = initialize_with_zeros(X_train.shape[0])
    # Gradient descent
    parameters, grads, costs = optimize(w,b,X_train,Y_train,num_iterations,learning_rate)
    # 获得训练后的参量w,b
    w = parameters["w"]
    b = parameters["b"]
    # 在测试集、训练集上进行预测
    Y_prediction_test = predict(w,b,X_test)
    Y_prediction_train = predict(w,b,X_train)
    # 打印结果
    print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))

    d = {"costs": costs,
         "Y_prediction_test": Y_prediction_test, 
         "Y_prediction_train" : Y_prediction_train, 
         "w" : w, 
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}
    
    return d

运行模型

d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
内容概要:本文详细介绍了“秒杀商城”微服务架构的设计与实战全过程,涵盖系统从需求分析、服务拆分、技术选型到核心功能开发、分布式事务处理、容器化部署及监控链路追踪的完整流程。重点解决了高并发场景下的超卖问题,采用Redis预减库存、消息队列削峰、数据库乐观锁等手段保障数据一致性,并通过Nacos实现服务注册发现与配置管理,利用Seata处理跨服务分布式事务,结合RabbitMQ实现异步下单,提升系统吞吐能力。同时,项目支持Docker Compose快速部署和Kubernetes生产级编排,集成Sleuth+Zipkin链路追踪与Prometheus+Grafana监控体系,构建可观测性强的微服务系统。; 适合人群:具备Java基础和Spring Boot开发经验,熟悉微服务基本概念的中高级研发人员,尤其是希望深入理解高并发系统设计、分布式事务、服务治理等核心技术的开发者;适合工作2-5年、有志于转型微服务或提升架构能力的工程师; 使用场景及目标:①学习如何基于Spring Cloud Alibaba构建完整的微服务项目;②掌握秒杀场景下高并发、超卖控制、异步化、削峰填谷等关键技术方案;③实践分布式事务(Seata)、服务熔断降级、链路追踪、统一配置中心等企业级中间件的应用;④完成从本地开发到容器化部署的全流程落地; 阅读建议:建议按照文档提供的七个阶段循序渐进地动手实践,重点关注秒杀流程设计、服务间通信机制、分布式事务实现和系统性能优化部分,结合代码调试与监控工具深入理解各组件协作原理,真正掌握高并发微服务系统的构建能力。
### 逻辑回归模型的训练与评估流程 逻辑回归(Logistic Regression)是一种广泛应用于分类任务的线性模型,尤其适用于二分类问题。其核心思想是通过拟合一个 Sigmoid 函数将线性回归的输出映射到 [0, 1] 区间,从而表示样本属于某一类别的概率[^5]。在实际应用中,通常使用 scikit-learn 提供的 `LogisticRegression` 类来实现该模型,并结合 Iris 等标准数据集进行训练和性能评估。 模型构建的基本步骤包括:导入必要的库、加载并预处理数据、划分训练集与测试集、创建逻辑回归实例、执行模型训练、进行预测以及评估模型效果。其中,数据预处理阶段常使用 StandardScaler 对特征进行标准化,以提高模型收敛速度和预测精度。以下是一个典型的代码示例: ```python from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # 加载数据集 iris = load_iris() X, y = iris.data, iris.target # 只保留前两类用于二分类 X = X[y != 2] y = y[y != 2] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 标准化数据 scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) # 创建并训练逻辑回归模型 model = LogisticRegression() model.fit(X_train_scaled, y_train) # 预测与评估 y_pred = model.predict(X_test_scaled) accuracy = accuracy_score(y_test, y_pred) print(f"模型准确率为:{accuracy:.2f}") ``` 上述代码展示了完整的建模流程,从数据准备到模型评估均涵盖在内。值得注意的是,在训练过程中,可以通过设置 `max_iter` 参数控制梯度下降的最大迭代次数,以避免因迭代不足或过长而导致模型无法收敛或计算资源浪费。为了找到最优参数值,可以绘制学习曲线观察不同迭代次数下模型在训练集、验证集和测试集上的表现变化,进而选择合适的配置[^4]。 ### 模型调参与优化策略 除了标准化输入数据外,逻辑回归模型还可以通过正则化方法(如 L1 和 L2 正则化)来防止过拟合。在 scikit-learn 中,`penalty` 参数支持指定 `'l1'` 或 `'l2'`,默认为 `'l2'`。同时,`C` 参数用于控制正则化的强度,较小的 `C` 值意味着更强的正则化效果。此外,求解器的选择(如 `liblinear`、`lbfgs`)也会影响模型的训练效率和稳定性。 在某些应用场景中,例如医疗诊断或电影票房预测,逻辑回归被用来分析多个影响因素对目标变量的影响程度。通过对预算、导演知名度、主演知名度等因素的建模,能够有效预测电影是否具有高票房潜力。类似地,在医学领域,逻辑回归可用于识别疾病的危险因素,并辅助临床决策支持系统做出判断[^3]。 ### 实际应用中的注意事项 尽管逻辑回归模型简单且易于解释,但在使用过程中仍需注意以下几点: - **类别不平衡问题**:当数据集中某一类样本数量远多于另一类时,模型可能会偏向多数类,导致少数类识别率较低。此时可考虑采用过采样、欠采样或加权损失函数等方法缓解此问题。 - **特征相关性**:如果输入特征之间存在高度共线性,可能会影响模型系数估计的稳定性。可通过主成分分析(PCA)等降维手段减少冗余信息。 - **非线性关系处理**:逻辑回归本质上是一个线性模型,对于非线性关系较强的特征组合,建议引入多项式特征或使用更复杂的非线性模型。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值