当前位置:网站首页>机器学习,吴恩达逻辑回归
机器学习,吴恩达逻辑回归
2022-07-23 06:15:00 【starmultiple】
一
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#路径来源
path = 'ex2data1.txt'
data = pd.read_csv(path, header=None, names=['Exam1 score', 'Exam2 score', 'Admitted'])
data.head()
data.describe()
#积极为1,消极为0
pos = data[data['Admitted'].isin([1])]
neg = data[data['Admitted'].isin([0])]
#画出图像
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(pos['Exam1 score'], pos['Exam2 score'], s=50, c='black', marker='+', label='Admitted')
ax.scatter(neg['Exam1 score'], neg['Exam2 score'], s=50, c='y', marker='o', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam1 Score')
ax.set_ylabel('Exam2 Score')
plt.show()

二、sigmoid函数

def sigmoid(z):
return 1 / (1 + np.exp(-z))
nums = np.arange(-10, 10, step=0.5)
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(nums, sigmoid(nums), 'r')
plt.show()

三、代价函数

def cost(theta, X, Y):
first = Y * np.log(sigmoid([email protected].T))
second = (1 - Y) * np.log(1 - sigmoid([email protected].T))
return -1 * np.mean(first + second)
#预处理数据
# add ones column
data.insert(0, 'Ones', 1)
# set X(training data) and Y(target variable)
X = data.iloc[:, 0: -1].values
Y = data.iloc[:, -1].values
theta = np.zeros(3)
print(cost(theta, X, Y))#0.6931471805599453
四、梯度下降
#偏导公式
# 计算步长
def gradient(theta, X, Y):
return (1/len(X) * X.T @ (sigmoid(X @ theta.T) - Y))
print(gradient(theta, X, Y))#[ -0.1 -12.00921659 -11.26284221]
#gradient只是计算了梯度下降$\theta$更新的步长,使用Scipy.optimize.fmin_tnc拟合最优的$\theta$
#拟合参数
#拟合参数
import scipy.optimize as opt
result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, Y))
#print(result)#(array([-25.1613187 , 0.20623159, 0.20147149]), 36, 0)
type(result)
cost(result[0], X, Y)
#使用Scipy.optimize.minimize拟合最优的$\theta$公式
res = opt.minimize(fun=cost, x0=np.array(theta), args=(X, np.array(Y)), method='Newton-CG', jac=gradient)
cost(res.x, X, Y)

五、决策边界
coef = -res.x / res.x[2]
x = np.arange(30, 100, 0.5)
y = coef[0] + coef[1] * x
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(pos['Exam1 score'], pos['Exam2 score'], s=50, c='black', marker='+', label='Admitted')
ax.scatter(neg['Exam1 score'], neg['Exam2 score'], s=50, c='y', marker='o', label='Not Admitted')
ax.plot(x, y, label='Decision Boundary', c='grey')
ax.legend()
ax.set_xlabel('Exam1 Score')
ax.set_ylabel('Exam2 Score')
plt.show()

边栏推荐
- Common scheduled cron expressions for scheduled tasks
- [jzof] 11 minimum number of rotation array
- 网易白帽子黑客训练营笔记(2)
- 当输入网址后,到网页显示,期间发生了什么
- CORTEX-A系列处理器
- redis分布式锁实践
- Space shooting part 1: player spirit and control
- The context of virtual memory technology (Part 1)
- Paging collections using streams
- 北大博士小姐姐:分享压箱底干货 | 五招提高学习效率
猜你喜欢

倍福和C#通过ADS通信传输Real类型

Functional testing to automated testing, sharing ten years of automated testing experience

太空射击 Part 2-3: 子弹与敌人碰撞处理

转行软件测试有学历要求吗?低于大专是真的没出路吗?

MySQL----复合查询 外连接

Cortex-a series processor

Beifu PLC and C transmit int array type variables through ads communication

CORTEX-A系列处理器

第十天笔记

Machine learning: Li Hang - statistical learning method (II) perceptron + code implementation (primitive + dual form)
随机推荐
【NOI模拟赛】不知是哪一道CF的论文题(概率期望,鞅的停时定理)
Machine learning: Li Hang - statistical learning method (II) perceptron + code implementation (primitive + dual form)
How does redis implement persistence? Explain in detail the three triggering mechanisms of RDB and their advantages and disadvantages, and take you to quickly master RDB
虚拟内存技术的来龙去脉(上)
[actf2020 freshman competition]backupfile 1
倍福PLC和C#通过ADS通信传输结构体类型变量
Opencv video operation
com.mysql.cj.jdbc.exceptions. MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value:
成功 万象奥科与CODESYS技术联合调测
Talk about study and work -- Qian Xuesen
PHP framework MVC class code audit
The relationship between method area, perpetual generation and meta space
倍福PLC和C#通过ADS通信传输int类型变量
0722~线程池扩展
Beifu PLC and C transmit int array type variables through ads communication
C语言-大端存储和小端存储
php框架MVC类代码审计
Intégrité du signal (si) intégrité de l'alimentation électrique (PI) notes d'apprentissage (32) Réseau de distribution d'énergie (4)
Successful joint commissioning of Vientiane Aoke and CoDeSys Technology
【日常训练】814. 二叉树剪枝