# 机器学习之线性回归(纯python实现)

2018-03-01 11:06:54来源:网络收集作者:无情人点击

def init_data():
return data
def linear_regression():
learning_rate = 0.01 #步长
initial_b = 0
initial_m = 0
num_iter = 1000 #迭代次数
data = init_data()
[b, m] = optimizer(data, initial_b, initial_m, learning_rate, num_iter)
plot_data(data,b,m)
print(b, m)
return b, m

def optimizer(data, initial_b, initial_m, learning_rate, num_iter):
b = initial_b
m = initial_m
for i in range(num_iter):
b, m = compute_gradient(b, m, data, learning_rate)
# after = computer_error(b, m, data)
if i % 100 == 0:
print(i, computer_error(b, m, data)) # 损失函数，即误差
return [b, m]

N = float(len(data))
#
# 偏导数， 梯度
for i in range(0, len(data)):
x = data[i, 0]
y = data[i, 1]
b_gradient += -(2 / N) * (y - ((m_cur * x) + b_cur))
m_gradient += -(2 / N) * x * (y - ((m_cur * x) + b_cur)) #偏导数
new_b = b_cur - (learning_rate * b_gradient)
new_m = m_cur - (learning_rate * m_gradient)
return [new_b, new_m]

Loss值的计算：

def computer_error(b, m, data):
totalError = 0
x = data[:, 0]
y = data[:, 1]
totalError = (y - m * x - b) ** 2
totalError = np.sum(totalError, axis=0)

if __name__ == '__main__':
linear_regression()

0 3.26543633854
100 1.41872132865
200 1.36529867423
300 1.34376973304
400 1.33509372632
500 1.33159735872
600 1.330188348
700 1.32962052693
800 1.32939169917
900 1.32929948325
1.23930380135 1.86724196887

def optimizer_two(data, initial_b, initial_m, learning_rate, num_iter):
b = initial_b
m = initial_m
while True:
before = computer_error(b, m, data)
b, m = compute_gradient(b, m, data, learning_rate)
after = computer_error(b, m, data)
if abs(after - before) < 0.0000001: #不断减小精度
break
return [b, m]
N = float(len(data))
delta = 0.0000001
for i in range(len(data)):
x = data[i, 0]
y = data[i, 1]
# 利用导数的定义来计算梯度
b_gradient = (error(x, y, b_cur + delta, m_cur) - error(x, y, b_cur - delta, m_cur)) / (2*delta)
m_gradient = (error(x, y, b_cur, m_cur + delta) - error(x, y, b_cur, m_cur - delta)) / (2*delta)
#
new_b = b_cur - (learning_rate * b_gradient)
new_m = m_cur - (learning_rate * m_gradient)
return [new_b, new_m]def error(x, y, b, m):
return (y - (m * x) - b) ** 2

sklearn中有相应的方法求线性回归，其直接使用最小二乘法求最优解。简单实现以做个比较。

def scikit_learn():
data = init_data()
y = data[:, 1]
x = data[:, 0]
x = (x.reshape(-1, 1))
linreg = LinearRegression()
linreg.fit(x, y)
print(linreg.coef_)
print(linreg.intercept_)
if __name__ == '__main__':
# linear_regression()
scikit_learn()