機器學習實踐二 -多分類和神經網絡

本次練習的任務是使用邏輯歸回和神經網絡進行識別手寫數字(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.pswp.cn/news/389021.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389021.shtml
英文地址,請注明出處:http://en.pswp.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類里定義數據…