从疝气病症预测病马的死亡率
说明:
将 horseColicTraining.txt
和 horseColicTest.txt
放在当前目录下。
import numpy as np
import matplotlib.pyplot as plt
定义 Sigmoid 函数
def sigmoid(inX):
return 1.0 / (1 + np.exp(-inX))
定义一般的梯度提升算法
def gradAscent(dataMatIn, classLabels):
#转换成numpy的mat矩阵
dataMatrix = np.mat(dataMatIn)
#转换成numpy的mat矩阵并且转置
labelMat = np.mat(classLabels).transpose()
m, n = np.shape(dataMatrix)
alpha = 0.001
#设置最大迭代次数为500次
maxCycles = 500
#权重全部初始化为1
weights = np.ones((n, 1))
for k in range(maxCycles):
"""
批量梯度上升法
"""
h = sigmoid(dataMatrix*weights)
error = (labelMat - h)
weights = weights + alpha * dataMatrix.transpose