代码
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])
以上就是python实现逻辑回归的示例的详细内容,更多关于python 逻辑回归的资料请关注其它相关文章!
标签:
python,逻辑回归
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“python实现逻辑回归的示例”评论...
更新日志
2024年11月08日
2024年11月08日
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]