使用NumPy从头开始实现神经网络

yizhihongxing

以下是使用NumPy从头开始实现神经网络的完整攻略以及两个示例:

一、准备工作

  1. 安装NumPy库。

  2. 准备数据集。神经网络需要有数据进行训练和测试,因此需要准备数据集。这里以鸢尾花数据集为例。

  3. 导入NumPy和数据集。

import numpy as np
from sklearn.datasets import load_iris

iris = load_iris()

二、数据预处理

  1. 分离训练集和测试集。将数据集分为训练集和测试集,通常测试集占数据集的20-30%。
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size = 0.3)
  1. 归一化。由于特征值的取值范围不同,需要将特征值归一化,确保在同一范围内和同一数据格式内。
X_train = X_train / np.max(X_train)
X_test = X_test / np.max(X_test)
  1. One-hot编码。将标签值变成一个向量,向量的长度等于标签可选范围的个数,每个值对应一个可能的取值,与实际取值完全对应的位置上放置1,其余位置则为0。
def one_hot(y):
    y_onehot = np.zeros((y.shape[0], np.unique(y).shape[0]))
    for i in range(y.shape[0]):
        y_onehot[i, y[i]] = 1
    return y_onehot

y_train = one_hot(y_train)
y_test = one_hot(y_test)

三、构建神经网络

  1. 初始化权重。权重即神经网络中每个神经元与其他神经元相互接触的连接权重,需要初始化为随机值。
def init_params(layer_dimensions):
    params = {}
    L = len(layer_dimensions)

    for l in range(1, L):
        params['W' + str(l)] = np.random.randn(layer_dimensions[l], layer_dimensions[l-1]) * 0.01
        params['b' + str(l)] = np.zeros((layer_dimensions[l], 1))

    return params

params = init_params([4, 10, 3])
  1. 前向传播。由于神经网络的本质就是通过前向传播来预测输出结果,因此需要编写前向传播算法。
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def forward_propagation(X, params):
    L = len(params) // 2
    A = X

    for l in range(1, L):
        A_prev = A
        Z = np.dot(params['W' + str(l)], A_prev) + params['b' + str(l)]
        A = sigmoid(Z)

    ZL = np.dot(params['W' + str(L)], A) + params['b' + str(L)]
    AL = np.exp(ZL) / np.sum(np.exp(ZL), axis = 0)

    return AL

AL = forward_propagation(X_train, params)
  1. 计算损失函数。定义损失函数是为了衡量预测结果和实际结果的差距。
def compute_cost(AL, Y):
    m = Y.shape[1]
    cost = (-1/m) * np.sum(np.dot(Y, np.log(AL).T) + np.dot(1-Y, np.log(1-AL).T))
    cost = np.squeeze(cost)
    return cost

cost = compute_cost(AL, y_train)
  1. 反向传播更新权重。定义反向传播函数进行权重的更新。
def sigmoid_backward(dA, Z):
    A = sigmoid(Z)
    return dA * A * (1 - A)

def backward_propagation(AL, Y, cache):
    grads = {}
    L = len(cache) // 3
    m = Y.shape[1]
    Y = Y.reshape(AL.shape)
    dZL = AL - Y

    dAL_prev = dZL
    for l in reversed(range(1, L+1)):
        A_prev = cache['A' + str(l-1)]
        dZ = np.multiply(sigmoid_backward(dAL_prev, cache['Z' + str(l-1)]), dAL_prev)
        grads['dW' + str(l)] = np.dot(dZ, A_prev.T) / m
        grads['db' + str(l)] = np.sum(dZ, axis = 1, keepdims=True) / m
        dAL_prev = np.dot(cache['W' + str(l)].T, dZ)
    return grads

grads = backward_propagation(AL, y_train, cache)
  1. 使用梯度下降法更新参数。
def update_params(params, grads, learning_rate):
    L = len(params) // 2

    for l in range(1, L+1):
        params['W' + str(l)] = params['W' + str(l)] - learning_rate * grads['dW' + str(l)]
        params['b' + str(l)] = params['b' + str(l)] - learning_rate * grads['db' + str(l)]

    return params

params = update_params(params, grads, learning_rate = 0.01)

四、模型训练和预测

  1. 定义模型训练函数,使用整个数据集进行多次迭代来训练神经网络模型。
def model(X_train, Y_train, layer_dimensions, learning_rate = 0.01, num_iterations = 10000, print_cost = False):
    params = init_params(layer_dimensions)

    for i in range(num_iterations):
        AL = forward_propagation(X_train, params)
        cost = compute_cost(AL, Y_train)
        grads = backward_propagation(AL, Y_train, cache)
        params = update_params(params, grads, learning_rate)

        if print_cost and i % 1000 == 0:
            print('Cost after iteration %i: %f' %(i, cost))

    return params

params = model(X_train.T, y_train.T, [4, 10, 3])
  1. 定义模型预测函数。
def predict(X, params):
    AL = forward_propagation(X, params)
    predictions = np.argmax(AL, axis = 0)
    return predictions

y_pred = predict(X_test.T, params)

五、代码示例

下面给出两个代码示例,分别使用神经网络解决手写数字识别和狗与猫分类问题。

  1. 手写数字识别

准备数据集。

from sklearn.datasets import load_digits

digits = load_digits()

X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size = 0.3)

X_train = X_train / np.max(X_train)
X_test = X_test / np.max(X_test)

y_train = one_hot(y_train)
y_test = one_hot(y_test)

定义模型。以多层神经网络为例。

params = model(X_train.T, y_train.T, [64, 128, 64, 10], learning_rate = 0.1, num_iterations = 3000, print_cost = True)

预测结果。

y_pred = predict(X_test.T, params)
  1. 狗与猫分类问题

准备数据集。

import os

path = 'train/'

def load_data(path):
    X = []
    y = []
    for file in os.listdir(path):
        if 'dog' in file:
            y.append(1)
        elif 'cat' in file:
            y.append(0)
        img = cv2.imread(os.path.join(path,file))
        img = cv2.resize(img, (64, 64), interpolation = cv2.INTER_AREA)
        X.append(img)

    return np.array(X), np.array(y)

X_train, y_train = load_data(path)
X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size = 0.3)
X_train = X_train / 255
X_test = X_test / 255

y_train = y_train.reshape((-1, 1))
y_test = y_test.reshape((-1, 1))

y_train = one_hot(y_train)
y_test = one_hot(y_test)

定义模型。以卷积神经网络为例。

params = model(X_train.T, y_train.T, [64, 128, 256, 512, 2], learning_rate = 0.001, num_iterations = 10, print_cost = True)

预测结果。

y_pred = predict(X_test.T, params)

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用NumPy从头开始实现神经网络 - Python技术站

(0)
上一篇 2023年3月25日
下一篇 2023年3月25日

相关文章

  • Python数据可视化实现多种图例代码详解

    在Python中,数据可视化是一个非常重要的领域,可以使用多种库来实现不同类型的图表。以下是详细的攻略,介绍如何使用matplotlib和seaborn库实现多种图表: matplotlib库的使用 matplotlib是一个Python库,可以帮助我们绘制各种类型的图表,包括折线图、散点图、柱状图、饼图等。以下是一个示例,演示如何使用matplotlib库…

    python 2023年5月14日
    00
  • 在 Robot Framework 中将 python 文件作为关键字运行时遇到问题

    【问题标题】:Trouble running python file as a keyword in Robot Framework在 Robot Framework 中将 python 文件作为关键字运行时遇到问题 【发布时间】:2023-04-02 02:03:01 【问题描述】: 我正在尝试将 python 文件作为机器人框架中的关键字运行。但是,当我…

    Python开发 2023年4月8日
    00
  • 抓取网站时缺少 HTML 元素。 Python

    【问题标题】:Missing HTML Elements when scraping website. Python抓取网站时缺少 HTML 元素。 Python 【发布时间】:2023-04-01 00:21:02 【问题描述】: 我正在尝试使用 bs4 和 Selenium 从网站中提取 HREF。但是,当我使用 Beautiful Soup 解析 HT…

    Python开发 2023年4月8日
    00
  • python ipset管理 增删白名单的方法

    首先,我们需要了解一下什么是ipset。ipset是一个能够高效地管理大量IP地址、子网和端口等信息的工具。它支持多种匹配方式,可以对网络流量进行筛选。在使用python进行ipset管理时,我们可以使用python的ipset模块,这个模块提供了一些方便的操作方法。 以下是python ipset管理白名单的方法: 1. 安装ipset模块 在使用pyth…

    python 2023年6月3日
    00
  • Python新手在作用域方面经常容易碰到的问题

    Python新手在作用域方面经常容易碰到的问题 在Python中,作用域是指变量的可见性和生命周期。Python新手在作用域方面经常容易碰到的问题包括全局变量和局部变量的使用、闭包的使用、及函数参数的传递等。本文将详细讲解Python新手在作用域方面经常容易碰到的问题,包括两个示例说明。 全局量和局部变量的使用 在Python中,局变量和局部变量的使用是一个…

    python 2023年5月13日
    00
  • 全网最新用python实现各种文件类型转换的方法

    全网最新用Python实现各种文件类型转换的方法 在Python中,我们可以使用各种库来实现文件类型转换,例如Pillow库、ffmpeg库、pywin32库等等。下面我们来分别介绍一下这些库,并且给出两条示例说明。 Pillow库 Pillow是Python Imaging Library(PIL)的替代品,是一个强大的图像处理库。我们可以使用Pillow…

    python 2023年6月2日
    00
  • python中使用sys模板和logging模块获取行号和函数名的方法

    以下是关于Python中使用sys模块和logging模块获取行号和函数名的完整攻略: 使用sys模块获取行号和函数名的方法 sys模块是Python的一个标准库,可以获取关于Python解释器和其环境的信息。可以使用sys模块获取当前正在执行的代码的行号和函数名。示例代码如下: import sys def print_info(): print(&quo…

    python 2023年6月2日
    00
  • Python笔记(叁)继续学习

    下面是关于“Python笔记(叁)继续学习”的完整攻略: Python笔记(叁)继续学习 本篇笔记是Python学习的第三篇,主要内容包括面向对象编程、模块和异常处理等方面的知识点,是Python进阶学习的重要内容。 面向对象编程 Python是一门面向对象编程的语言,因此深入理解面向对象编程思想对于Python开发者非常重要。在本篇笔记中,我们将深入学习面…

    python 2023年6月3日
    00
合作推广
合作推广
分享本页
返回顶部