开发语言 Python逻辑回归(1) - ymat-h
θ更新过程可以写成:
正则化后的梯度下降算法θ的更新变为:
代码部分:
使用如下所示数据100条
数据加载
class Logistic_regression():
#初始化
def init(self):
self.xmat = list();
self.ymat = list();
#数据加载处理
def loadData(self,filename):
file = open(filename);
lines = file.readlines();
#print(lineArry);
for line in lines:
lineArry = line.strip().split();# split 用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
dataline = [1.0];
for i in range(len(lineArry)):
dataline.append(float(lineArry[i]));
#print(“dataline”,dataline);
label = dataline.pop();
self.ymat.append(int(label));#删除最后一个 并返回
self.xmat.append(dataline);
self.xmat = np.mat(self.xmat); # mat()函数 转换为矩阵
self.ymat = np.mat(self.ymat).transpose();
#print(“len”,len(self.xmat));
#print(self.xmat);
sigmoid函数
定义sigmoid函数
def sigmod(self,X):
return 1/(1-np.exp(-X));
梯度下降
梯度下降计算权重0
def stocGradAscent0(self,maxCycles=1000,alpha=0.001):
m,n = np.shape(self.xmat);
weights = np.ones((n,1));
for i in range(maxCycles):
h = self.sigmod(self.xmat*weights);
error = self.ymat-h;
#print(“error”,np.shape(error))
#print(“xmat”,np.shape(self.xmat.transpose()))
weights+=alpha*self.xmat.transpose()*error; #ranspose()转置
return weights;
画图
#画出最终分类图
def plotBestfit(self,weights):
xcord1 = [];
xcord2 = [];
ycord1 = [];
ycord2 = [];
for i in range(len(self.xmat)):
label = self.ymat[i];
#print(int(label))
#用x1 代表x坐标 x2 代表y坐标
if int(label) == 1:
xcord1.append(self.xmat[i,1]);
ycord1.append(self.xmat[i,2]);
else:
xcord2.append(self.xmat[i,1]);
ycord2.append(self.xmat[i,2]);
#print(xcord1,xcord2,ycord1,ycord2)
plt.figure();
#定义线条颜色
plt.scatter(xcord1,ycord1,s=30,c=‘red’,marker=‘s’);
plt.scatter(xcord2,ycord2,s=30,c=‘green’);
#坐标轴
x = np.arange(-3.0,3.0,0.1); # 从-3.0 到 3.0 步长为0.1
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)
edf79.png)
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注Python)
精彩文章,开发语言 拼多多帮助力入口