这篇文章主要讲解了“怎么使用Python线性回归方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用Python线性回归方法”吧!
来说说约定的符号,线性回归参数主要由斜率和截距组成,这里用W表示斜率,b表示截距。大写的W表示这是一个向量。一般来说是n_feauter_num数量,就是有多少个特征,W的shape就是(n_feauter_num,1),截距b是一个常数,通过公式Y=W*X+b计算出目标Y值,一般来说,在机器学习中约定原始值为Y,预测值为Y_hat。下面来谈谈具体实现步骤
下面给出具体python代码实现,本代码是通用代码,可以任意扩展W,代码中计算loss和梯度的地方采用的向量实现,因此增加W的维度不用修改代码
import matplotlib.pyplot as pltimport numpy as npdef f(X):
w = np.array([1, 3, 2])
b = 10
return np.dot(X, w.T) + bdef cost(X, Y, w, b):
m = X.shape[0]
Z = np.dot(X, w) + b
Y_hat = Z.reshape(m, 1)
cost = np.sum(np.square(Y_hat - Y)) / (2 * m) return costdef gradient_descent(X, Y, W, b, learning_rate):
m = X.shape[0]
W = W - learning_rate * (1 / m) * X.T.dot((np.dot(X, W) + b - Y))
b = b - learning_rate * (1 / m) * np.sum(np.dot(X, W) + b - Y) return W, bdef main():
# sample number
m = 5
# feature number
n = 3
total = m * n # construct data
X = np.random.rand(total).reshape(m, n)
Y = f(X).reshape(m, 1)# iris = datasets.load_iris()# X, Y = iris.data, iris.target.reshape(150, 1)# X = X[Y[:, 0] < 2]# Y = Y[Y[:, 0] < 2]# m = X.shape[0]# n = X.shape[1]
# define parameter
W = np.ones((n, 1), dtype=float).reshape(n, 1)
b = 0.0
# def forward pass++
learning_rate = 0.1
iter_num = 10000
i = 0
J = [] while i < iter_num:
i = i + 1
W, b = gradient_descent(X, Y, W, b, learning_rate)
j = cost(X, Y, W, b)
J.append(j)
print(W, b)
print(j)
plt.plot(J)
plt.show()if __name__ == '__main__':
main()
可以看到,结果输出很接近预设参数[1,3,2]和10
是不是感觉so easy.
step: 4998 loss: 3.46349593719e-07[[ 1.00286704]
[ 3.00463459]
[ 2.00173473]] 9.99528287088step: 4999 loss: 3.45443124835e-07[[ 1.00286329]
[ 3.00462853]
[ 2.00173246]] 9.99528904819step: 5000 loss: 3.44539028368e-07
感谢各位的阅读,以上就是“怎么使用Python线性回归方法”的内容了,经过本文的学习后,相信大家对怎么使用Python线性回归方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是天达云,小编将为大家推送更多相关知识点的文章,欢迎关注!