python分类代码_python实现logistic分类算法代码

本文介绍了使用Python实现Logistic分类算法的过程,包括成本函数定义、梯度下降优化以及训练和预测函数的详细步骤。通过实例展示了如何进行训练和测试。
摘要由CSDN通过智能技术生成

最近在看吴恩达的机器学习课程,自己用python实现了其中的logistic算法,并用梯度下降获取最优值。

logistic分类是一个二分类问题,而我们的线性回归函数

65431f45fd7f053c831db65b64fdd4d2.png

的取值在负无穷到正无穷之间,对于分类问题而言,我们希望假设函数的取值在0~1之间,因此logistic函数的假设函数需要改造一下

cdfa757c8e19cab0268447db388185fb.png

由上面的公式可以看出,0 < h(x) < 1,这样,我们可以以1/2为分界线

bbdd5e9e1388391323a0931f607e8d69.png

cost function可以这样定义

4dcab24dad7cba15cb2dbeef1fbbd3b1.png

其中,m是样本的数量,初始时θ可以随机给定一个初始值,算出一个初始的J(θ)值,再执行梯度下降算法迭代,直到达到最优值,我们知道,迭代的公式主要是每次减少一个偏导量

0b6142dc5fb16231123da34c57e14477.png

如果将J(θ)代入化简之后,我们发现可以得到和线性回归相同的迭代函数

8c1f2e8046cf7737cd1e4eb48d2174d7.png

按照这个迭代函数不断调整θ的值,直到两次J(θ)的值差值不超过某个极小的值之后,即认为已经达到最优解,这其实只是一个相对较优的解,并不是真正的最优解。 其中,α是学习速率,学习速率越大,就能越快达到最优解,但是学习速率过大可能会让惩罚函数最终无法收敛,整个过程python的实现如下

import math

ALPHA = 0.3

DIFF = 0.00001

def predict(theta, data):

results = []

for i in range(0, data.__len__()):

temp = 0

for j in range(1, theta.__len__()):

temp += theta[j] * data[i][j - 1]

temp = 1 / (1 + math.e ** (-1 * (temp + theta[0])))

results.append(temp)

return results

def training(training_data):

size = training_data.__len__()

dimension = training_data[0].__len__()

hxs = []

theta = []

for i in range(0, dimension):

theta.append(1)

initial = 0

for i in range(0, size):

hx = theta[0]

for j in range(1, dimension):

hx += theta[j] * training_data[i][j]

hx = 1 / (1 + math.e ** (-1 * hx))

hxs.append(hx)

initial += (-1 * (training_data[i][0] * math.log(hx) + (1 - training_data[i][0]) * math.log(1 - hx)))

initial /= size

iteration = initial

initial = 0

counts = 1

while abs(iteration - initial) > DIFF:

print("第", counts, "次迭代, diff=", abs(iteration - initial))

initial = iteration

gap = 0

for j in range(0, size):

gap += (hxs[j] - training_data[j][0])

theta[0] = theta[0] - ALPHA * gap / size

for i in range(1, dimension):

gap = 0

for j in range(0, size):

gap += (hxs[j] - training_data[j][0]) * training_data[j][i]

theta[i] = theta[i] - ALPHA * gap / size

for m in range(0, size):

hx = theta[0]

for j in range(1, dimension):

hx += theta[j] * training_data[i][j]

hx = 1 / (1 + math.e ** (-1 * hx))

hxs[i] = hx

iteration += -1 * (training_data[i][0] * math.log(hx) + (1 - training_data[i][0]) * math.log(1 - hx))

iteration /= size

counts += 1

print('training done,theta=', theta)

return theta

if __name__ == '__main__':

training_data = [[1, 1, 1, 1, 0, 0], [1, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1], [0, 1, 0, 0, 0, 1],

[0, 0, 0, 0, 1, 1]]

test_data = [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]]

theta = training(training_data)

res = predict(theta, test_data)

print(res)

运行结果如下

84cb9a9a33b65f035a05fb8b792a0b1e.png

以上这篇python实现logistic分类算法代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持聚米学院。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Python 实现逻辑回归(logistic regression)算法实现分类,包括训练和预测。 ``` import numpy as np class LogisticRegression: def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False): self.lr = lr self.num_iter = num_iter self.fit_intercept = fit_intercept self.verbose = verbose def __add_intercept(self, X): intercept = np.ones((X.shape[0], 1)) return np.concatenate((intercept, X), axis=1) def __sigmoid(self, z): return 1 / (1 + np.exp(-z)) def __loss(self, h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def fit(self, X, y): if self.fit_intercept: X = self.__add_intercept(X) # 初始化权重 self.theta = np.zeros(X.shape[1]) for i in range(self.num_iter): z = np.dot(X, self.theta) h = self.__sigmoid(z) gradient = np.dot(X.T, (h - y)) / y.size self.theta -= self.lr * gradient if(self.verbose == True and i % 10000 == 0): z = np.dot(X, self.theta) h = self.__sigmoid(z) print(f'loss: {self.__loss(h, y)} \t') def predict_prob(self, X): if self.fit_intercept: X = self.__add_intercept(X) return self.__sigmoid(np.dot(X, self.theta)) def predict(self, X, threshold): return self.predict_prob(X) >= threshold ``` 这个模型实现了以下功能: - `__add_intercept` 方法添加一个截距项到输入数据(如果 `fit_intercept=True`)。 - `__sigmoid` 方法应用 sigmoid 函数来实现概率预测。 - `__loss` 方法计算损失函数。 - `fit` 方法使用梯度下降来拟合模型参数。 - `predict_prob` 方法预测样本的概率。 - `predict` 方法根据阈值返回二分类结果。 使用方法: ``` import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt X, y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) model = LogisticRegression(lr=0.1, num_iter=300000) model.fit(X_train, y_train) # 绘制决策边界 x1_min, x1_max = X[:, 0].min() - .5, X[:, 0].max() + .5 x2_min, x2_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max, 100), np.linspace(x2_min, x2_max, 100)) X_test = np.c_[xx1.ravel(), xx2.ravel()] Z = model.predict_prob(X_test) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, cmap=plt.cm.RdBu, alpha=.8) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu, edgecolors='k') plt.show() print("Test accuracy:", sum(model.predict(X_test, 0.5) == y_test) / len(y_test)) ``` 这里使用 Scikit-Learn 的 `make_classification` 函数生成一个二分类数据集,并将它分成训练和测试集。我们使用 `LogisticRegression` 类拟合训练数据,并使用 `predict` 方法在测试集上进行预测。最后,我们绘制了决策边界并计算了测试准确度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值