一、机器学习分类

机器学习分为:有监督学习,无监督学习和半监督学习。

参考文章 机器学习两种方法——监督学习和无监督学习(通俗理解)

1、有监督学习

通过给定的训练数据集中学习出一个函数(模型参数),当新数据到来时,可以根据这个函数预测结果。
有监督学习的训练集要求包括输入和输出,也就是特征和目标。
有监督学习是最常见的 分类 问题,通过已有的训练样本(即已知数据及其对应输出)去训练得到一个最优模型,再利用这个模型将所有的输入映射为响应的数据,对输出进行简单的判断从而实现分类的目的。也就具有了对位置数据分类的能力。
有监督学习的目标往往是让计算机去学习我们已经创建好的分类系统(模型)。

有监督学习是 训练神经网络决策树 的常见技术。这两个技术高度依赖事先确定的分类系统给出的信息。
对于神经网络,系统分类利用信息判断网络的错误,然后不断调整网络参数。
对于决策树,分类系统用它来判断哪些属性提供了最多的信息。
常见的有监督学习算法:回归分析和统计分类。最典型的算法是KNN和SVM。

2、无监督学习

输入数据没有被标记,也没有确定的结果。样本数据类别未知,需要根据样本间的相似性对样本集进行分类试图使类内差距最小化,类间差距最大化。
通俗点将就是实际应用中,不少情况下无法预先知道样本的标签,也就是说没有训练样本对应的类别,因而只能从原先没有样本标签的样本集开始学习分类器设计。
非监督学习目标不是告诉计算机怎么做,而是让它(计算机)自己去学习怎样做事情。
无监督学习的方法分为两大类:
(1) 一类为基于概率密度函数估计的直接方法:指设法找到各类别在特征空间的分布参数,再进行分类。
(2) 另一类是称为基于样本间相似性度量的简洁聚类方法:其原理是设法定出不同类别的核心或初始内核,然后依据样本与核心之间的相似性度量将样本聚集成不同的类别。
利用聚类结果,可以提取数据集中隐藏信息,对未来数据进行分类和预测。应用于数据挖掘,模式识别,图像处理等。

3、二者区别

  • 有监督学习:必须要有训练集和测试样本。在训练集中找规律,而对测试样本使用这种规律。

  • 无监督学习:没有训练集,只有一组数据,在该数据集中寻找规律。

  • 有监督学习:有监督学习是识别事物,识别的结果表现在给待识别数据上加上标签。因此训练集必须由带标签的样本组成。

  • 无监督学习:无监督学习是只有要分析数据集的本身,没有标签,如果发现数据集呈现某种聚集性,则可按自然的聚集性分类,但不予以某种预先分类标签对上号为目的。

  • 非监督学习方法在寻找数据集中的规律性,这种规律性并不一定要达到划分数据集的目的,也就是说不一定要“分类”。这一点是比有监督学习方法的用途要广。譬如分析一堆数据的主分量,或分析数据集有什么特点都可以归于非监督学习方法的范畴。

  • 用非监督学习方法分析数据集的主分量与用K-L变换计算数据集的主分量又有区别。后者从方法上讲不是学习方法。因此用K-L变换找主分量不属于无监督学习方法,即方法上不是。而通过学习逐渐找到规律性这体现了学习方法这一点。在人工神经元网络中寻找主分量的方法属于无监督学习方法。

4、总结

思维导图

二、线性回归

简单解释:最终得到的结果是个具体的数值,成为线性回归。

延伸学习 机器学习方法:回归(一):线性回归Linear regression
还有一类叫 分类 ,这个最终预测的结果是一个类别值,比如这个数值属于A类还是B类。

Sklearn 安装:

1
2
3
pip install scikit-learn
或者
conda install scikit-learn

1、回归问题

例如银行借钱,需要填写 工资年龄 来判断要分配多少 额度 ,其中 工资年龄 便称为特征,额度 称为目标。
:银行最终借款额度, x1 :工资, x2 :年龄, θ1 :工资的权重参数, θ2 :年龄的权重参数。
假设为每一行添加一列权重参数为 x0 ,且值为 1
线性回归案例1
第二个方程式为将第一个方程式转换成 向量 形式。

线性回归案例2
独立同分布 : 每个样本(这里是误差)不相关称为 独立 ,每个误差具有相同的分布称为 同分布 。(高斯分布就是正态分布)

线性回归案例3
L(θ) :似然函数,值越大代表模型越好。

显然求累乘和的难度很高,于是这里引入 对数似然函数 ,求解过程如下:
线性回归案例4
J(θ) :目标函数,值越大代表模型越好。

对等式两边求导:
线性回归案例5
θ 就是最终要得到的目标结果。

2、代码实现

按照上面的结论来写下面的模型就很简单了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets

class LinearRegression():
def __init__(self):
self.w = None # w参数就是上面公式里面的 θ

def fit(self, X, y):
# Insert constant ones for bias weights 为偏置权重插入常数
print(X.shape)
X = np.insert(X, 0, 1, axis=1)
print(X.shape)
X_ = np.linalg.inv(X.T.dot(X)) # X_ 表示处理完后的X值
self.w = X_.dot(X.T).dot(y)

def predict(self, X):
# Insert constant ones for bias weights 为偏置权重插入常数
X =np.insert(X, 0, 1, axis=1)
y_pred = X.dot(self.w)
return y_pred

def mean_squared_error(y_true, y_pred):
mse = np.mean(np.power(y_true - y_pred,2))
return mse

def main():
# Load the diabetes datasets 加载数据
diabetes = datasets.load_diabetes()

# Use only one feature 只使用一个特性
X = diabetes.data[:, np.newaxis, 2]
print(X.shape)
# Split the data into training 使用这些数据做测试
# x_train, y_train 训练集 x_test,y_test 测试集
x_train, x_test = X[:-20],X[-20:]
y_train, y_test = diabetes.target[:-20],diabetes.target[-20:]
clf = LinearRegression()
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

#Print the mean squared error
print("Mean Square Error:",mean_squared_error(y_test, y_pred))

# Plot the results
plt.scatter(x_test[:,0], y_test, color="black")
plt.plot(x_test[:,0], y_pred, color="blue", linewidth=3)
plt.show()

main()

二、Logistic回归(逻辑回归)

Logistic Regression(逻辑回归)是机器学习中一个非常非常常见的模型,在实际生产环境中也常常被使用,是一种经典的分类模型(不是回归模型)。
虽然是种回归,实际是拿来做数据分类,得出每个类别的概率。
逻辑回归只能做 二分类问题 ,不是A类就是B类。

延伸学习 Logistic Regression(逻辑回归)原理及公式推导

1、逻辑回归问题

将数据进行分类,这里通过 Sigmoid函数 来说明:
逻辑回归1

其中,传入任意数值 zg(z) 函数都会返回一个 0~1 之间的数值,通过指定 中间阀值 (通常是0.5),便将原始数据划分为两类,大于中间阀值0.5的为1这类,小于中间阀值0.5的为0这类。
将结果值 g(z) 看作概率,即 Sigmoid函数 可以将任意实数转换为概率。将一个回归问题转换成分类问题。
逻辑回归2
逻辑回归3

2、梯度下降

参考文章:梯度下降(Gradient Descent)小结
代码实现:(计算那高尔夫球离球洞距离和准确度)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# 一、绘制图像

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

pga = pd.read_csv("../data/pga.csv")

# 数据归一化
pga.distance = (pga.distance - pga.distance.mean()) / pga.distance.std()
pga.accuracy = (pga.accuracy - pga.accuracy.mean()) / pga.accuracy.std()
# 绘图
plt.scatter(pga.distance, pga.accuracy)
plt.xlabel("初始化距离")
plt.ylabel("初始化准确值")
plt.show()


# 二、计算梯度下降
## 1、非梯度下降法
## 定义目标函数(损失函数)
def cost(theta0, theta, x, y):
J = 0
m = len(x)
for i in range(m):
h = theta * x[i] + theta0
J += (h - y[i])**2
J /= (2*m)
return J
print(cost(0, 1, pga.distance, pga.accuracy))

theta0 = 100
thetals = np.linspace(-3, 2, 100)
costs = []
for thetal in thetals:
costs.append(cost(theta0, thetal, pga.distance, pga.accuracy))
plt.plot(thetals, costs)
plt.show()


## 2、梯度下降法
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(-10, 10, 100)
y = np.linspace(-10, 10, 100)
X,Y = np.meshgrid(x, y)
Z = X**2 + Y **2
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(X=X,Y=Y,Z=Z)
plt.show()

theta0s = np.linspace(-2, 2, 100)
theta1s = np.linspace(-2, 2, 100)
COST = np.empty(shape = (100, 100))
TOS, T1S = np.meshgrid(theta0s, theta1s)
for i in range(100):
for j in range(100):
COST[i, j] = cost(TOS[0, i], T1S[j, 0], pga.distance, pga.accuracy)
fig2 = plt.figure()
ax = fig2.gca(projection="3d")
ax.plot_surface(X = TOS, Y=T1S, Z=COST)
plt.show()

### 对θ0和θ1求偏导
### θ0
def partial_cost_theta1(theta0, theta1, x, y):
h = theta0 + theta1 * x
diff = (h - y) * x
partial = diff.sum() / (x.shape[0])
return partial

partial1 = partial_cost_theta1(0, 5, pga.distance, pga.accuracy)

### θ1
def partial_cost_theta0(theta0, theta1, x, y):
h = theta0 + theta1 * x
diff = (h - y)
partial = diff.sum() / (x.shape[0])
return partial

partial1 = partial_cost_theta0(1, 1, pga.distance, pga.accuracy)
### 定义更新函数
def gradient_descent(x, y, a;pha=0.1, theta0 = 0, theta1 = 0):
max_epochs = 1000 # 最大循环次数
counter = 0 # 当前循环次数
c = cost(theta1, theta0, pga.distance, pga.accuracy) # 计算当前目标函数值
costs = [c] # 添加值作为图像显示
convergence_thres = 0.000001
cprev = c + 10
theta0s = [theta0]
theta1s = [theta1]

while (np.abs(cprev - c) > convergence_thres) and (counter < max_epochs):
cprev = c
# 参数更新 导数 * 步长 = 下降距离
update0 = alpha * partial_cost_theta0(theta0, theta1, x, y)
update1 = alpha * partial_cost_theta1(theta0, theta1, x, y)
# 实际更新 梯度下降
theta0 -= update0
theta1 -= update1
# 保存数据
theta0s.append(theta0)
theta1s.append(theta1)

c = cost(theta0, theta1, pga.distance, pga.accuracy)
costs.append(c)
counter += 1 # 计算次数
return {"theta0":theta0, "theta1": theta1, "costs": costs}

print("Theta1 = ",gradient_descent(pga.distance, pga.accuracy)["theta1"])
descend = gradient_descent(pga.distance, pga.accuracy, alpha=.01)
plt.scatter(range(len(descend["costs"])),descend["costs"])
plt.show()