python實(shí)現(xiàn)邏輯回歸的示例
代碼
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets.samples_generator import make_classificationdef initialize_params(dims): w = np.zeros((dims, 1)) b = 0 return w, bdef sigmoid(x): z = 1 / (1 + np.exp(-x)) return zdef 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, dbdef linear_train(X, y, learning_rate, epochs): # 參數(shù)初始化 w, b = initialize_params(X.shape[1]) loss_list = [] for i in range(epochs): # 計(jì)算當(dāng)前的預(yù)測(cè)值、損失和梯度 y_hat, loss, dw, db = logistic(X, y, w, b) loss_list.append(loss) # 基于梯度下降的參數(shù)更新 w += -learning_rate * dw b += -learning_rate * db # 打印迭代次數(shù)和損失 if i % 10000 == 0: print('epoch %d loss %f' % (i, loss)) # 保存參數(shù) params = { ’w’: w, ’b’: b } # 保存梯度 grads = { ’dw’: dw, ’db’: db } return loss_list, loss, params, gradsdef predict(X, params): w = params[’w’] b = params[’b’] y_pred = sigmoid(np.dot(X, w) + b) return y_predif __name__ == '__main__': # 生成數(shù)據(jù) 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) # 生成偽隨機(jī)數(shù) rng = np.random.RandomState(2) X += 2 * rng.uniform(size=X.shape) # 劃分訓(xùn)練集和測(cè)試集 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) # 訓(xùn)練 loss_list, loss, params, grads = linear_train(X_train, y_train, 0.01, 100000) print(params) # 預(yù)測(cè) y_pred = predict(X_test, params) print(y_pred[:10])
以上就是python實(shí)現(xiàn)邏輯回歸的示例的詳細(xì)內(nèi)容,更多關(guān)于python 邏輯回歸的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Java commons-httpclient如果實(shí)現(xiàn)get及post請(qǐng)求2. 一文帶你徹底理解Java序列化和反序列化3. JS中6個(gè)對(duì)象數(shù)組去重的方法4. Python基于requests庫(kù)爬取網(wǎng)站信息5. vscode運(yùn)行php報(bào)錯(cuò)php?not?found解決辦法6. python中文本字符處理的簡(jiǎn)單方法記錄7. PHP laravel實(shí)現(xiàn)導(dǎo)出PDF功能8. Python使用Selenium自動(dòng)進(jìn)行百度搜索的實(shí)現(xiàn)9. PHP利用curl發(fā)送HTTP請(qǐng)求的實(shí)例代碼10. 資深程序員:給Python軟件開(kāi)發(fā)測(cè)試的25個(gè)忠告!

網(wǎng)公網(wǎng)安備