课堂笔记 - 深度学习 Deep Learning (5) Lab1

  • 用python实作PLA (直接把训练资料写进程序里)

https://ithelp.ithome.com.tw/upload/images/20211024/201427832EuYOiQSn6.png

昨天才发现之前就交出去的作业code不小心写错一个地方.... 希望扣分不要扣太重.../images/emoticon/emoticon02.gif

import numpy as np
import matplotlib.pyplot as plt

dataset = np.array([

    [1, 0, 1],
    [1, 3, -1],
    [2, -6, 1],
    [-1, -3, 1],
    [-5, 5, -1],
    [5, 2, 1],
    [-2, 2, -1],
    [-7, 2, -1],
    [4, -4, 1],
    [-5, -1, -1]

])

num = 10
# 切割dataset的数据
x1 = dataset[:, 0]
x2 = dataset[:, 1]
y = dataset[:, 2]


def pla_with_data():

    # 初始值 >> w=[0,0] b=0
    w = np.zeros((2, 1))
    dot = 0
    b = 0
    flag = 1

    for k in range(100):   # 限制无穷回圈 >> 次数设定100次
        flag = 1
        for i in range(num):     # 看每个点是否为正确

            dot = x1[i]*int(w[0])+x2[i]*int(w[1])   # 将一个点的座标带入 跟w作内积
            if sign(dot, b) != y[i]:  # 与参考资料y不相符 >> 线划分错误

                flag = 0
                w[0] += y[i] * x1[i]    # 矫正 w = w + y*x
                w[1] += y[i] * x2[i]
                b = b + y[i]            # 矫正 b = b + y
                # print(w, b)

            else:
                continue  # 与参考资料y相符 >> 下一个点

        if flag == 1:
            break  # 全部的点都与参考资料y相符 >> 划分完成

    return w, b


def sign(dot, b):
    if dot+b >= 0:
        return 1
    else:
        return -1


def draw(x1, x2, y):

    # 制作figure
    fig = plt.figure()

    # 图表的设定
    ax = fig.add_subplot(1, 1, 1)

    # 散布图
    for i in range(num):
        if y[i] == 1:
            ax.scatter(x1[i], x2[i], color='red')
        else:
            ax.scatter(x1[i], x2[i], color='black')

    # data
    x = [2, -5, -2]
    y = [-4, 1, -2]
    ax.scatter(x, y, c='g', marker="x")

    plt.show()


prex1 = [2, -5, -2]
prex2 = [-4, 1, -2]


w, b = pla_with_data()

for i in range(3):
    pre = np.sign((prex1[i]*w[0]+prex2[i]*w[1])+b)
    print('predict example %s = %s' % (i+1, pre))

print('w1 = %s , w2 = %s , b = %s' % (w[0], w[1], b))
draw(x1, x2, y)

该写的注解都在上面了,下面是结果:
https://ithelp.ithome.com.tw/upload/images/20211024/20142783CLa3bGiCIR.png

github连结:
https://github.com/Minimindy/PLA-numpy-only-/tree/main


<<:  Extra09 - Storybook - 元件开发框架

>>:  课堂笔记 - 深度学习 Deep Learning (6) Lab2

LeetCode 双刀流:24. Swap Nodes in Pairs

24. Swap Nodes in Pairs 前面我们着重在「资料结构」的议题上做了不少的讨论,...

[day-17] 认识Python的资料结构!(Part .4)

一、认识"set"(集合)   甚麽是set呢?简单来说set就像是一个大杂烩,...

[Day 21] Leetcode 560. Subarray Sum Equals K (C++)

前言 今天这题也是来自top 100 liked的题目,题目是:560. Subarray Sum ...

【Day28】反馈元件 - Modal

元件介绍 Modal 元件为弹出相关元件提供了重要的基础建设,如 Dialog、Popover、Dr...

30-21 之 Domain Layer - Lazy Load ( 未完成 )

什麽是 Lazy Load 呢 ? An object that doesn’t contain a...