介绍
这期内容当中小编将会给大家带来有关使用python实现逻辑回归,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
代码
进口numpy np 进口matplotlib。pyplot作为plt 从sklearn.datasets。samples_generator进口make_classification def initialize_params (dim): w=np。0 ((dim, 1)) b=0 返回w b def乙状结肠(x): z=1/(1 + np.exp (- x)) 返回z def物流(X, y, w, b): num_train=X.shape [0] y_hat=乙状结肠(np。点(X, w) + b) 损失=1/num_train * np。总和(y * np.log (y_hat) + (1 y) * np.log (1-y_hat)) 成本=1/num_train * np。总和(y * np.log (y_hat) + (1 - y) * np。日志(1 - y_hat)) dw=np.dot (X。T (y_hat - y))/num_train db=np。(y_hat - y)/num_train求和 返回y_hat、成本、dw, db def linear_train (X, y, learning_rate时代): #参数初始化 w, b=initialize_params (X.shape [1]) loss_list=[] 因为我在范围(时代): #计算当前的预测值,损失和梯度 y_hat、损失,dw, db=物流(X, y, w, b) loss_list.append(损失) #基于梯度下降的参数更新 w +=-learning_rate * dw b +=-learning_rate * db #打印迭代次数和损失 如果我% 10000==0: 打印(“时代% d % f"损失;%(我损失)) #保存参数 params={ & # 39;w # 39;: w, & # 39;b, b } #保存梯度 毕业生={ & # 39;dw # 39;: dw, & # 39;db # 39;: db } 返回loss_list,损失,params,毕业生 def预测(X, params): w=params [& # 39; w # 39;】 b=params [& # 39; b # 39;】 y_pred=乙状结肠(np。点(X, w) + b) 返回y_pred if __name__==癬_main__": #生成数据 X,标签=make_classification (n_samples=100, n_features=2, n_informative=2, n_redundant=0, random_state=1, n_clusters_per_class=2) 打印(X.shape) 打印(labels.shape) #生成伪随机数 rng=np.random.RandomState (2) X +=2 * rng.uniform(大?X.shape) #划分训练集和测试集 抵消=int (X。形状[0]* 0.9) X_train y_train=X(抵消),标签(抵消): X_test y_test=X(抵消:),标签(抵消:) y_train=y_train。重塑((1,1)) y_test=y_test。重塑((1,1)) 打印(& # 39;X_train=& # 39;, X_train.shape) 打印(& # 39;y_train=& # 39;, y_train.shape) 打印(& # 39;X_test=& # 39;, X_test.shape) 打印(& # 39;y_test=& # 39;, y_test.shape) #训练 loss_list,损失,params,毕业生=linear_train (X_train y_train, 0.01, 100000) 打印(params) #预测 y_pred=预测(X_test params) print (y_pred [10])
上述就是小编为大家分享的使用python实现逻辑回归了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。