python如何实现逻辑回归?本篇文章小编给大家分享一下python实现逻辑回归代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
代码如下:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_classification
def initialize_params(dims):
w = np.zeros((dims, 1))
b = 0
return w, b
def sigmoid(x):
z = 1 / (1 + np.exp(-x))
return z
def logistic(X, y, w, b):
num_train = X.shape[0]
y_hat = sigmoid(np.dot(X, w) + b)
loss = -1 / num_train * np.sum(y * np.log(y_hat) + (1-y) * np.log(1-y_hat))
cost = -1 / num_train * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))
dw = np.dot(X.T, (y_hat - y)) / num_train
db = np.sum(y_hat - y) / num_train
return y_hat, cost, dw, db
def linear