1. 监督学习
1.1 广义线性模型
y是x的线性组合 y ^ ( w , x ) = w 0 + w 1 x p + . . . + w p x p \hat{y}(w, x) = w_0 + w_1 x_p+...+w_p x_p y^(w,x)=w0+w1xp+...+wpxp。求解y与x的回归问题。
定义向量 w = ( w 1 , . . . , w p ) w = (w_1, ..., w_p) w=(w1,...,wp)作为coef_
定义 w 0 w_0 w0作为intercept_
1.1.1 普通最小二乘法
追求残差平方和最小。
from sklearn import linear_model
regression = linear_model.LinearRegression()
dataSet = [
# 自变量
[
[0,0], [1,1],[2,2]
],
# 因变量
[
0,1,2
],
]
regression.fit(dataSet[0], dataSet[1])
print(regression.predict(dataSet[0]))
console: [2.22044605e-16 1.00000000e+00 2.00000000e+00]
模型依赖于自变量各个维度的相互独立性。
如果实验数据设计不当,自变量数据容易出现多重共线性(multicollinearity)。
设自变量是维度为
n
f
e
a
t
u
r
e
s
n_{features}
nfeatures,样本数量为
n
s
a
m
p
l
e
s
n_{samples}
nsamples。且
n
s
a
m
p
l
e
s
≥
n
f
e
a
t
u
r
e
s
n_{samples} \geq n_{features}
nsamples≥nfeatures,
那么算法的复杂度为
O
(
n
s
a
m
p
l
e
s
n
f
e
a
r
u
r
e
s
2
)
O(n_{samples} n_{fearures}^2)
O(nsamplesnfearures2)。
1.1.2 岭回归
为了提高估计的稳定性,放弃最小二乘法的无偏性估计,而采用对权重的大小施加惩罚。
惩罚的力度α取得不同的值,权重的变化称为岭迹图。当权重的变化趋于稳定时,α的取值即为合理值。
from sklearn import linear_model
regression = linear_model.Ridge(alpha=0.5)
dataSet = [
[
[0,0], [0,0], [1,1]
],
[
0,0.1,1
]
]
regression.fit(dataSet[0],dataSet[1])
print(regression.predict(dataSet[0]))
console: [0.13636364 0.13636364 0.82727273]
时间复杂度同最小二乘法。
同时,我们也可以使用广义交叉验证来自动设置正则化参数:
regression = linear_model.RidgeCV(alphas=[0.1,1.0,10])
regression.fit(dataSet[0],dataSet[1])
print(regression.alpha_)
console: 0.1
1.1.3 Lasso
1.4 支持向量机
支持向量机的优势:高维空间中高效,维度比样本数量多依然有效,内存利用高效。
缺点:选择核函数避免过拟合。
1.4.1 分类
from sklearn import svm
dataSet = [
[
[0,0], [1,1]
],
[
0,1
]
]
clf = svm.SVC(gamma='scale')
clf.fit(dataSet[0], dataSet[1])
print(clf.predict(dataSet[0]))
console: [0 1]
clf.support_vectors_ # 支持向量 clf.support_ # 获得支持向量的索引 clf.n_support_ # 两个类的支持向量的数量