python_定义一个高维空间样本点集类HDPoints,计算minkowski各种情况下得最大距离
problem:
定义一个高维空间样本点集类HDPoints,须包含以下数据属性与方法属性:
(a)数据属性self.points:类型为列表,由多个子列表构成,每个子列表表示高维空间中的一个数据点,且数据维度可以任意,并通过初始化构造函数获得。
(b)方法属性centerpoint(self):计算点集的中心点。
©方法属性minkowski (self, x, y, p):计算两点x和y之间的闵可夫斯基距离,p为非负整数,用p=0情形表示切比雪夫距离。由此定义的距离称为p-闵氏距离,其数学定义如下:
(d)方法属性farthestpoint(self, p):找出离中心点p-闵氏距离最远的点,返回在self.points中的下标以及最大距离。
(e)方法属性farthest2points(self, p):找出点集self.points中p-闵氏距离最远的两点,返回两点在self.points中的下标及其最大距离。
接一下来,实例化类HDPoints,利用random模块,随机产生至少50个高维空间数据点,样本点的维度至少在5以上,且每个分量取值服从区间[0,1]上的均匀分布。
同时,随机产生一个0~5之间的一个非负整数,赋值传递给p-闵氏距离函数中的参数p,对HDPoints实例对象的全部自定义方法属性(即centerpoint()、minkowski()、farthestpoint()和farthest2points())进行功能测试。
code:
import numpy as np from numpy import random import itertools class HDPoints(): def __init__(self,HDPoints_list): self.points =HDPoints_list def centerpoint(self): ndarray=np.array(self.points) return sum(ndarray)/len(ndarray) def minkowski(self,x,y,p): abs_list= [abs(x-y)**p for x,y in zip(x,y)] return sum(abs_list)**(1/p) def farthestpoint(self,p): centerpoint=self.centerpoint() distances_list=[self.minkowski(centerpoint,point,p) for point in self.points ] max_distance= max(distances_list) return distances_list.index(max_distance),max_distance def farthest2points(self,p): points_index_tuple_list=[(point,i)for i,point in enumerate(self.points)] point_pairs_tuples=(itertools.combinations(points_index_tuple_list,r=2)) #element shape:(([point_list1],index2),([point_list2],index2)) distances_list=[(self.minkowski(tuple[0][0],tuple[1][0],p),(tuple[0][1],tuple[1][1])) for tuple in point_pairs_tuples ] #element shape:(minkowski_distance,(index1,index2)) max_distance_point=max(distances_list,key=lambda tuple:tuple[0]) return max_distance_point[1],max_distance_point[0] # a=random.rand(1,0.5,2,3,6,3) a=random.uniform(0,1,5).tolist() """ get points list: """ points=[random.uniform(0,1,5).tolist() for i in range(50)] hd_Points=HDPoints(points) p=random.randint(1,6) print("the centerpoint is:",hd_Points.centerpoint()) """ the minkowski method will be test contained in the farthestpoint() method! """ print("the farthest point:",hd_Points.farthestpoint(p)) print(f"the farthest2point: index of the 2 pointes: {hd_Points.farthest2points(p)[0]},the max minkowski distance is {hd_Points.farthest2points(p)[1]}")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了