python实现梯度下降和逻辑回归
本文实例为大家分享了python实现梯度下降和逻辑回归的具体代码,供大家参考,具体内容如下
importnumpyasnp
importpandasaspd
importos
data=pd.read_csv("iris.csv")#这里的iris数据已做过处理
m,n=data.shape
dataMatIn=np.ones((m,n))
dataMatIn[:,:-1]=data.ix[:,:-1]
classLabels=data.ix[:,-1]
#sigmoid函数和初始化数据
defsigmoid(z):
return1/(1+np.exp(-z))
#随机梯度下降
defStocgrad_descent(dataMatIn,classLabels):
dataMatrix=np.mat(dataMatIn)#训练集
labelMat=np.mat(classLabels).transpose()#y值
m,n=np.shape(dataMatrix)#m:dataMatrix的行数,n:dataMatrix的列数
weights=np.ones((n,1))#初始化回归系数(n,1)
alpha=0.001#步长
maxCycle=500#最大循环次数
epsilon=0.001
error=np.zeros((n,1))
foriinrange(maxCycle):
forjinrange(m):
h=sigmoid(dataMatrix*weights)#sigmoid函数
weights=weights+alpha*dataMatrix.transpose()*(labelMat-h)#梯度
ifnp.linalg.norm(weights-error)0.5:
pred.append(1)
else:
pred.append(0)
data["pred"]=pred
os.remove("data_and_pred.csv")#删除List_lost_customers数据集#第一次运行此代码时此步骤不要
data.to_csv("data_and_pred.csv",index=False,encoding="utf_8_sig")#数据集保存
pred_result(dataMatIn)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。