python machine learning introductory notes sharing

Machine Learning (Introduction) Study Notes

1-1 Understand artificial intelligence

Three essential elements for artificial intelligence : algorithm, computing power (computing power), and data

Main branches of artificial intelligence:

  1. Computer Vision:

eg: face recognition

  1. Natural language processing:

Speech Recognition

Semantic recognition

1-2 Machine learning workflow

  1. definition[***]

Automatic data analysis to obtain models

predict

Automatically analyze and obtain models from data, and use the models to predict unknown data.

2. Workflow[****]

1. Get data

2. Basic data processing

3. Feature engineering

4. Machine learning (model training)

5. Model evaluation

3. Introduction to the obtained data set

1.Proper nouns

sample

feature

Target value (label value)

Eigenvalues

2. Data type composition

Type 1: Feature value + target value

The target value is divided into discrete or continuous

Type 2: Only feature values, no target values

3. Data partitioning

Training data (training set) -- Build model 0.7--0.8

Test data (test set) -- model evaluation 0.2--0.3

4. Basic data processing

Process missing values, remove outliers, etc. on logarithms

5. Feature engineering

1.Definition

Convert data into data that is easier for machines to recognize

2. Why feature engineering is needed

Data and features determine the upper limit of machine learning, while models and algorithms only approach this upper limit.

3. Contains content

Feature extraction

Feature preprocessing

Feature dimensionality reduction

6. Machine Learning

Choose the appropriate algorithm to train the model

7. Model evaluation

Evaluate the trained model

1-3 Classification of machine learning algorithms :

1. Supervised learning: There are feature values ​​and target values

Target value continuous--regression

Target value discrete--classification

2. Unsupervised learning: only eigenvalues

3. Semi-supervised learning:

There are eigenvalues, but some have target values ​​and some do not.

4. Reinforcement learning:

Dynamic process, the output of the previous step's data is the input of the next step's data

Four elements: agent, action, environment, reward

Supervised learning versus reinforcement learning

supervised learning

reinforcement learning

feedback mapping

A mapping from input to output. The output of supervised learning is the relationship between them. It can tell the algorithm what input corresponds to what output.

A mapping from input to output. The output of reinforcement learning is the feedback reward function to the machine, which is used to judge whether the behavior is good or bad.

feedback time

If you make a bad choice, it will be immediately fed back to the algorithm.

As a result, there is a delay in feedback. Sometimes it may take many steps to know whether the previous choice was good or bad.

Input features

The inputs are independently and identically distributed

The inputs faced are always changing. Whenever the algorithm makes a behavior, it affects the input of the next decision.

behavior pattern

Without considering the balance between behaviors, just develop

(exploitation)

An agent can make trade-offs between exploration and exploitation and choose the one that maximizes rewards

1-4 Model Evaluation:

  1. Classification model evaluation

Accuracy: the proportion of correct predictions to the total number of samples

Precision rate: the proportion of correct predictions that are positive to all predictions that are positive

Recall rate: the proportion of all positive samples that are correctly predicted as positive

F1-score: Mainly used to evaluate the robustness of the model

AUC indicator: mainly used to evaluate sample balance

  1. Regression model evaluation

  1. Mean square error (MSE): Calculate the square of the difference between the predicted value and the true value of each sample, then sum and average. This indicator calculates the average sum of square errors of the sample points corresponding to the fitted data and the original data. The smaller the value, the better the fitting effect. (yi is the real value, f(xi) is the predicted value)

  1. Root mean square error (RMSE): The root mean square error is the square root of the mean square error. The smaller the value, the better the fitting effect.

  1. (R-square): The coefficient of determination value is between 0 and 1. The closer it is to 1, the better the prediction effect of the model is. The closer it is to 0, the worse the prediction effect of the model is. Of course, there are also negative values, which means the model is very poor. formula

is the average value of y.

  1. average relative error

  1. mean matching error

  1. relative squared error

1-5 fitting

Overfitting: The specific manifestation is that the final model performs well on the training set but performs poorly on the test set . The model generalization ability is weak .

欠拟合:在训练集及测试集上的表现都不好





2-1 Matplotlib 画图库

详细学习地址 Matplotlib教程(非常详细) (biancheng.net)


3-1 Numpy

Numpy中文网地址 NumPy 参考手册 | NumPy 中文

Numpy菜鸟教程 https://www.runoob.com/numpy/numpy-tutorial.html

算法

  1. K-近邻算法(KNN)

  1. K-近邻算法(KNN)

定义:根据“邻居”来判断类别

如何计算你到你的"邻居"的距离:一般时候,都是使用欧氏距离

1-2 K-近邻算法API

sklearn.neighbors.KNeighborsClassifier(n_neighbors=5)

n_neighbors:int,可选(默认= 5),k_neighbors查询默认使用的邻居数

1-3 K值的选择

KNN中K值大小选择对模型的影响【知道】

K值过小:

容易受到异常点的影响

容易过拟合

k值过大:

受到样本均衡的问题

容易欠拟合

1-4 kd树

1、构建树

2、最近领域搜索

案例:

  1. 构建树

第一次:

x轴 -- 2,5,9,4,8,7 --> 2,4,5,7,8,9

y轴 -- 3,4,6,7,1,2 --> 1,2,3,4,6,7

首先选择x轴,找中间点,发现是(7,2)

第二次:

左面:(2,3),(4,7),(5,4) --> 3, 4, 7

右面:(8,1),(9,6) --> 1 , 6

从y轴开始选择,左边选择点是(5,4),右边选择点(9,6)

第三次:

从x轴开始选择

  1. 搜索

  1. 在本域内,没有进行跨域搜索

  1. 要跨到其他域搜索

1-5 案例:鸢尾花种类预测 -- 数据集介绍

1、获取数据集【知道】

小数据:

sklearn.datasets.load_*

(注意:该数据集从本地获取)

大数据集:

sklearn.datasets.fetch_*

(注意:该数据集从网上下载)

subset -- 表示获取到的数据类型

  1. 数据集返回值介绍【知道】

返回值类型是bunch--是一个字典类型

返回值的属性:

data:特征数据数组 target:标签(目标)数组

DESCR:数据描述 feature_names:特征名,

target_names:标签(目标值)名

  1. 数据可视化

import seaborn

Seaborn.lmplot()

参数

x,y -- 具体x轴,y轴数据的索引值

data -- 具体数据

hue -- 目标值是什么

fit-reg -- 是否进行线性拟合

4、数据集的划分【掌握】

sklearn.model_selection.train_test_split(arrays, *options)

参数:

x -- 特征值 y -- 目标值

test_size -- 测试集大小 ramdom_state -- 随机数种子

返回值:

x_train, x_test, y_train, y_test (顺序不能乱)

1-6、特征工程-特征预处理

1、定义

通过一些转换函数将特征数据转换成更加适合算法模型的特征数据过程

2、包含内容:

归一化

标准化

3、api

sklearn.preprocessing

  1. 归一化

定义:通过对原始数据进行变换把数据映射到(默认为[0,1])之间

api:

sklearn.preprocessing.MinMaxScaler (feature_range=(0,1)… )

MinMaxScalar.fit_transform(X)

参数:

feature_range -- 自己指定范围,默认0-1

X:numpy array格式的数据[n_samples,n_features]

返回值:转换后的形状相同的array

总结:

鲁棒性比较差(容易受到异常点的影响)

只适合传统精确小数据的场景(以后不会用你了)

  1. 标准化

定义:通过对原始数据进行变换把数据变换到均值为0,标准差为1范围内

api:

sklearn.preprocessing.StandardScaler( )

处理之后每列来说所有数据都聚集在均值0附近标准差差为1

StandardScaler.fit_transform(X)

参数:

X:numpy array格式的数据[n_samples,n_features]

返回值:转换后的形状相同的array

总结:

异常值对我影响小

适合现代嘈杂大数据场景(以后就用你了)

1-7、案例:鸢尾花种类预测—流程实现

1、api

sklearn.neighbors.KNeighborsClassifier(n_neighbors=5,algorithm='auto')

参数:

n_neighbors:

int,可选(默认= 5),k_neighbors查询默认使用的邻居数

algorithm:选择什么样的算法进行计算

‘auto’,‘ball_tree’,‘kd_tree’,‘brute’

  1. 案例流程

1.获取数据集

2.数据基本处理

3.特征工程

4.机器学习(模型训练)

5.模型评估

1-8 K-近邻算法(KNN)总结

优点:

  1. 简单有效

  1. 重新训练代价低

  1. 适合类域交叉样本

  1. 适合大样本自动分类

缺点:

  1. 惰性学习

  1. 类别评分不是规范化

  1. 输出可解释性不强

  1. 对不均衡的样本不擅长

样本不均衡:收集到的数据每个类别占比严重失衡

  1. 计算量大

1-9、交叉验证和网格搜索

1、交叉验证

1、定义:

将拿到的训练数据,分为训练和验证集

*折交叉验证(*表示分为几份)

2、分割方式

训练集:训练集+验证集

测试集:测试集

3、为什么需要交叉验证

为了让评估的模型更加准确可靠

注意:交叉验证不能提高模型准确率

2、网格搜索

超参数:

sklearn中,需要手动指定的参数,叫做超参数

网格搜索就是把这些超参数的值,通过字典的形式传递进去,然后进行选择最值

3、api

sklearn.model_selection.GridSearchCV(estimator, param_grid=None,cv=None)

对估计器的指定参数值进行详尽搜索

estimator:选择了哪个训练模型(估计器对象)

param_grid:需要传递的超参数(估计器参数 (dict){“n_neighbors”:[1,3,5,7,9]})

cv:指定几折交叉验证

fit:输入训练数据

score:准确率

结果分析:

bestscore__:在交叉验证中验证的最好结果

bestestimator:最好的参数模型

cvresults:每次交叉验证后的验证集准确率结果和训练集准确率结果

2、线性回归

2.1 线性回归简介

1、定义

利用回归方程(函数)对一个或多个自变量(特征值)和因变量(目标值)之间关系进行建模的一种分析方式

2、表示方式

h(w)=w1 x 1 + w2 x 2 + w3 x 3 + ...... + b = w转置x + b

3、分类

线性关系

非线性关系

2.2 线性回归api初步使用

1、api

sklearn.linear_model.LinearRegression()

属性:

LinearRegression.coef_:回归系数

2.3 导数

1、常见的导数

2、导数的四则运算

2.4 线性回归的损失和优化

1、损失

最小二乘法

2、优化

正规方程

梯度下降(*****)

3、正规方程 -- 一蹴而就

利用矩阵的逆,转置进行一步求解

只是适合样本和特征比较少的情况

4、梯度下降法 -- 循序渐进

举例:

山-- 可微分函数

山底-- 函数的最小值

梯度的概念

单变量-- 切线

多变量-- 向量

梯度下降法中关注的两个参数

α -- 就是步长

步长太小-- 下山太慢

步长太大-- 容易跳过极小值点(*****)

为什么梯度要加一个负号

梯度方向是上升最快方向,负号就是下降最快方向

5、梯度下降和正规方程对比

梯度下降

正规方程

需要选择学习率

不需要

需要迭代求解

一次运算求出

特征数量较大可以使用

需要计算方程,时间复杂度高O(n3)

6、梯度下降法和正规方程选择

小规模数据:

正规方程:LinearRegression(不能解决拟合问题)

岭回归

大规模数据:

梯度下降法:SGDRegressor

2.5、梯度下降法介绍

1、全梯度下降算法(FG)【知道】

在进行计算的时候,计算所有样本的误差平均值,作为我的目标函数

2、随机梯度下降算法(SG)【知道】

每次只选择一个样本进行考核

3、小批量梯度下降算法(mini-batch)【知道】

选择一部分样本进行考核

4、随机平均梯度下降算法(SAG)【知道】

会给每个样本都维持一个平均值,后期计算的时候,参考这个平均值

2.6 api

正规方程

sklearn.linear_model.LinearRegression(fit_intercept=True)

参数

fit_intercept:是否计算偏置

属性

LinearRegression.coef_:回归系数

LinearRegression.intercept_:偏置

梯度下降(*****)

sklearn.linear_model.SGDRegressor(loss="squared_loss", fit_intercept=True,

learning_rate ='invscaling', eta0=0.01)

参数:

loss:损失类型

loss=”squared_loss”: 普通最小二乘法

fit_intercept:是否计算偏置

learning_rate : string, optional

学习率填充

'constant': eta = eta0

'optimal': eta = 1.0 / (alpha * (t + t0)) [default]

'invscaling': eta = eta0 / pow(t, power_t)

power_t=0.25:存在父类当中

对于一个常数值的学习率来说,可以使用learning_rate=’constant’ ,并使用eta0来指定学习率。

属性:

SGDRegressor.coef_:回归系数

SGDRegressor.intercept_:偏置

2.7 案例

1.获取数据集

2.数据基本处理

2.1数据集划分

3.特征工程 --标准化

4.机器学习(线性回归)

5.模型评估

2.8 拟合

过拟合:

在训练集上效果好;在测试集上效果差。模型泛化能力弱

解决方法

  1. 重新清洗数据

  1. 增大数据的训练量

  1. 正则化

  1. 减少特征维度

欠拟合:

在训练集及测试集上的表现都不好

解决方法

继续学习:1、添加其他特征项

2、添加多项式特征

正则化

通过限制高次项的系数进行防止过拟合

L1正则化

理解:直接把高次项前面的系数变为0

Lasso回归

L2正则化

理解:把高次项系数前面的系数变成特别小的值

岭回归

2.9 正则化线性模型

1、Ridge Regression 岭回归

就是把系数添加平方项

然后限制系数值的大小

α值越小,系数值越大,α越大,系数值越小

2、Lasso 回归

对系数值进行绝对值处理

由于绝对值在顶点处不可导,所以进行计算的过程中产生很多0,最后得到结果为:稀疏矩阵

3、Elastic Net 弹性网络

是前两个内容的综合

设置了一个r,如果r=0--岭回归;r=1--Lasso回归

4、Early stopping

通过限制错误率的阈值,进行停止

3、逻辑回归

3.1 逻辑回归介绍

1、逻辑回归概念【知道】

解决的是一个二分类问题

逻辑回归的输入是线性回归的输出

2、逻辑回归的原理【掌握】

1、输入:

线性回归的输出

2、激活函数

sigmoid函数

把整体的值映射到[0,1]

再设置一个阈值,进行分类判断

3、损失

对数似然损失

借助了log思想,进行完成

真实值等于0,等于1两种情况进行划分

4、优化

提升原本属于1类别的概率,降低原本是0类别的概率。

3.2 逻辑回归api 介绍

sklearn.linear_model.LogisticRegression(solver='liblinear', penalty=‘l2’, C = 1.0)

参数

solver可选参数:{'liblinear'(默认), 'sag', 'saga','newton-cg', 'lbfgs'},

penalty:正则化的种类

C:正则化力度

(注意:回归,分类api 有时候是可以混合使用)

3.3 案例:癌症分类预测-良/恶性乳腺癌肿瘤预测

1.获取数据

2.基本数据处理

2.1 缺失值处理

2.2 确定特征值,目标值

2.3 分割数据

3.特征工程(标准化)

4.机器学习(逻辑回归)

5.模型评估

3.4 分类评估方法

1、混淆矩阵

预测结果

正例

真实结果

正例

真正例TP

伪反例FN

假例

伪正例FP

真反例TN

2、精确率(Precision)与召回率(Recall)

准确率-- 对不对

(TP+TN)/(TP+TN+FN+FP)

精确率-- 查的准不准

TP/(TP+FP)

召回率-- 查的全不全

TP/(TP+FN)

F1-score

反映模型的稳健性

3、api

sklearn.metrics.classification_report(y_true, y_pred, labels=[], target_names=None )

4、roc曲线和 auc指标

roc曲线

通过tpr和fpr来进行图形绘制,然后绘制之后,行成一个指标auc

auc

越接近1,效果越好

越接近0,效果越差

越接近0.5,效果就是胡说

注意:这个指标主要用于评价不平衡的二分类问题

5、api

sklearn.metrics.roc_auc_score(y_true, y_score)

y-true -- 要把正例转换为1,反例转换为0

3.5 ROC曲线的绘制

1.构建模型,把模型的概率值从大到小进行排序

2.从概率最大的点开始取值,一直进行tpr和fpr的计算,然后构建整体模型,得到结果

3.其实就是在求解积分(面积)

Guess you like

Origin blog.csdn.net/m0_64892604/article/details/128605814