机器学习实践二 -多分类和神经网络

本次练习的任务是使用逻辑归回和神经网络进行识别手写数字(form 0 to 9, 自动手写数字问题已经应用非常广泛,比如邮编识别。

使用逻辑回归进行多分类分类

练习2 中的logistic 回归实现了二分类分类问题,现在将进行多分类,one vs all。

加载数据集

这次数据时MATLAB 的格式,使用Scipy.io.loadmat 进行加载。Scipy是一个用于数学、科学、工程领域的常用软件包,可以处理插值、积分、优化、图像处理、常微分方程数值解的求解、信号处理等问题。它可用于计算Numpy矩阵,使Numpy和Scipy协同工作。

import numpy as np
import scipy.io
from scipy.io import loadmat
import matplotlib.pyplot as plt
import scipy.optimize as optdata = scipy.io.loadmat('ex3data1.mat')
X = data['X']
y = data['y']

在这里插入图片描述
数据集共有5000个样本, 每个样本是20*20的灰度图像。

visuazing the data

随机展示100个图像

def display_data(sample_images):fig, ax_array = plt.subplots(nrows=10, ncols=10, figsize=(6, 4))for row in range(10):for column in range(10):ax_array[row, column].matshow(sample_images[10 * row + column].reshape((20, 20)).T, cmap='gray')ax_array[row, column].axis('off')plt.show()returnrand_samples = np.random.permutation(X.shape[0]) # 打乱顺序
sample_images = X[rand_samples[0:100], :]
display_data(sample_images)

在这里插入图片描述

Vectorizing Logistic Regression

看一下logistic回归的代价函数:
在这里插入图片描述
其中:
在这里插入图片描述
进行向量化运算:
在这里插入图片描述

def sigmoid(z):return 1 / (1 + np.exp(-z))
def regularized_cost(theta, X, y, l):thetaReg = theta[1:]first = (-y*np.log(sigmoid(X.dot(theta)))) + (y-1)*np.log(1-sigmoid(X.dot(theta)))reg = (thetaReg.dot(thetaReg))*l / (2*len(X))return np.mean(first) + reg

gradient

def regularized_gradient(theta, X, y, l):thetaReg = theta[1:]first = (1 / len(X)) * X.T @ (sigmoid(X.dot(theta)) - y)reg = np.concatenate([np.array([0]), (l / len(X)) * thetaReg])return first + reg

one-vs-all Classification

这个任务,有10个类,logistics是二分类算法,用在多分类上原理就是把所有的数据分为“某类”和“其它类”

from scipy.optimize import minimizedef one_vs_all(X, y, l, K):all_theta = np.zeros((K, X.shape[1]))  # (10, 401)for i in range(1, K+1):theta = np.zeros(X.shape[1])y_i = np.array([1 if label == i else 0 for label in y])ret = minimize(fun=regularized_cost, x0=theta, args=(X, y_i, l), method='TNC',jac=regularized_gradient, options={'disp': True})all_theta[i-1,:] = ret.x             return all_theta

向量化操作检错,经验的机器学习工程师通常会检验矩阵的维度,来确认操作是否正确。

predict

def predict_one_vs_all(all_theta, X):m = np.size(X, 0)# You need to return the following variables correctly# Add ones to the X data matrixX = np.c_[np.ones((m, 1)), X]hypothesis = sigmoid(X.dot(all_theta.T)pred = np.argmax(hypothesis), 1) + 1return pred

这里的hypothesis.shape =[5000 * 10], 对应5000个样本,每个样本对应10个标签的概率。取 概率最大的的值,作为最终预测结果。pred 是最终的5000个样本预测数组。

pred = predict_one_vs_all(all_theta, X)
print('Training Set Accuracy: %.2f%%' % (np.mean(pred == y) * 100))

Neural Networks

这里只需要验证所给权重数据,也就是theta,查看分类准确性。

## ================ Part 2: Loading Pameters ================
print('Loading Saved Neural Network Parameters ...')# Load the weights into variables Theta1 and Theta2
weight = scipy.io.loadmat('ex3weights.mat')
Theta1, Theta2 = weight['Theta1'], weight['Theta2']

predict

def load_weight(path):data = loadmat(path)return data['Theta1'], data['Theta2']theta1, theta2 = load_weight('ex3weights.mat')
theta1.shape, theta2.shapeX = np.insert(X, 0, values=np.ones(X.shape[0]), axis=1)  # intercept
#
#正向传播
a1 = X
z2 = a1.dot(theta1.T)
z2.shape
z2 = np.insert(z2, 0, 1, axis=1)
a2 = sigmoid(z2)
a2.shape
z3 = a2.dot(theta2.T)
z3.shape
a3 = sigmoid(z3)
a3.shapey_pred = np.argmax(a3, axis=1) + 1
accuracy = np.mean(y_pred == y)
print ('accuracy = {0}%'.format(accuracy * 100)) # accuracy = 97.52%

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/389021.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Hadoop 倒排索引

倒排索引是文档检索系统中最常用的数据结构,被广泛地应用于全文搜索引擎。它主要是用来存储某个单词(或词组)在一个文档或一组文档中存储位置的映射,即提供了一种根据内容来查找文档的方式。由于不是根据文档来确定文档所包含的内…

koa2异常处理_读 koa2 源码后的一些思考与实践

koa2的特点优势什么是 koa2Nodejs官方api支持的都是callback形式的异步编程模型。问题:callback嵌套问题koa2 是由 Express原班人马打造的,是现在比较流行的基于Node.js平台的web开发框架,Koa 把 Express 中内置的 router、view 等功能都移除…

Bind9的dns解析服务

前言随着原中国电信集团按南北地域分家,新的中国电信和网通集团随即成立,互联网的骨干网也被一分为二了,北有网通、南有电信。从此,细心的网民可以发现,有些经常访问的网站速度一下子慢了下来,有时候还有访…

上凸包和下凸包_使用凸包聚类

上凸包和下凸包I recently came across the article titled High-dimensional data clustering by using local affine/convex hulls by HakanCevikalp in Pattern Recognition Letters. It proposes a novel algorithm to cluster high-dimensional data using local affine/c…

sqlmap手册

sqlmap用户手册 | by WooYun知识库 sqlmap用户手册 当给sqlmap这么一个url (http://192.168.136.131/sqlmap/mysql/get_int.php?id1) 的时候,它会: 1、判断可注入的参数 2、判断可以用那种SQL注入技术来注入 3、识别出哪种数据库 4、根据用户选择&…

幸运三角形 南阳acm491(dfs)

幸运三角形 时间限制:1000 ms | 内存限制:65535 KB 难度:3描述话说有这么一个图形,只有两种符号组成(‘’或者‘-’),图形的最上层有n个符号,往下个数依次减一,形成倒置…

jsforim

var isMouseDownfalse;var isFirsttrue;var centerdivObj;var ndiv1;var ndiv2;var ndiv3;var kjX;var kjY; window.οnerrοrfunction(){ return true;}; var thurlhttp://qq.jutoo.net/;var wzId12345; function createDiv(){ var sWscreen.width; var sHscree…

决策树有框架吗_决策框架

决策树有框架吗In a previous post, I mentioned that thinking exhaustively is exhausting! Volatility and uncertainty are ever present and must be factored into our decision making — yet, we often don’t have the time or data to properly account for it.在上一…

凑个热闹-LayoutInflater相关分析

前言 最近给组内同学做了一次“动态换肤和换文案”的主题分享,其中的核心就是LayoutInflater类,所以把LayoutInflater源码梳理了一遍。巧了,这周掘金新榜和部分公众号都发布了LayoutInflater或者换肤主题之类的文章。那只好站在各位大佬的肩膀…

ASP.NET Core文件上传、下载与删除

首先我们需要创建一个form表单如下: <form method"post" enctype"multipart/form-data" asp-controller"UpLoadFile" asp-action"FileSave"> <div> <div> <p>Form表单多个上传文件:</p> <input type…

8 一点就消失_消失的莉莉安(26)

文|明鸢Hi&#xff0c;中午好&#xff0c;我是暖叔今天是免费连载《消失的莉莉安》第26章消失的莉莉安▶▶往期链接&#xff1a;▼ 向下滑动阅读1&#xff1a;“消失的莉莉安(1)”2&#xff1a; 消失的莉莉安(2)3&#xff1a;“消失的莉莉安(3)”4&#xff1a;“消失的莉莉安…

透明的WinForm窗体

this.Location new System.Drawing.Point(100, 100); this.Cursor System.Windows.Forms.Cursors.Hand; // 定义在窗体上&#xff0c;光标显示为手形 this.Text "透明的WinForm窗体&#xff01;"; // 定义窗体的标题…

mysql那本书适合初学者_3本书适合初学者

mysql那本书适合初学者为什么要书籍&#xff1f; (Why Books?) The internet is a treasure-trove of information on a variety of topics. Whether you want to learn guitar through Youtube videos or how to change a tire when you are stuck on the side of the road, …

junit与spring-data-redis 版本对应成功的

spring-data-redis 版本:1.7.2.RELEASE junit 版本:4.12 转载于:https://www.cnblogs.com/austinspark-jessylu/p/9366863.html

语音对话系统的设计要点与多轮对话的重要性

这是阿拉灯神丁Vicky的第 008 篇文章就从最近短视频平台的大妈与机器人快宝的聊天说起吧。某银行内&#xff0c;一位阿姨因等待办理业务的时间太长&#xff0c;与快宝机器人展开了一场来自灵魂的对话。对于银行工作人员的不满&#xff0c;大妈向快宝说道&#xff1a;“你们的工…

c读取txt文件内容并建立一个链表_C++链表实现学生信息管理系统

可以增删查改&#xff0c;使用链表存储&#xff0c;支持排序以及文件存储及数据读取&#xff0c;基本可以应付期末大作业&#xff08;狗头&#xff09; 界面为源代码为一个main.cpp和三个头文件&#xff0c;具体为 main.cpp#include <iostream> #include <fstream>…

注册表启动

public void SetReg() { RegistryKey hklmRegistry.LocalMachine; RegistryKey runhklm.CreateSubKey("Software/Microsoft/Windows/CurrentVersion/Run"); //定义hklm指向注册表的LocalMachine,对注册表的结构&#xff0c;可以在windows的运行里&#…

阎焱多少身价_2020年,数据科学家的身价是多少?

阎焱多少身价Photo by Christine Roy on Unsplash克里斯汀罗伊 ( Christine Roy) 摄于Unsplash Although we find ourselves in unprecedented times of uncertainty, current events have shown just how valuable the fields of Data Science and Computer Science truly are…

Django模型定义参考

字段 对字段名称的限制 字段名不能是Python的保留字&#xff0c;否则会导致语法错误字段名不能有多个连续下划线&#xff0c;否则影响ORM查询操作Django模型字段类 字段类说明AutoField自增ID字段BigIntegerField64位有符号整数BinaryField存储二进制数据的字段&#xff0c;对应…

精通Quartz-入门-Job

JobDetail实例&#xff0c;并且&#xff0c;它通过job的类代码引用这个job来执行。每次调度器执行job时&#xff0c;它会在调用job的execute(..)方法之前创建一个他的实例。这就带来了两个事实&#xff1a;一、job必须有一个不带参数的构造器&#xff0c;二、在job类里定义数据…