用Python实现神经网络基础实验

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

神经网络是所有 AI 算法的核心,如今,深度神经网络用于从图像识别和对象检测到自然语言处理和生成的各种任务。


一、神经网络是什么?

生物神经元是一个细胞,有输入的树突,有输出的轴突。而神经网络上的神经元是人工神经元,它也是一个函数,更准确地说,它是一类函数。像数字电路一样,它也是由简单的函数复合而成。数字电路的基本单位是与、或、非门,而神经网络的基本单位则是神经元。

二、实验

1.实验目的

        通过实验进一步了解和掌握人工神经网络(感知机)的基本概念和原理,仔 细领悟使用 python 语言编写人工神经网络的基本思路和神经网络训练方法,进一步掌握使 用 python 生成随机数、进行可视化的第三方包,进一步加深对函数式编程的理解。

2.实验原理

1)感知机、人工神经网络的基本概念;

2)神经网络训练、优化的基本方法:

3)数据生成和增强方法;

4)matplotlib 可视化的原理。

3.实验内容

import matplotlib.pyplot as plt
import random
import numpy as np
import scipy as sp
import math
import pylab as pl

def DataGeneration(r, w, d, Na, Nb):
        N = Na  +Nb
        array = np.zeros((N,4))
        array_b = np.zeros((Nb,4))
        i = 0
        while(N>0):
            ax = random.uniform(-r - 0.5*w,r + 0.5 * w)
            ay = random.uniform(0,r +0.5*w)
            if(r -0.5 *w)**2 <= ax**2 +ay**2 <= (r +0.5*w)**2:
                array[i,0] = 1
                array[i,1] = ax
                array[i,2] = ay
                array[i,3] = 1
                i = i + 1
                N = N - 1
            else:
                N = N
                i = i
        for i in range(Nb):
            array_b[i,0] = array[i+100, 0]
            array_b[i,1] = array[i+100, 1] + r
            array_b[i,2] = -array[i + 100, 2] - d
            array_b[i,3] = array[i + 100, 3] - 1

        array[100:199,:] = array_b[0:99,:]
        return array


def sgn(input):
    if input > 0:
        return 1
    elif input<0:
        return  -1
    elif input == 0:
        return 0

def init_weight(shape, bias, lr):
    wt = np.zeros(shape)
    for i in range(shape[1]):
        wt[0,i] = random.gauss(0,lr)
    wt[0,0] = bias
    return wt

def train(wt, input_sample, lr):
    input_data = input_sample[0:3]
    label = input_sample[3]
    output = np.sum(np.multiply(input_data, wt))
    output = sgn(output)
    loss = 0
    if label == 1:
        desired_output = 1
    elif label == 0:
        desired_output = -1
    wt = np.add(wt,lr*(desired_output - output)* input_data)
    loss = abs(desired_output - output)
    if loss == 0:
        result = True
    else:
        result = False
    return  wt, loss, result

if __name__ == '__main__':
        r, w, d = 10, 2, 2
        lr = 0.1
        Na, Nb = 100, 100
        N = Na+ Nb
        shape = np.zeros([1,3]).shape
        bias = 0
        iteration_num = 100
        array = DataGeneration(r, w, d, Na, Nb)
        seq = np.arange(N)
        np.random.shuffle(seq)
        wt = init_weight(shape, bias, lr)
        x_data = []
        y_data = []
        iter_list = []
        loss_list = []
        correct_rate_list = []
        for k in range(iteration_num):
            loss = 0
            correct_num = 0
            for i in  range(N):
                Sample_point = array[seq[i], 0:4]
                wt_new, loss_new, result = train(wt, Sample_point, lr)
                wt = wt_new
                loss = loss + loss_new
                if result == True:
                    correct_num += 1
                if k == 0:
                    temp = array[seq[i], 1:3]
                    x_data.append(temp[0])
                    y_data.append(temp[1])
            if k%1 == 0:
                loss = loss/N
                iter_list.append(k)
                loss_list.append(loss)
                correct_rate_list.append(correct_num/N)

plt.figure(1)
plt.grid()
plt.plot(x_data, y_data, 'o')
plt.xlabel('x')
plt.ylabel('y')
t = np.arange(-30, 40, 1)
y = -(t * wt[0,1] + wt[0,0])/wt[0,2]
plt.plot(t,y,'red',linewidth = 2)

plt.figure(2)
plt.plot(iter_list, loss_list,'red')
plt.xlabel('iteration')
plt.ylabel('loss')
plt.figure(3)
plt.scatter(iter_list, correct_rate_list, color = 'green')
plt.xlabel('iteration')
plt.ylabel('correct rate')

plt.show()

结果

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值