这篇文章主要讲解了“怎么理解并掌握Python逻辑回归”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么理解并掌握Python逻辑回归”吧!
def sigmoid(x):定义sigmoid函数
return 1/(1+np.exp(-x))
进行逻辑回归的参数设置以及迭代
def weights(x,y,alpha,thershold):#初始化参数m,n = x_train.shapetheta = np.random.rand(n) #参数cnt = 0 # 迭代次数max_iter = 50000#开始迭代while cnt < max_iter:cnt += 1diff = np.full(n,0)for i in range(m):diff = (y[i]-sigmoid(theta.T @ x[i]))*x[i]theta = theta + alpha * diffif(abs(diff)<thershold).all():breakreturn theta
预测函数
def predict(x_test,theta):if sigmoid(theta.T @ x_test)>0.5:return 1else:return 0
调用函数
x_train = np.array([[1,2.697,6.254],[1,1.872,2.014],[1,2.312,0.812],[1,1.983,4.990],[1,0.932,3.920],[1,1.321,5.583],[1,2.215,1.560],[1,1.659,2.932],[1,0.865,7.362],[1,1.685,4.763],[1,1.786,2.523]])y_train = np.array([1,0,0,1,0,1,0,0,1,0,1])alpha = 0.001 # 学习率thershold = 0.01 # 指定一个阈值,用于检查两次误差print(weights(x_train,y_train,alpha,thershold))
感谢各位的阅读,以上就是“怎么理解并掌握Python逻辑回归”的内容了,经过本文的学习后,相信大家对怎么理解并掌握Python逻辑回归这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!