Logistic回归python代码
时间: 2023-11-13 14:51:49 浏览: 98
Logistic回归的Python代码如下:
```python
import numpy as np
# 加载数据集
def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
labelMat.append(int(lineArr[2]))
return dataMat,labelMat
# Sigmoid函数
def sigmoid(inX):
return 1.0 / (1 + np.exp(-inX))
# 梯度上升算法
def gradAscent(dataMatIn, classLabels):
dataMatrix = np.mat(dataMatIn)
labelMat = np.mat(classLabels).transpose()
m, n = np.shape(dataMatrix)
alpha = 0.001
maxCycles = 500
weights = np.ones((n,1))
for k in range(maxCycles):
h = sigmoid(dataMatrix * weights)
error = labelMat - h
weights = weights + alpha * dataMatrix.transpose() * error
return weights
# 测试代码
dataMat,labelMat = loadDataSet()
weights = gradAscent(dataMat, labelMat)
print(weights)
```
阅读全文