# 逻辑斯提回归 用来分类
import numpy as np
import math
import matplotlib.pyplot as plt
#w0 * 1 =b
def loadData():
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
def sigmoid(inX):
return 1.0/(1.0+np.exp(-inX))
#转为mat利用矩阵相乘,每次全部数据都参与运算
def gradAscent(dataMatIn, classlabelIn):
dataMat = np.mat(dataMatIn)
classlabel = np.mat(classlabelIn).T
m, n = np.shape(dataMat)
alpha = 0.001
maxiter = 500
weights = np.ones([n, 1])
for k in range(maxiter):
h = sigmoid(dataMat*weights)
error = classlabel - h
weights += alpha*dataMat.transpose()*error
return weights
dataMat, labelMat = loadData()
weights = gradAscent(dataMat, labelMat)
print(weights)
#getA 将numpy数组转为array
dataArr = np.array(dataMat)
n = np.shape(dataArr)[0]
xcord1, ycord1 = [], []
xcord2, ycord2 = [], []
for i in range(n):
if labelMat[i] == 1:
xcord1.append(dataArr[i, 1])
ycord1.append(dataArr[i, 2])
else:
xcord2.append(dataArr[i, 1])
ycord2.append(dataArr[i, 2])
plt.figure()
plt.scatter(xcord1, ycord1, c='red')
plt.scatter(xcord2, ycord2, c='green')
x = np.arange(-3, 3, 0.1)
y = (-weights[0]-weights[1]*x)/weights[2]
plt.plot(x, y)
plt.show()