Python实现logistics回归
Python 实现 回归
2023-09-14 09:14:57 时间
import numpy as np
def sigmoid(x):
#请补全逻辑回归函数
return 1.0/(1+np.exp(-x))
def predict(x_test, weight):
if sigmoid(weight.T @ x_test) > 0.5:
return 1
return 0
#实现逻辑回归的训练
def fit(x, y):
m, n = x.shape
w = np.zeros(n).reshape((n,1))
y = y.reshape((m,1))
r = 0.001 #learning rate
cnt = 0
max_cnt = 10000 #设置最大迭代次数
t = 0.00001 #设置收敛条件
#利用梯度下降方法求最优解
#............................
for i in range(max_cnt):
# x:11*3 w:3*1
de = np.dot(x.T, y - sigmoid(np.dot(x,w)))
w += r*de
if np.linalg.norm(r*de)<=t:
break
# w:3*1
return w
if __name__ == '__main__':
x_train = np.array([
[1, 2.697, 6.254],
[1, 1.872, 2.014],
[1, 2.312, 0.812],
[1, 1.983, 4.990],
[1, 0.932, 3.920],
[1, 1.321, 5.583],
[1, 2.215, 1.560],
[1, 1.659, 2.932],
[1, 0.865, 7.362],
[1, 1.685, 4.763],
[1, 1.786, 2.523]
])
y_train = np.array([1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1])
weight = fit(x_train, y_train)
print(weight)
lis = []
#调用预测函数,输出x_train的预测结果,并输出准确率
for i in range(11):
lis.append(predict(x_train[i],weight))
print(lis)
n = 0 # 正确计数
for i in range(11):
if lis[i] == y_train[i]:
n+=1
print("正确率%s%%" %(n/11*100))
[[-3.29407748]
[ 0.02245258]
[ 0.79967711]]
[1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0]
正确率81.81818181818183%
相关文章
- Python中elasticsearch插入和更新数据的实现方法
- 用Python实现一个大数据搜索引擎
- Python协程的四种实现方式
- Python语言学习:Python语言学习之python包/库package的简介(模块的封装/模块路径搜索/模块导入方法/自定义导入模块实现华氏-摄氏温度转换案例应用)、使用方法、管理工具之详细攻略
- Python编程语言学习:python的列表的特殊应用之一行命令实现if判断中的两类判断
- Python的IDE:基于Eclipse/MyEclipse软件的PyDev插件配置python的开发环境(不同python项目加载不同版本的python)—从而实现Python编程图文教程之详细攻略
- Python:利用python代码编程实现将视频的avi格式转换为MP4格式
- 已解决Visit python.org to download an earlier version of Python.
- 人工智能——线性回归(Python实现)
- https如何使用python+flask来实现
- Python实现哈里斯鹰优化算法(HHO)优化Catboost回归模型(CatBoostRegressor算法)项目实战
- Python实现GWO智能灰狼优化算法优化LightGBM回归模型(LGBMRegressor算法)项目实战
- Python实现GWO智能灰狼优化算法优化循环神经网络回归模型(LSTM回归算法)项目实战
- Python实现PSO粒子群优化循环神经网络LSTM回归模型项目实战
- Python实现ACO蚁群优化算法优化支持向量机回归模型(SVR算法)项目实战
- Python实现SMA黏菌优化算法优化支持向量机回归模型(SVR算法)项目实战
- Python实现决策树回归模型(DecisionTreeRegressor算法)并应用网格搜索算法调优项目实战
- Python实现贝叶斯岭回归模型(BayesianRidge算法)并使用K折交叉验证进行模型评估项目实战
- Python实现PSO粒子群优化支持向量机回归模型(svr算法)项目实战
- 设置Python打印格式
- 【华为OD机试Python实现】HJ69 矩阵乘法(中等)
- python里使用协程和StreamReader、StreamWriter来创建echo服务端
- python基础===一行 Python 代码实现并行(转)
- python基础===jieba模块,Python 中文分词组件
- Python开发学习之Python和Excel的数据实现互通