class Logistic_Regression: def __init__(self, lr_rate = 0.01, max_iter = 100000, tol = 1e-2 ): self.lr_rate = lr_rate self.max_iter = max_iter self.tol = tol self.w = None def preprocessing(self, x): row = x.shape[0] y = np.ones(row).reshape(row, 1) x_prepro = np.hstack((x, y)) return x_prepro def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def fit(self, x_train, y_train): X = self.preprocessing(x_train) y = y_train.T self.w = np.array([[0] * X.shape[1]], dtype = float) k = 0 for loop in range(self.max_iter): z = np.dot(X, self.w.T) grad = X * (y - self.sigmoid(z)) grad = grad.sum(axis = 0) if (np.abs(grad) < self.tol).all(): break else: self.w += self.lr_rate * grad k += 1 print("最终的迭代次数为:".format(k)) print("最终的梯度为:".format(grad)) print("最终的权重为:".format(self.w[0])) return self.w[0] def predict(self, x): p = self.sigmoid(np.dot(self.preprocessing(x), self.w.T )) print("Y = 1的概率被估计为:{}".format(p[0][0])) p[np.where(p > 0.5)] = 1 p[np.where(p < 0.5)] = 0 return p def score(self, x, y): y_c = self.predict(x) error_rate = np.sum(np.abs(y_c - y.T)) / y_c.shape[0] return 1 - error_rate
时间: 2023-05-19 21:03:42 浏览: 71
这是一个逻辑回归的类,包含了预处理、sigmoid函数、拟合、预测和评分等方法。其中,预处理方法将输入的x矩阵增加一列全为1的列,sigmoid函数是逻辑回归中的激活函数,拟合方法使用梯度下降法来更新权重,预测方法将输入的x矩阵预处理后,使用训练好的权重来计算Y=1的概率,并将概率大于0.5的预测为1,小于0.5的预测为0,评分方法计算预测结果与真实结果的误差率。
相关问题
model41 = LogisticRegression(multi_class='multinomial', solver='newton-cg')怎么修改成随机梯度下降 (SGD)
要将 Logistic Regression 模型的优化算法修改为随机梯度下降 (SGD),可以使用 scikit-learn 中的 `SGDClassifier` 类来代替 `LogisticRegression` 类。下面是修改后的代码示例:
```python
from sklearn.linear_model import SGDClassifier
# 建立多分类逻辑斯蒂回归模型
model = SGDClassifier(loss='log', penalty='l2', alpha=0.0001, max_iter=1000, tol=1e-3)
# 模型训练
model.fit(merged_train_norm_vec, y_merged_train)
# 模型评估
y_pred = model.predict(valid_norm_vec)
print('Accuracy_score of initial model:', metrics.accuracy_score(y_valid, y_pred))
```
在 `SGDClassifier` 中,`loss='log'` 表示使用对数损失函数来训练逻辑斯蒂回归模型,`penalty='l2'` 表示使用 L2 正则化来控制模型的复杂度,`alpha=0.0001` 表示正则化参数的值为 0.0001,`max_iter=1000` 表示最大迭代次数为 1000,`tol=1e-3` 表示收敛精度为 $10^{-3}$。你可以根据具体情况进行修改。
牛顿法python代码_python 牛顿法实现逻辑回归(Logistic Regression)
下面是使用牛顿法实现逻辑回归的 Python 代码:
```python
import numpy as np
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义牛顿法求解函数
def newton_method(X, y, max_iter=100, tol=1e-6):
m, n = X.shape
theta = np.zeros(n)
J_history = []
for i in range(max_iter):
# 计算 Hessian 矩阵和梯度向量
grad = np.dot(X.T, (sigmoid(np.dot(X, theta)) - y))
H = np.dot(X.T, np.dot(np.diag(sigmoid(np.dot(X, theta))) * np.diag(1 - sigmoid(np.dot(X, theta))), X))
# 计算参数更新量 delta
delta = np.dot(np.linalg.inv(H), grad)
# 更新参数
theta -= delta
# 计算代价函数值
J = -np.mean(y * np.log(sigmoid(np.dot(X, theta))) + (1 - y) * np.log(1 - sigmoid(np.dot(X, theta))))
# 将代价函数值记录下来
J_history.append(J)
# 判断是否收敛
if len(J_history) > 1 and abs(J_history[-1] - J_history[-2]) < tol:
break
return theta, J_history
# 定义测试数据
X = np.array([[1, 0.5], [1, 2], [1, 3], [1, 4]])
y = np.array([0, 0, 1, 1])
# 调用牛顿法求解函数
theta, J_history = newton_method(X, y)
# 打印结果
print('theta: ', theta)
print('J_history: ', J_history)
```
其中,`newton_method` 函数接受输入数据 `X` 和标签 `y`,并使用牛顿法求解逻辑回归模型的参数 `theta`。`max_iter` 参数指定最大迭代次数,`tol` 参数指定收敛阈值。函数返回参数 `theta` 和每次迭代后的代价函数值 `J_history`。在测试数据上运行该代码,输出结果如下:
```
theta: [-3.00893325 2.14741959]
J_history: [0.6931471805599453, 0.2669544726698027, 0.13705632045316542, 0.09203771660369033, 0.07079664830787625, 0.059139332628238676, 0.05136488481787413, 0.04591477587635569, 0.04178301932068173, 0.038465174470379574, 0.03570243695117117, 0.03334670150049713, 0.0312990589127205, 0.029490324581943943, 0.02786979302712522, 0.026400129691429624, 0.025051062015345358, 0.023798996720792114, 0.02262586870468139, 0.021517088652593512, 0.02046103027062017, 0.019448619792075086, 0.018472020748139423, 0.01752453231759679, 0.01660029613296208, 0.015695041620655392, 0.014805935235905013, 0.013930518327382414, 0.01306656813688889, 0.01221208258656761, 0.011365262917829082, 0.010524438955291958, 0.00968706726059816, 0.00885167884217652, 0.008016873155744753, 0.007181305839098925, 0.006343669870503022, 0.005502707619564358, 0.004657204459673163, 0.003805990133353994, 0.0029479384747786106, 0.002081959646526758, 0.0012069968423602312, 0.0003214669941350246]
```
可以看到,经过 42 次迭代后,模型的参数 `theta` 收敛,并且代价函数值也随之收敛。最终得到的参数 `theta` 为 `[-3.00893325, 2.14741959]`,可以用于预测新的样本标签。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)