二元逻辑回归在分类中的应用分析

版权申诉
0 下载量 47 浏览量 更新于2024-10-14 收藏 1KB ZIP 举报
在数据科学和机器学习领域,Logistic回归是一种广泛使用的分类算法。它主要应用于二分类问题,即将输入数据根据某种标准分为两类。Logistic回归模型的输出是属于某一类的概率估计,通常是使用sigmoid函数(或称为logistic函数)将线性组合的结果映射到(0, 1)区间内。 本资源提供了一个名为“demo_logistic.m”的文件,它是用MATLAB语言编写的一个演示程序,目的是说明如何使用Logistic回归算法来处理二维(2D)的离散数据集,并将其分为两类。下面将详细介绍Logistic回归的相关知识点,并对本资源的使用场景和步骤进行解读。 ### Logistic回归基本原理 Logistic回归是一种概率型分类方法,它使用逻辑函数(通常指sigmoid函数)来预测离散型输出。sigmoid函数的表达式如下: $$ \sigma(z) = \frac{1}{1 + e^{-z}} $$ 其中,$e$是自然对数的底数,$z$是输入特征的线性组合,即$z = w_0 + w_1x_1 + w_2x_2 + \ldots + w_nx_n$。这里的$w_i$是模型的权重参数,$x_i$是特征变量。 在Logistic回归模型中,通过学习训练数据集来拟合参数$w_i$,使得模型能够根据新的输入数据预测出属于某一类的概率。在二分类问题中,如果$\sigma(z) > 0.5$,则将输入数据预测为正类(1),反之预测为负类(0)。 ### 使用Logistic回归处理2D数据 在二维空间中,使用Logistic回归对离散数据进行分类,通常涉及到以下步骤: 1. **数据准备**:首先需要收集并准备好二维特征空间中的离散数据。数据通常包含两个特征,并且每条数据记录都带有对应的分类标签(0或1)。 2. **模型构建**:使用Logistic函数构建分类模型。在MATLAB中,这个过程可以通过定义sigmoid函数来实现,并编写相应的线性回归方程。 3. **参数估计**:通过最大似然估计(MLE)等方法对模型参数进行估计。在本资源中,这一步骤可能通过demo_logistic.m文件中的代码来实现,通过输入数据集来学习模型权重。 4. **模型训练**:根据估计的参数,使用训练数据来训练模型。这涉及到在特征空间中找到一个决策边界,该边界尽可能准确地区分开两类数据。 5. **分类预测**:在模型训练完成后,可以使用学习到的模型对新的数据点进行分类预测。模型将输出一个介于0和1之间的概率值,表明数据点属于某一类的可能性。 6. **结果评估**:通过比较预测标签与实际标签来评估模型的性能。通常会使用混淆矩阵、准确率、精确率、召回率等指标来量化模型的分类效果。 ### MATLAB中的实现 在MATLAB环境中实现Logistic回归,demo_logistic.m文件可能包含以下内容: 1. **数据加载**:载入二维数据集,准备进行分类。 2. **特征映射**:将数据集中的特征映射到Logistic函数中。 3. **参数优化**:使用MATLAB提供的优化工具箱或编写自定义算法来优化模型参数。 4. **决策边界绘制**:绘制通过数据集确定的决策边界,可视化模型分类的效果。 5. **预测与评估**:利用训练好的模型进行分类预测,并评估模型效果。 通过这些步骤,用户可以直观地看到Logistic回归如何将一个线性模型应用于二维分类问题,并通过调整模型参数来优化分类性能。通过本资源,学习者可以加深对Logistic回归算法的理解,并掌握如何在MATLAB中实现并应用该算法。

把这段代码的PCA换成LDA:LR_grid = LogisticRegression(max_iter=1000, random_state=42) LR_grid_search = GridSearchCV(LR_grid, param_grid=param_grid, cv=cvx ,scoring=scoring,n_jobs=10,verbose=0) LR_grid_search.fit(pca_X_train, train_y) estimators = [ ('lr', LR_grid_search.best_estimator_), ('svc', svc_grid_search.best_estimator_), ] clf = StackingClassifier(estimators=estimators, final_estimator=LinearSVC(C=5, random_state=42),n_jobs=10,verbose=1) clf.fit(pca_X_train, train_y) estimators = [ ('lr', LR_grid_search.best_estimator_), ('svc', svc_grid_search.best_estimator_), ] param_grid = {'final_estimator':[LogisticRegression(C=0.00001),LogisticRegression(C=0.0001), LogisticRegression(C=0.001),LogisticRegression(C=0.01), LogisticRegression(C=0.1),LogisticRegression(C=1), LogisticRegression(C=10),LogisticRegression(C=100), LogisticRegression(C=1000)]} Stacking_grid =StackingClassifier(estimators=estimators,) Stacking_grid_search = GridSearchCV(Stacking_grid, param_grid=param_grid, cv=cvx, scoring=scoring,n_jobs=10,verbose=0) Stacking_grid_search.fit(pca_X_train, train_y) Stacking_grid_search.best_estimator_ train_pre_y = cross_val_predict(Stacking_grid_search.best_estimator_, pca_X_train,train_y, cv=cvx) train_res1=get_measures_gridloo(train_y,train_pre_y) test_pre_y = Stacking_grid_search.predict(pca_X_test) test_res1=get_measures_gridloo(test_y,test_pre_y) best_pca_train_aucs.append(train_res1.loc[:,"AUC"]) best_pca_test_aucs.append(test_res1.loc[:,"AUC"]) best_pca_train_scores.append(train_res1) best_pca_test_scores.append(test_res1) train_aucs.append(np.max(best_pca_train_aucs)) test_aucs.append(best_pca_test_aucs[np.argmax(best_pca_train_aucs)].item()) train_scores.append(best_pca_train_scores[np.argmax(best_pca_train_aucs)]) test_scores.append(best_pca_test_scores[np.argmax(best_pca_train_aucs)]) pca_comp.append(n_components[np.argmax(best_pca_train_aucs)]) print("n_components:") print(n_components[np.argmax(best_pca_train_aucs)])

2023-07-22 上传

报错ValueError: np.nan is an invalid document, expected byte or unicode string. 怎么修改import pandas as pd from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # 读取电影评论数据集 data = pd.read_csv(r'D:\shujukexue\review_data.csv', encoding='gbk') x = v.fit_transform(df['eview'].apply(lambda x: np.str_(x))) # 分割数据集为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(data['review'], data['sentiment'], test_size=0.2, random_state=42) # 创建CountVectorizer对象进行词频统计和向量化 count_vectorizer = CountVectorizer() X_train_count = count_vectorizer.fit_transform(X_train) X_test_count = count_vectorizer.transform(X_test) # 创建TfidfVectorizer对象进行TF-IDF计算和向量化 tfidf_vectorizer = TfidfVectorizer() X_train_tfidf = tfidf_vectorizer.fit_transform(X_train) X_test_tfidf = tfidf_vectorizer.transform(X_test) # 创建逻辑回归分类器并在CountVectorizer上进行训练和预测 classifier_count = LogisticRegression() classifier_count.fit(X_train_count, y_train) y_pred_count = classifier_count.predict(X_test_count) accuracy_count = accuracy_score(y_test, y_pred_count) print("Accuracy using CountVectorizer:", accuracy_count) # 创建逻辑回归分类器并在TfidfVectorizer上进行训练和预测 classifier_tfidf = LogisticRegression() classifier_tfidf.fit(X_train_tfidf, y_train) y_pred_tfidf = classifier_tfidf.predict(X_test_tfidf) accuracy_tfidf = accuracy_score(y_test, y_pred_tfidf) print("Accuracy using TfidfVectorizer:", accuracy_tfidf)

359 浏览量

优化这段代码 for j in n_components: estimator = PCA(n_components=j,random_state=42) pca_X_train = estimator.fit_transform(X_standard) pca_X_test = estimator.transform(X_standard_test) cvx = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) cost = [-5, -3, -1, 1, 3, 5, 7, 9, 11, 13, 15] gam = [3, 1, -1, -3, -5, -7, -9, -11, -13, -15] parameters =[{'kernel': ['rbf'], 'C': [2x for x in cost],'gamma':[2x for x in gam]}] svc_grid_search=GridSearchCV(estimator=SVC(random_state=42), param_grid=parameters,cv=cvx,scoring=scoring,verbose=0) svc_grid_search.fit(pca_X_train, train_y) param_grid = {'penalty':['l1', 'l2'], "C":[0.00001,0.0001,0.001, 0.01, 0.1, 1, 10, 100, 1000], "solver":["newton-cg", "lbfgs","liblinear","sag","saga"] # "algorithm":['auto', 'ball_tree', 'kd_tree', 'brute'] } LR_grid = LogisticRegression(max_iter=1000, random_state=42) LR_grid_search = GridSearchCV(LR_grid, param_grid=param_grid, cv=cvx ,scoring=scoring,n_jobs=10,verbose=0) LR_grid_search.fit(pca_X_train, train_y) estimators = [ ('lr', LR_grid_search.best_estimator_), ('svc', svc_grid_search.best_estimator_), ] clf = StackingClassifier(estimators=estimators, final_estimator=LinearSVC(C=5, random_state=42),n_jobs=10,verbose=0) clf.fit(pca_X_train, train_y) estimators = [ ('lr', LR_grid_search.best_estimator_), ('svc', svc_grid_search.best_estimator_), ] param_grid = {'final_estimator':[LogisticRegression(C=0.00001),LogisticRegression(C=0.0001), LogisticRegression(C=0.001),LogisticRegression(C=0.01), LogisticRegression(C=0.1),LogisticRegression(C=1), LogisticRegression(C=10),LogisticRegression(C=100), LogisticRegression(C=1000)]} Stacking_grid =StackingClassifier(estimators=estimators,) Stacking_grid_search = GridSearchCV(Stacking_grid, param_grid=param_grid, cv=cvx, scoring=scoring,n_jobs=10,verbose=0) Stacking_grid_search.fit(pca_X_train, train_y) var = Stacking_grid_search.best_estimator_ train_pre_y = cross_val_predict(Stacking_grid_search.best_estimator_, pca_X_train,train_y, cv=cvx) train_res1=get_measures_gridloo(train_y,train_pre_y) test_pre_y = Stacking_grid_search.predict(pca_X_test) test_res1=get_measures_gridloo(test_y,test_pre_y) best_pca_train_aucs.append(train_res1.loc[:,"AUC"]) best_pca_test_aucs.append(test_res1.loc[:,"AUC"]) best_pca_train_scores.append(train_res1) best_pca_test_scores.append(test_res1) train_aucs.append(np.max(best_pca_train_aucs)) test_aucs.append(best_pca_test_aucs[np.argmax(best_pca_train_aucs)].item()) train_scores.append(best_pca_train_scores[np.argmax(best_pca_train_aucs)]) test_scores.append(best_pca_test_scores[np.argmax(best_pca_train_aucs)]) pca_comp.append(n_components[np.argmax(best_pca_train_aucs)]) print("n_components:") print(n_components[np.argmax(best_pca_train_aucs)])

112 浏览量