当前位置: 首页 > news >正文

机器学习——李航(实验)笔记第一二章

plt.plot(x_points,fit_func(p_lsq[0],x_points),label='fitted curve')

result = leastsq(residuals_func, initial_params, args=(x_data, y_data))

regularization=0.00001  #较小的λ值意味着正则化作用较弱,模型可能仍然会过拟合;较大的λ值则可能导致模型欠拟合。

简单方法:

1.plt.rcParams['axes.unicode_minus'] = False

这行代码用于解决Matplotlib在绘制图表时,负号(-)显示为方块或乱码的问题。

强制Matplotlib使用直线来表示负号

 2.plt.rcParams['font.sans-serif']=['SimHei']

这行代码的作用是设置Matplotlib中默认的无衬线字体(sans-serif)为“SimHei”(黑体)

3.在 scikit-learn 库中,Perceptron 类是一个用于二分类任务的线性分类器。它是基于感知机学习算法实现的,该算法是一种简单的线性分类算法,旨在找到一个能够将不同类别的数据点分开的超平面(在二维空间中是一条直线,在三维空间中是一个平面,以此类推)。

4.fit_intercept=True:这个参数指定是否应该计算截距项(即偏置项),提高灵活性

5.max_iter=1000:这个参数指定了算法收敛的最大迭代次数。

6.tol=None:这个参数指定了算法收敛的容忍度。如果权重更新的变化量小于这个值,则算法认为已经收敛,并停止迭代。在您的代码中,tol 被设置为 None,这意味着将使用 scikit-learn 的默认容忍度值。

手动实现:

1.y 是从 df 的最后一列(即原始的 Iris 标签,经过转换后变为 1 和 -1)中提取的。

X 是从 df(一个包含 Iris 数据集前 100 个样本的 DataFrame)中提取的,具体是前两列(花萼长度和花萼宽度)

import pandas as pd
import numpy as np
import sklearn.datasets
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

#导入数据
iris=load_iris()
df=pd.DataFrame(iris.data,columns=iris.feature_names)
df['label']=iris.target
df.columns=['sepal length','sepal width','petal length','petal width','label']
df.label.value_counts()

#绘制散点图
plt.scatter(df[:50]['sepal length'],df[:50]['sepal width'],label='0')
plt.scatter(df[50:100]['sepal length'],df[50:100]['sepal width'],label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

#数据准备
data=np.array(df.iloc[:100,[0,1,-1]])
X,y=data[:,:-1],data[:,-1]  #X是前两列,y是最后一列
y=np.array([1 if i==1 else -1 for i in y])

#感知机模型
class Model:
    #初始化权重和偏置
    def __init__(self):
        self.w=np.ones(len(data[0])-1,dtype=np.float32)
        self.b=0
        self.lr=0.1
    #定义sign函数
    def sign(self,x,w,b):
        y=np.dot(x,w)+b
        return y
    #训练模型
    def fit(self,X_train,y_train):
        is_wrong=False
        while not is_wrong:
            wrong_count=0
            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: #sign函数作用是计算wx+b的值
                    self.w=self.w+self.lr*np.dot(y,X)
                    self.b=self.b+self.lr*y
                    wrong_count+=1
            if wrong_count==0:
                is_wrong=True
        return 'Perceptron Model!'

#训练模型
perceptron=Model()
perceptron.fit(X,y)

#绘制分类图
X_points=np.linspace(4,7,10)
y_ = -(perceptron.w[0] *X_points + perceptron.b) / perceptron.w[1] 
plt.plot(X_points,y_)
plt.plot(data[:50,0],data[:50,1],'bo',color='blue',label='0')
plt.plot(data[50:100,0],data[50:100,1],'bo',color='orange',label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

 

#丰富图案,采用内置函数perceptron
import sklearn
from sklearn.linear_model import Perceptron

sklearn.__version__

clf = Perceptron(fit_intercept=True,    
                 max_iter=1000,
                 tol=None,
                 shuffle=True)
clf.fit(X, y)

# 画布大小
plt.figure(figsize=(10,10))

# 中文标题
plt.rcParams['font.sans-serif']=['SimHei']  #rc
plt.rcParams['axes.unicode_minus'] = False
plt.title('鸢尾花线性数据示例')

plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Iris-setosa',)
plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')

# 画感知机的线
x_ponits = np.arange(4, 8)
y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
plt.plot(x_ponits, y_)

# 其他部分
plt.legend()  # 显示图例
plt.grid(False)  # 不显示网格
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()
import numpy as np
import scipy as sp  # 导入scipy库,用于科学计算
from scipy.optimize import leastsq  # 导入最小二乘法函数
import matplotlib.pyplot as plt

regularization=0.00001  #较小的λ值意味着正则化作用较弱,模型可能仍然会过拟合;较大的λ值则可能导致模型欠拟合。

def real_func(x):
    return np.sin(2*np.pi*x)
def fit_func(p,x):
    f=np.poly1d(p)
    return f(x)
def residuals_func(p,x,y):
    return fit_func(p,x)-y
def residuals_func_regularization(p,x,y):
    ret=fit_func(p,x)-y
    ret=np.append(ret,np.sqrt(0.5*regularization*np.square(p)))
    return ret

x=np.linspace(0,1,10)
x_points=np.linspace(0,1,1000)
y_=real_func(x)
y=[np.random.normal(0,0.1)+y1 for y1 in y_]
def fitting(M=0):
    p_init=np.random.rand(M+1)
    p_lsq=leastsq(residuals_func,p_init,args=(x,y))
    p_lsq_regularization=leastsq(residuals_func_regularization,p_init,args=(x,y))
    print('Fitting Parameters:',p_lsq[0])   #p_lsq[0]输出拟合参数,p_lsq[1]输出协方差矩阵
    plt.plot(x_points,real_func(x_points),label='real') #real_func(x_points)为真实值,x_points为x轴
    plt.plot(x_points,fit_func(p_lsq[0],x_points),label='fitted curve') #fit_func(p_lsq[0],x_points)为拟合值
    plt.plot(x_points,fit_func(p_lsq_regularization[0],x_points),label='regularization') #fit_func(p_lsq[0],x_points)为拟合值
    plt.plot(x,y,'bo',label='noise') #y为带噪声的真实值
    plt.legend()
    plt.show()
    return p_lsq

p_lsq_0=fitting(M=0) #M=0表示多项式的次数为0
p_lsq_1=fitting(M=1) #M=1表示多项式的次数为1
p_lsq_3=fitting(M=3) #M=3表示多项式的次数为3
p_lsq_9=fitting(M=9) #M=9表示多项式的次数为9

 

 

相关文章:

  • 电子元器件识别图大全、符号对照表
  • 【TCAD】Sentaurus 中的“陷阱trap”仿真设置
  • 对象存储之Ceph
  • halcon三维点云数据处理(二十八)reconstruct_3d_object_model_for_matching
  • 笔记20250226
  • Ubuntu22中的bash脚本记录
  • 【Linux 进程状态】—— 从创建到消亡的全生命周期
  • QT初学——helloworld
  • 魔法方法:__str__( )
  • uniapp 小程序如何实现大模型流式交互?前端SSE技术完整实现解析
  • 【图像的读写与基本操作】
  • C#调用CANoeCLRAdapter.dll文章(一)
  • React Native 0.77正式版发布
  • TEMU标签超简单制作方法,三步快速合成TEMU标签
  • 笔试练习day8
  • 【Python3教程】Python3基础篇之数据结构
  • 一文讲解Redis的内存淘汰和过期策略
  • Python爬取某云热歌榜:解析动态加载的歌曲数据
  • 项目收支管理怎么做
  • vue+element-dialog:修改关闭icon / 遮罩层不能挡住弹窗 / 遮罩层不能遮挡元素
  • 最新研究:新型合成小分子可“精准杀伤”癌细胞
  • 中国海警舰艇编队5月14日在我钓鱼岛领海巡航
  • 马上评丨岂能为流量拿自己的生命开玩笑
  • 220名“特朗普币”持有者花1.48亿美元,获邀与特朗普共进晚餐
  • 继71路之后,上海中心城区将迎来第二条中运量公交
  • 人民日报访巴西总统卢拉:“巴中关系正处于历史最好时期”