search
HomeBackend DevelopmentPython TutorialIntroduction to Python's sklearn machine learning algorithm

Introduction to Python's sklearn machine learning algorithm

Free learning recommendations: python video tutorial

Import necessary common modules

import pandas as pdimport matplotlib.pyplot as pltimport osimport numpy as npimport copyimport reimport math

One general framework for machine learning: taking knn as an example

#利用邻近点方式训练数据不太适用于高维数据from sklearn.model_selection import train_test_split#将数据分为测试集和训练集from sklearn.neighbors import KNeighborsClassifier#利用邻近点方式训练数据#1.读取数据data=pd.read_excel('数据/样本数据.xlsx')#2.将数据标准化from sklearn import preprocessingfor col in data.columns[2:]:#为了不破坏数据集中的离散变量,只将数值种类数高于10的连续变量标准化
       if len(set(data[col]))>10:
              data[col]=preprocessing.scale(data[col])#3.构造自变量和因变量并划分为训练集和测试集X=data[['month_income','education_outcome','relationship_outcome', 'entertainment_outcome','traffic_', 'express',
       'express_distance','satisfac', 'wifi_neghbor','wifi_relative', 'wifi_frend', 'internet']]y=data['wifi']X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)#利用train_test_split进行将训练集和测试集进行分开,test_size占30%#4.模型拟合model=KNeighborsClassifier()#引入训练方法model.fit(X_train,y_train)#进行填充测试数据进行训练y_predict=model.predict(X_test)#利用测试集数据作出预测#通过修改判别概率标准修改预测结果proba=model.predict_proba(X_test)#返回基于各个测试集样本所预测的结果为0和为1的概率值#5.模型评价#(1)测试集样本数据拟合优度,model.score(X,y)model.score(X_test,y_test)#(2)构建混淆矩阵,判断预测精准程度"""
混淆矩阵中行代表真实值,列代表预测值
TN:实际为0预测为0的个数       FP:实际为0预测为1的个数
FN:实际为1预测为0的个数       TP:实际为1预测为1的个数

精准率precision=TP/(TP+FP)——被预测为1的样本的的预测正确率
召回率recall=TP/(TP+FN)——实际为1的样本的正确预测率
"""from sklearn.metrics import confusion_matrix
cfm=confusion_matrix(y_test, y_predict)plt.matshow(cfm,cmap=plt.cm.gray)#cmap参数为绘制矩阵的颜色集合,这里使用灰度plt.show()#(3)精准率和召回率from sklearn.metrics import precision_score,recall_score
precision_score(y_test, y_predict)# 精准率recall_score(y_test, y_predict)#召回率#(4)错误率矩阵row_sums = np.sum(cfm,axis=1)err_matrix = cfm/row_sums
np.fill_diagonal(err_matrix,0)#对err_matrix矩阵的对角线置0,因为这是预测正确的部分,不关心plt.matshow(err_matrix,cmap=plt.cm.gray)#亮度越高的地方代表错误率越高plt.show()

Second data processing

#1.构造数据集from sklearn import datasets#引入数据集#n_samples为生成样本的数量,n_features为X中自变量的个数,n_targets为y中因变量的个数,bias表示使线性模型发生偏差的程度,X,y=datasets.make_regression(n_samples=100,n_features=1,n_targets=1,noise=1,bias=0.5,tail_strength=0.1)plt.figure(figsize=(12,12))plt.scatter(X,y)#2.读取数据data=pd.read_excel('数据/样本数据.xlsx')#3.将数据标准化——preprocessing.scale(data)from sklearn import preprocessing#为了不破坏数据集中的离散变量,只将数值种类数高于10的连续变量标准化for col in data.columns[2:]:
       if len(set(data[col]))>10:
              data[col]=preprocessing.scale(data[col])

Three regression

1. Ordinary Least Squares Linear Regression

import numpy as npfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_split

X=data[['work', 'work_time', 'work_salary',
       'work_address', 'worker_number', 'month_income', 'total_area',
       'own_area', 'rend_area', 'out_area',
       'agricultal_income', 'things', 'wifi', 'internet_fee', 'cloth_outcome',
       'education_outcome', 'medcine_outcome', 'person_medicne_outcome',
       'relationship_outcome', 'food_outcome', 'entertainment_outcome',
       'agriculta_outcome', 'other_outcome', 'owe', 'owe_total', 'debt',
       'debt_way', 'distance_debt', 'distance_market', 'traffic_', 'express',
       'express_distance', 'exercise', 'satisfac', 'wifi_neghbor',
       'wifi_relative', 'wifi_frend', 'internet', 'medical_insurance']]y=data['total_income']model=LinearRegression().fit(X,y)#拟合模型model.score(X,y)#拟合优度model.coef_#查看拟合系数model.intercept_#查看拟合截距项model.predict(np.array(X.ix[25,:]).reshape(1,-1))#预测model.get_params()#得到模型的参数

2. Logistic Regression Logit

from sklearn.linear_model import LogisticRegression#2.1数据处理X=data[['month_income', 'education_outcome','relationship_outcome', 'entertainment_outcome','traffic_', 'express',
       'express_distance','satisfac', 'wifi_neghbor','wifi_relative', 'wifi_frend', 'internet']]y=data['wifi']X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3)#利用train_test_split进行将训练集和测试集进行分开,test_size占30%#2.2模型拟合model = LogisticRegression()model.fit(X_train,y_train)model.score(X_test,y_test)#2.3模型预测y_predict = model.predict(X_test)#2.4通过调整判别分数标准,来调整判别结果decsion_scores = model.decision_function(X_test)#用于决定预测值取值的判别分数y_predict = decsion_scores>=5.0#将判别分数标准调整为5#2.5通过 精准率——召回率曲线图 寻找最优判别标准#由于随着判别标准的变化,精确率和召回率此消彼长,因此需要寻找一个最佳的判别标准使得精准率和召回率尽可能大from sklearn.metrics import precision_recall_curve
precisions,recalls,thresholds = precision_recall_curve(y_test,decsion_scores)#thresholds表示所有可能得判别标准,即判别分数最大与最小值之间的范围#由于precisions和recalls中比thresholds多了一个元素,因此要绘制曲线,先去掉这个元素plt.plot(thresholds,precisions[:-1])plt.plot(thresholds,recalls[:-1])plt.show()y_predict = decsion_scores>=2#根据上图显示,两线交于-0.3处,因此将判别分数标准调整为-0.3#2.6绘制ROC曲线:用于描述TPR和FPR之间的关系,ROC曲线围成的面积越大,说明模型越好"""TPR即是召回率_越大越好,FPR=(FP)/(TN+FP)_越小越好"""from sklearn.metrics import roc_curve
fprs,tprs,thresholds = roc_curve(y_test,decsion_scores)plt.plot(fprs,tprs)plt.show()#2.7绘制混淆矩阵from sklearn.metrics import confusion_matrix,precision_score,recall_score
cfm =confusion_matrix(y_test, y_predict)# 构建混淆矩阵并绘制混淆矩阵热力图plt.matshow(cfm,cmap=plt.cm.gray)#cmap参数为绘制矩阵的颜色集合,这里使用灰度plt.show()precision_score(y_test, y_predict)# 精准率recall_score(y_test, y_predict)#召回率

IV Model evaluation

#1.混淆矩阵,精准率和召回率from sklearn.metrics import confusion_matrix,precision_score,recall_score"""
混淆矩阵中行代表真实值,列代表预测值
TN:实际为0预测为0的个数       FP:实际为0预测为1的个数
FN:实际为1预测为0的个数       TP:实际为1预测为1的个数

精准率precision=TP/(TP+FP)——被预测为1的样本的的预测正确率
召回率recall=TP/(TP+FN)——实际为1的样本的正确预测率
"""cfm =confusion_matrix(y_test, y_predict)# 构建混淆矩阵并绘制混淆矩阵热力图plt.matshow(cfm,cmap=plt.cm.gray)#cmap参数为绘制矩阵的颜色集合,这里使用灰度plt.show()precision_score(y_test, y_predict)# 精准率recall_score(y_test, y_predict)#召回率#2.精准率和召回率作图:由于精准率和召回率此消彼长,应当选择适当的参数使二者同时尽可能的大#3.调和平均值"""精准率和召回率的调和平均值"""from sklearn.metrics import f1_score
f1_score(y_test,y_predict)#4.错误率矩阵row_sums = np.sum(cfm,axis=1)err_matrix = cfm/row_sums
np.fill_diagonal(err_matrix,0)#对err_matrix矩阵的对角线置0,因为这是预测正确的部分,不关心plt.matshow(err_matrix,cmap=plt.cm.gray)#亮度越高的地方代表错误率越高plt.show()

For a large number of free learning recommendations, please visitpython tutorial(Video)

The above is the detailed content of Introduction to Python's sklearn machine learning algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),