尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

机械学习-逻辑回归

机械学习-逻辑回归 逻辑回归原理1逻辑回归是做分类的且是二分类0/1不是回归2为什么不用线性代数3.Sigmoid函数4.逻辑回归公式5.损失函数线性回归用MSE 均方误差逻辑回归不能用容易梯度下降进入局部最优解6.样本损失7.梯度下降求解权重逻辑回归API所有默认值fromsklearn.linear_modelimportLogisticRegression LogisticRegression(penaltyl2,#可选用l1/l2#L2 正则权重衰减让参数尽量小防止过拟合#L1 正则可以把不重要特征权重压缩到 0实现特征筛选#elasticnet弹性网 L1L2 混合正则需要配合l1_ratio#None没有任何正则dualFalse,#是否使用对偶形式对偶形式只在liblinear 求解器 L2 正则时生效当样本数 特征数可以开True加速样本远大于特征保持 False。tol1e-4,#迭代时如果损失函数变化量小于 tol判定为收敛停止迭代调大 tol → 提早停止速度快调小 tol → 迭代更充分训练慢。C1.0,#**正则化强度的倒数**C越小正则化越强C越大正则越弱C0.1强正则压制参数抑制过拟合C100弱正则几乎不约束参数。fit_interceptTrue,#默认True模型会增加截距项 bintercept_scaling1,#仅 solverliblinear且 fit_interceptTrue 才生效class_weightNone,#类别权重解决样本不平衡random_stateNone,#随机种子solverlbfgs,#优化求解器#lbfgs支持l2、None中小数据集多分类首选#liblinear支持l1,l2小数据集二分类#sag支持l2、None大数据集梯度下降速度快#saga支持l1/l2/elasticnet大数据支持弹性网正则max_iter100,#最大迭代次数multi_classauto,verbose0,#默认 0不输出日志0 输出训练迭代日志。调试用。warm_startFalse,#热启动True复用上一次.fit()训练得到的参数作为本次训练初始值。n_jobsNone,#默认None‑1代表使用全部 CPU 核心仅在多分类 ovr 模式下多个二分类任务可以并行加速liblinear 求解器不生效。l1_ratioNone#ElasticNet 混合系数仅当penaltyelasticnet才生效取值范围[0,1]#l1_ratio0 →等价 L2 正则#l1_ratio1 →等价 L1 正则#0~1 之间L1 和 L2 混合。)模型属性model.coef_ 特征权重系数shape(n_classes, n_features)model.intercept_ 截距项 bmodel.classes_ 标签类别数组model.n_iter_ 实际迭代轮数逻辑回归代码importpandasaspdimportnumpyasnp# 绘制可视化混淆矩阵defcm_plot(y,yp):fromsklearn.metricsimportconfusion_matriximportmatplotlib.pyplotasplt cmconfusion_matrix(y,yp)plt.matshow(cm,cmapplt.cm.Blues)plt.colorbar()forxinrange(len(cm)):foryinrange(len(cm)):plt.annotate(cm[x,y],(x,y),horizontalalignmentcenter,verticalalignmentcenter)plt.ylabel(True label)plt.xlabel(Predicted label)returnplt第一步数据预处理datapd.read_csv(C:\\Users\\futingjian\\PycharmProjects\\futingjian\\AI\\逻辑回归\\creditcard.csv)数据标准化Z标准化fromsklearn.preprocessingimportStandardScaler scalerStandardScaler()adata[[Amount]]data[[Amount]]scaler.fit_transform(data[[Amount]])datadata.drop([Time],axis1)#分开测试集和训练集fromsklearn.model_selectionimporttrain_test_split xdata.drop(Class,axis1)ydata.Classx_train,x_test,y_train,y_testtrain_test_split(x,y,test_size0.2,random_state1234)#交叉验证fromsklearn.linear_modelimportLinearRegression,LogisticRegression lr.fit(x_train,y_train)fromsklearnimportmetrics train_predictedlr.predict(x_train)print(metrics.classification_report(y_train,train_predicted))cm_plot(y_train,train_predicted).show()# 使用测试集测试test_predictedlr.predict(x_test)print(metrics.classification_report(y_test,test_predicted,digits6))cm_plot(y_test,test_predicted).show()
返回列表