Home Backend Development Python Tutorial Introduction to Python's sklearn machine learning algorithm

Introduction to Python's sklearn machine learning algorithm

Jan 22, 2021 am 09:55 AM
python

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
Copy after login

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()
Copy after login

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])
Copy after login

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()#得到模型的参数
Copy after login

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)#召回率
Copy after login

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()
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

See all articles