python实现逻辑回归的示例
作者:chenxiangzhen 时间:2022-04-05 05:16:59
代码
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_train(X, y, learning_rate, epochs):
# 参数初始化
w, b = initialize_params(X.shape[1])
loss_list = []
for i in range(epochs):
# 计算当前的预测值、损失和梯度
y_hat, loss, dw, db = logistic(X, y, w, b)
loss_list.append(loss)
# 基于梯度下降的参数更新
w += -learning_rate * dw
b += -learning_rate * db
# 打印迭代次数和损失
if i % 10000 == 0:
print("epoch %d loss %f" % (i, loss))
# 保存参数
params = {
'w': w,
'b': b
}
# 保存梯度
grads = {
'dw': dw,
'db': db
}
return loss_list, loss, params, grads
def predict(X, params):
w = params['w']
b = params['b']
y_pred = sigmoid(np.dot(X, w) + b)
return y_pred
if __name__ == "__main__":
# 生成数据
X, labels = make_classification(n_samples=100,
n_features=2,
n_informative=2,
n_redundant=0,
random_state=1,
n_clusters_per_class=2)
print(X.shape)
print(labels.shape)
# 生成伪随机数
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
# 划分训练集和测试集
offset = int(X.shape[0] * 0.9)
X_train, y_train = X[:offset], labels[:offset]
X_test, y_test = X[offset:], labels[offset:]
y_train = y_train.reshape((-1, 1))
y_test = y_test.reshape((-1, 1))
print('X_train=', X_train.shape)
print('y_train=', y_train.shape)
print('X_test=', X_test.shape)
print('y_test=', y_test.shape)
# 训练
loss_list, loss, params, grads = linear_train(X_train, y_train, 0.01, 100000)
print(params)
# 预测
y_pred = predict(X_test, params)
print(y_pred[:10])
来源:https://www.cnblogs.com/chenxiangzhen/p/10395231.html
标签:python,逻辑回归,机器学习
0
投稿
猜你喜欢
SqlServer 执行计划及Sql查询优化初探
2024-01-14 23:03:01
vue动态设置页面title的方法实例
2023-07-02 16:38:56
django settings.py配置文件的详细介绍
2022-09-20 07:40:33
Spring+MyBatis实现数据库读写分离方案
2024-01-23 03:05:36
Python实现 版本号对比功能的实例代码
2022-07-22 05:53:59
python opencv实现图像矫正功能
2022-05-22 17:00:13
python selenium 弹出框处理的实现
2022-12-05 14:19:19
如何快速地更新网页内容?
2010-01-01 15:12:00
js选项卡的实现方法
2024-04-22 22:23:51
Chrome调试折腾记之JS断点调试技巧
2023-07-07 16:35:08
python爬虫 urllib模块反爬虫机制UA详解
2022-04-07 02:22:51
Python curses内置颜色用法实例
2021-07-27 02:41:35
浅谈解除装饰器作用(python3新增)
2022-05-30 03:31:52
python 获取微信好友列表的方法(微信web)
2022-02-20 10:05:21
说说回车键触发表单提交的问题
2009-02-03 13:25:00
Tensorflow的可视化工具Tensorboard的初步使用详解
2021-06-12 18:32:06
PHP registerXPathNamespace()函数讲解
2023-06-05 01:58:00
Python还能这么玩之用Python做个小游戏的外挂
2022-12-11 18:27:43
Python中使用PIL库实现图片高斯模糊实例
2023-12-09 14:12:20
一篇文章带你了解Python和Java的正则表达式对比
2021-08-17 20:24:35