最近在看慕课上北大开的数据结构和算法Python版,老师讲的深入浅出,我会不断输出课上的心得体会,与大家共同讨论,共同进步。
Python算法之回归分析
回归分析是一种用于数据分类的回归模型。这个模型非常简单,事实上,它是一个线性分类器。
无论如何,当你想要去探索你的数据的时候,这是一个很好的出发点。
很容易编程,完全可以速成。且模型是解释性的模型,也就是说模型将告诉你每个特性对因变量的影响。
绿色和蓝色-正确的分类 红色-错误分类
首先,输入的数据可以通过多项式特征手动扩展,而逻辑回归几乎不需要对数据进行任何假设就可以成为非常有用的非线性分类器。
import numpy as np
from bokeh.plotting import figure, show, output_notebook
def logistic_regression(X, Y, W, lr=0.001, steps=1000):
m = len(Y)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
for _ in range(steps):
# prediction
hypothesis = sigmoid(X @ W)
# fix overflow & underflow
hypothesis = np.clip(hypothesis, 1e-5, 1 - 1e-5)
# loss function, gradient, training
loss = -1 / m * (Y @ np.log(hypothesis) +
(1 - Y) @ np.log(1 - hypothesis))
gradient = 1 / m * (X.T @ (hypothesis - Y))
W -= lr * gradient
# current loss & prediction
return loss, sigmoid(X @ W)
测试:
n = 10000
# random values
x_, y_ = np.random.rand(2, n)
# polynomial coefficients
X = np.c_[np.ones(n), x_, y_, x_ ** 2, y_ ** 2]
# Y: target values
Y = (x_ - .5 <= (y_ - .5) ** 2) * 1
# weights
W = np.zeros(5)
for _ in range(10):
loss, H = logistic_regression(X, Y, W, lr=5., steps=1000)
print(loss)
print('accuracy', np.mean(Y == H.round()))
print('weights', W)
小刘学Python,与你一起进步,一起走向技术大牛!