题目太长啦!文档下载【传送门

第1题

简述:实现逻辑回归。

此处使用了minimize函数代替Matlab的fminunc函数,参考了该博客【传送门】。

 import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as op #S函数
def sigmoid(z):
g = 1/(1+np.exp(-z))
return g #cost计算函数
def costFunction(theta, X, y):
theta = np.array(theta).reshape((np.size(theta),1))
m = np.size(y)
h = sigmoid(np.dot(X, theta))
J = 1/m*(-np.dot(y.T, np.log(h)) - np.dot((1-y.T), np.log(1-h)))
return J.flatten() def gradient(theta, X, y):
theta = np.array(theta).reshape((np.size(theta), 1))
m = np.size(y)
h = sigmoid(np.dot(X, theta))
grad = 1/m*np.dot(X.T, h - y)
return grad.flatten() #读取数据,第一列是成绩1,第二列是成绩2,第三列是yes/no
data = np.loadtxt('ex2data1.txt', delimiter=',', dtype='float')
m = np.size(data[:, 0])
# print(data) #绘制样本点
X = data[:, 0:2]
y = data[:, 2:3]
pos = np.where(y == 1)[0]
neg = np.where(y == 0)[0]
X1 = X[pos, 0:2]
X0 = X[neg, 0:2]
plt.plot(X1[:, 0], X1[:, 1], 'k+')
plt.plot(X0[:, 0], X0[:, 1], 'yo')
plt.xlabel('Exam 1 score')
plt.ylabel('Exam 2 score') #求解最优解
one = np.ones(m)
X = np.insert(X, 0, values=one, axis=1)
initial_theta = np.zeros(np.size(X, 1))
result = op.minimize(fun=costFunction, x0=initial_theta, args=(X, y), method='TNC', jac=gradient)
# print(result)
theta = result.x
cost = result.fun
print('theta:', theta)
print('cost:', cost) #绘制决策边界
plot_x = np.array([np.min(X[:, 1]), np.max(X[:, 2])])
# print(plot_x)
plot_y = (-1/theta[2])*(theta[1]*plot_x+theta[0])
# print(plot_y)
plt.plot(plot_x,plot_y)
plt.legend(labels=['Admitted', 'Not admitted'])
plt.axis([30, 100, 30, 100])
plt.show() #预测[45 85]成绩的学生,并计算准确率
theta = np.array(theta).reshape((np.size(theta),1))
z = np.dot([1, 45, 85], theta)
prob = sigmoid(z)
print('For a student with scores 45 and 85, we predict an admission probability of ', prob)
p = np.round(sigmoid(np.dot(X,theta)))
acc = np.mean(p==y)*100
print('Train Accuracy: ',acc,'%')

运行结果:

第2题

简述:通过正规化实现逻辑回归。

 import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as op #S函数
def sigmoid(z):
g = 1/(1+np.exp(-z))
return g #cost计算函数
def costFunction(theta, X, y, lamb):
theta = np.array(theta).reshape((np.size(theta), 1))
m = np.size(y)
h = sigmoid(np.dot(X, theta))
J = 1/m*(-np.dot(y.T, np.log(h)) - np.dot((1-y.T), np.log(1-h)))
# 添加项
theta2 = theta[1:, 0]
Jadd = lamb/(2*m)*np.sum(theta2**2)
J = J + Jadd
return J.flatten() #求梯度
def gradient(theta, X, y, lamb):
theta = np.array(theta).reshape((np.size(theta), 1))
m = np.size(y)
h = sigmoid(np.dot(X, theta))
grad = 1/m*np.dot(X.T, h - y)
#添加项
theta[0,0] = 0
gradadd = lamb/m*theta
grad = grad + gradadd
return grad.flatten() #求特征矩阵
def mapFeature(X1, X2):
degree = 6
out = np.ones((np.size(X1),1))
for i in range(1, degree+1):
for j in range(0, i+1):
res = np.multiply(np.power(X1, i-j), np.power(X2, j))
out = np.insert(out, np.size(out[0, :]), values=res, axis=1)
return out #读取数据,第一列是成绩1,第二列是成绩2,第三列是yes/no
data = np.loadtxt('ex2data2.txt', delimiter=',', dtype='float')
m = np.size(data[:, 0]) #绘制样本点
X = data[:, 0:2]
y = data[:, 2:3]
pos = np.where(y == 1)[0]
neg = np.where(y == 0)[0]
X1 = X[pos, 0:2]
X0 = X[neg, 0:2]
plt.plot(X1[:, 0], X1[:, 1], 'k+')
plt.plot(X0[:, 0], X0[:, 1], 'yo')
plt.xlabel('Microchip Test 1')
plt.ylabel('Microchip Test 2')
plt.legend(labels=['y = 1', 'y = 0']) #数据初始化
X = mapFeature(X[:, 0], X[:, 1])
# print(X)
lamb = 1
initial_theta = np.zeros(np.size(X, 1)) #求解最优解
result = op.minimize(fun=costFunction, x0=initial_theta, args=(X, y, lamb), method='TNC', jac=gradient)
# print(result)
cost = result.fun
theta = result.x
print('theta:', theta)
print('cost:', cost) #绘制决策边界
u = np.linspace(-1, 1.5, 50)
v = np.linspace(-1, 1.5, 50)
z = np.zeros((np.size(u),np.size(v)))
theta = np.array(theta).reshape((np.size(theta), 1))
for i in range(0, np.size(u)):
for j in range(0, np.size(v)):
z[i, j] = np.dot(mapFeature(u[i], v[j]), theta)
# print(z)
plt.contour(u, v, z.T, [0])
plt.show() #计算准确率
p = np.round(sigmoid(np.dot(X,theta)))
acc = np.mean(p==y)*100
print('Train Accuracy: ',acc,'%')

运行结果:

机器学习作业(二)逻辑回归——Python(numpy)实现的更多相关文章

  1. 机器学习二 逻辑回归作业、逻辑回归(Logistic Regression)

    机器学习二 逻辑回归作业   作业在这,http://speech.ee.ntu.edu.tw/~tlkagk/courses/ML_2016/Lecture/hw2.pdf 是区分spam的. 57 ...

  2. 机器学习总结之逻辑回归Logistic Regression

    机器学习总结之逻辑回归Logistic Regression 逻辑回归logistic regression,虽然名字是回归,但是实际上它是处理分类问题的算法.简单的说回归问题和分类问题如下: 回归问 ...

  3. 机器学习算法整理(二)梯度下降求解逻辑回归 python实现

    逻辑回归(Logistic regression) 以下均为自己看视频做的笔记,自用,侵删! 还参考了:http://www.ai-start.com/ml2014/ 用梯度下降求解逻辑回归 Logi ...

  4. scikit-learn机器学习(二)逻辑回归进行二分类(垃圾邮件分类),二分类性能指标,画ROC曲线,计算acc,recall,presicion,f1

    数据来自UCI机器学习仓库中的垃圾信息数据集 数据可从http://archive.ics.uci.edu/ml/datasets/sms+spam+collection下载 转成csv载入数据 im ...

  5. Coursera-AndrewNg(吴恩达)机器学习笔记——第三周编程作业(逻辑回归)

    一. 逻辑回归 1.背景:使用逻辑回归预测学生是否会被大学录取. 2.首先对数据进行可视化,代码如下: pos = find(y==); %找到通过学生的序号向量 neg = find(y==); % ...

  6. 【机器学习基础】逻辑回归——LogisticRegression

    LR算法作为一种比较经典的分类算法,在实际应用和面试中经常受到青睐,虽然在理论方面不是特别复杂,但LR所牵涉的知识点还是比较多的,同时与概率生成模型.神经网络都有着一定的联系,本节就针对这一算法及其所 ...

  7. Stanford机器学习---第三讲. 逻辑回归和过拟合问题的解决 logistic Regression & Regularization

    原文:http://blog.csdn.net/abcjennifer/article/details/7716281 本栏目(Machine learning)包括单参数的线性回归.多参数的线性回归 ...

  8. 机器学习入门11 - 逻辑回归 (Logistic Regression)

    原文链接:https://developers.google.com/machine-learning/crash-course/logistic-regression/ 逻辑回归会生成一个介于 0 ...

  9. Spark机器学习(2):逻辑回归算法

    逻辑回归本质上也是一种线性回归,和普通线性回归不同的是,普通线性回归特征到结果输出的是连续值,而逻辑回归增加了一个函数g(z),能够把连续值映射到0或者1. MLLib的逻辑回归类有两个:Logist ...

随机推荐

  1. C#设计模式学习笔记:(17)中介者模式

    本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/7966240.html,记录一下学习过程以备后续查用. 一.引言 今天我们要讲行为型设计模式的第五个模式--中 ...

  2. springcloud 项目源码 微服务 分布式 Activiti6 工作流 vue.js html 跨域 前后分离

    1.代码生成器: [正反双向](单表.主表.明细表.树形表,快速开发利器)freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本.处理类.service等完整模块2. ...

  3. Javascript 基础学习(三)js 的原始类型和声明变量

    java的基本数据类型一共有 byte short int long float double char boolean js中定义变量使用关键字 var js的原始类型(五个) String: 字符 ...

  4. JavaScript将数组转换为链表

    JS中将数组转换为链表 /** * 将数组转换为链表 * @param array arr 需要转换的数组 * @param int type 转换的类型,0为单链表,1为循环链表 * @return ...

  5. 「Flink」配置使用Flink调试WebUI

    很多时候,我们在IDE中编写Flink代码,我们希望能够查看到Web UI,从而来了解Flink程序的运行情况.按照以下步骤操作即可,亲测有效. 1.添加Maven依赖 <dependency& ...

  6. Bellman-ford算法 无向图

    // 单源最短路问题 // Bellman-Ford算法 // 复杂度O(V*E) //! 可以判断负圈 #include <cstdio> #include <iostream&g ...

  7. Python3标准库:queue线程安全的FIFO实现

    1. queue线程安全的FIFO实现 queue模块提供了一个适用于多线程编程的先进先出(FIFO,first-in,first-out)数据结构,可以用来在生产者和消费者线程之间安全地传递消息或其 ...

  8. 面向对象+闭包+三种对象的声明方式(字面式、new Object、构造函数、工厂模式、原型模式、混合模式)

    面向对象: 对代码的一种抽象,对外统一提供调用接口的编程思想 对象的属性:事物自身拥有的东西 对象的方法:事物的功能 对象:事物的一个实例 对象的原型:.prototype -> 内存地址 -& ...

  9. LeetCode 56. Merge Intervals 合并区间 (C++/Java)

    题目: Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6] ...

  10. docker - apt-get更换国内源解决Dockerfile构建速度过慢

    背景 使用ubuntu镜像一般apt-get源地址都是在国外导致在构建时因为源地址问题导致下载速度极其得慢 在构建中应事先修改apt-get源地址来避免因下载速度过慢导致的构建缓慢问题 方案 在Doc ...