NNDL 实验五 前馈神经网络(3)鸢尾花分类

NNDL 实验五 前馈神经网络(3)鸢尾花分类

一、深入研究鸢尾花数据集

在这里插入图片描述

# coding=gbk
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import Perceptron
 
"""自定义感知机模型"""
# 数据线性可分,二分类数据
# 此处为一元一次线性方程
class Model:
    def __init__(self):
        # 创建指定形状的数组,数组元素以 1 来填充
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        self.b = 0  # 初始w/b的值
        self.l_rate = 0.1
        # self.data = data
 
    def sign(self, x, w, b):
        y = np.dot(x, w) + b  # 求w,b的值
        # Numpy中dot()函数主要功能有两个:向量点积和矩阵乘法。
        # 格式:x.dot(y) 等价于 np.dot(x,y) ———x是m*n 矩阵 ,y是n*m矩阵,则x.dot(y) 得到m*m矩阵
        return y
 
    # 随机梯度下降法
    # 随机梯度下降法(SGD),随机抽取一个误分类点使其梯度下降。根据损失函数的梯度,对w,b进行更新
    def fit(self, X_train, y_train):  # 将参数拟合 X_train数据集矩阵 y_train特征向量
        is_wrong = False
        # 误分类点的意思就是开始的时候,超平面并没有正确划分,做了错误分类的数据。
        while not is_wrong:
            wrong_count = 0  # 误分为0,就不用循环,得到w,b
            for d in range(len(X_train)):
                X = X_train[d]
                y = y_train[d]
                if y * self.sign(X, self.w, self.b) <= 0:
                    # 如果某个样本出现分类错误,即位于分离超平面的错误侧,则调整参数,使分离超平面开始移动,直至误分类点被正确分类。
                    self.w = self.w + self.l_rate * np.dot(y, X)  # 调整w和b
                    self.b = self.b + self.l_rate * y
                    wrong_count += 1
            if wrong_count == 0:
                is_wrong = True
        return 'Perceptron Model!'
 
    # 得分
    def score(self):
        pass
 
 
# 导入数据集
df = pd.read_csv('Iris.csv', usecols=[1, 2, 3, 4, 5])
 
# pandas打印表格信息
# print(df.info())
 
# pandas查看数据集的头5条记录
# print(df.head())
 
"""绘制训练集基本散点图,便于人工分析,观察数据集的线性可分性"""
# 表示绘制图形的画板尺寸为8*5
plt.figure(figsize=(8, 5))
# 散点图的x坐标、y坐标、标签
plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa')
plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor')
plt.scatter(df[100:150]['SepalLengthCm'], df[100:150]['SepalWidthCm'], label='Iris-virginica')
plt.xlabel('SepalLengthCm')
plt.ylabel('SepalWidthCm')
# 添加标题 '鸢尾花萼片的长度与宽度的散点分布'
plt.title('Scattered distribution of length and width of iris sepals.')
# 显示标签
plt.legend()
plt.show()
 
 
# 取前100条数据中的:前2个特征+标签,便于训练
data = np.array(df.iloc[:100, [0, 1, -1]])
# 数据类型转换,为了后面的数学计算
X, y = data[:, :-1], data[:, -1]
y = np.array([1 if i == 'Iris-setosa' else -1 for i in y])
 
 
"""自定义感知机模型,开始训练"""
perceptron = Model()
perceptron.fit(X, y)
# 最终参数
print(perceptron.w, perceptron.b)
# 绘图
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.plot(x_points, y_)
plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa')
plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor')
plt.xlabel('SepalLengthCm')
plt.ylabel('SepalWidthCm')
# 添加标题 '自定义感知机模型训练结果'
plt.title('Training results of Custom perceptron model.')
plt.legend()
plt.show()
 
 
"""sklearn感知机模型,开始训练"""
# 使用训练数据进行训练
clf = Perceptron()
# 得到训练结果,权重矩阵
clf.fit(X, y)
# Weights assigned to the features.输出特征权重矩阵
# print(clf.coef_)
# 超平面的截距 Constants in decision function.
# print(clf.intercept_)
# 对测试集预测
# print(clf.predict([[6.0, 4.0]]))
# 对训练集评分
# print(clf.score(X, y))
 
# 绘图
x_points = np.linspace(4, 7, 10)
y_ = -(clf.coef_[0][0] * x_points + clf.intercept_[0]) / clf.coef_[0][1]
plt.plot(x_points, y_)
plt.scatter(df[:50]['SepalLengthCm'], df[:50]['SepalWidthCm'], label='Iris-setosa')
plt.scatter(df[50:100]['SepalLengthCm'], df[50:100]['SepalWidthCm'], label='Iris-versicolor')
plt.xlabel('SepalLengthCm')
plt.ylabel
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值