Stanford Algorithms学习:Clustering

COMP9101 算法设计 week4 贪心算法 问题一: 一个活动ai的列表,1<=i<=n,si时间开始,fi结束,没有两个活动在同时发生。 任务:找到最大兼容size的子集。 尝试1:总是选择最短且与之前不冲突活动,删掉冲突的活动? 不可以。 尝试2:选择一个与其他冲突最小的activity。看起来对未来选择限制最小。 不可以。 **正确的策略:**在不与之前选择的冲突下,总是选择结束时间最早的。 证明这个贪心算法的最优 证明任何最优解与贪婪算法的活动数量相同: 找到违反贪婪原则的第一个的活动。 表明用贪婪算法的选择代替 阅读详情

第二周的第一个编程作业,是利用贪婪算法来实现一个clustering的问题,和ML里学的unsupervised learning差不多。

Question 1

In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing  k -clustering. Download the text file  here. This file describes a distance function (equivalently, a complete graph with edge costs). It has the following format:

[number_of_nodes]
[edge 1 node 1] [edge 1 node 2] [edge 1 cost]
[edge 2 node 1] [edge 2 node 2] [edge 2 cost]
...
There is one edge  (i,j)  for each choice of  1≤i<j≤n , where  n  is the number of nodes. For example, the third line of the file is "1 3 5250", indicating that the distance between nodes 1 and 3 (equivalently, the cost of the edge (1,3)) is 5250. You can assume that distances are positive, but you should NOT assume that they are distinct.

Your task in this problem is to run the clustering algorithm from lecture on this data set, where the target number  k  of clusters is set to 4. What is the maximum spacing of a 4-clustering?

这个算法的实现和Kruskal's MST算法很像,先对所有边进行从小到大排序,然后利用Union-Find数据结构来;区别只是不要把所有的顶点都遍历一次,而是在要求的k值(这里是4)前结束循环。要求的距离就是下一个即将被扫描到的边的cost。

这里的Union-Find和Edge数据结构都是Algorithms fourth edition by Sedgewick里面的:

public class UnionFind {
	
	
	private int[] id;					//id[i] = parent of i 
	private int[] sizes;				//size of each component
	private int count;					//number of components
	
	/**
	 * Creates an empty union-find structure with N nodes
	 * @param N
	 */
	public UnionFind(int N) {
		count = N;
		id = new int[N];
		sizes = new int[N];
		for (int i = 0; i < N; i++) {
			id[i] = i;
			sizes[i] = 1;
		}
	}
	public int count(){
		return count;
	}
	
	public boolean connected(int u, int v){
		return (find(u) == find(v));
	}
	
	/**
	 * Return component identifier for component containing p
	 * @param u
	 * @return
	 */
	private int find(int u){
		while (u != id[u]) {
			u = id[u];
		}
		return u;	
	}
	
	public void union(int u, int v){
		int i = find(u);
		int j= find(v);
		if (i == j) {
			return;
		}
		if (sizes[i] < sizes[j]) {
			id[i] = j;
			sizes[j] += sizes[i];
		}
		else {
			id[j] = i;
			sizes[i] += sizes[j];
		}
		count--;
	}
}

public class Edge implements Comparable<Edge>{
	private final int u;	//the first vertex
	private final int v;	//the other vertex
	private final int cost;	//edge cost
	
	public Edge(int u, int v, int cost) {
		this.u = u;
		this.v = v;
		this.cost = cost;
	}
	
	public int cost(){
		return cost;
	}
	/**
	 * returns one vertex of the edge
	 */
	public int either(){
		return u;
	}
	/**
	 * given one vertex, returns the other vertex of that edge
	 * @param vertex
	 * @return
	 */
	public int other(int vertex) {
		if (vertex == u) {
			return v;
		}else if (vertex == v) {
			return u;
		}
		else {
			throw new RuntimeException("Inconsistent edge");
		}
	}
	
	@Override
	public int compareTo(Edge arg0) {
		if (this.cost() < arg0.cost()) {
			return -1;
		}
		else if (this.cost() > arg0.cost) {
			return 1;
		}
		else {
			return 0;
		}
		
	}

}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.StringTokenizer;



public class Clustering {
	private ArrayList<Edge> edges;			//stores all edges
	private UnionFind uf;
	private int N;							//number of edges
	private String fileName = "/Users/Zhusong/Documents/Study/AlgorithmsDesignAndAnalysis/Assignments/Ass2/Ass2Prob1/clustering1.txt";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Clustering cl = new Clustering();
		cl.run();
	}
	
	private void run(){
		edges = new ArrayList<Edge>();
		readGraph();
		sortEdges();
		uf = new UnionFind(N);
		Iterator<Edge> iterator = edges.iterator();
		while(uf.count() > 4){
			Edge edge = iterator.next();
			int u = edge.either();
			uf.union(u, edge.other(u));
		}
		while(true){
			Edge edge = iterator.next();
			int u = edge.either();
			int v = edge.other(u);
			if (uf.connected(u, v)) {
				continue;
			}
			else {
				System.out.println(edge.cost());
				break;
			}
		}

	}
	/**
	 * read in the text file and form a graph
	 */
	private void readGraph() {
		File file = new File(fileName);
		try {
			BufferedReader rd = new BufferedReader(new FileReader(file));
			String line;
			line = rd.readLine();
			N = Integer.parseInt(line);
			while((line = rd.readLine()) != null){
				StringTokenizer tokenizer = new StringTokenizer(line);
				int u = Integer.parseInt(tokenizer.nextToken()) - 1;
				int v = Integer.parseInt(tokenizer.nextToken()) - 1;
				int cost = Integer.parseInt(tokenizer.nextToken());
				addEdge(u, v, cost);
			}
			rd.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void addEdge(int u, int v, int cost){
		Edge edge = new Edge(u, v, cost);
		edges.add(edge);
	}
	
	private void sortEdges(){
		Collections.sort(edges);
	}
}


视觉特征-自监督-对比学习:SimCLR(在潜空间用对比损失最大化同一样本经不同数据增强所得视图间的一致性来学习表示)【Loss:对比损失函数】【同批次非同源样本作为负样本】【2020-02】 Abstract摘要本文提出了SimCLR:一个用于视觉表征对比学习的简单框架。我们简化了近期提出的对比式自监督学习算法,无需专门的架构或记忆库。为了理解是什么使对比预测任务能够学习到有用的表征,我们系统地研究了该框架的主要组成部分。我们表明:(1)数据增强的组合在定义有效预测任务中起着关键作用;(2)在表征与对比损失之间引入可学习的非线性变换,可显著提升所学习表征的质量;(3)与监督学习相比,对比学习受益于更大的批量大小和更多的训练步骤。 阅读详情

相关推荐

视觉特征-自监督-同源不同crop视图一致性【2023-04】:DINOv2(无监督学习鲁棒视觉特征)【12 亿张互不重复的图像】【判别式自监督方法】【交叉熵损失+iBOT损失】

近期,自然语言处理领域在大量数据上进行模型 Pretraining 取得的突破,为计算机视觉中类似Foundation Model 的发展开辟了道路。这些模型能够生成通用视觉特征,即无需微调即可跨图像分布和任务发挥作用的特征,从而大幅简化图像在任何系统中的使用。本研究表明,现有的 Pretraining 方法,尤其是自监督方法,如果在来自多样化来源的充足精选数据上进行训练,便能够产生此类特征。我们重新审视了现有方法,并结合不同技术,从数据规模和模型规模两方面扩展我们的 Pretraining。

u013250861的博客 362

Coursera - Algorithm (Stanford) - 课程笔记 - Week 13

Bellman Ford Algorithm 单源最短路问题定义 输入:有向图,已知各边长度,以及源点sss 输出:计算从源点出发,到达图中个点最短路的长度 Dijkstra算法的问题 对于存在负权边的情形,并不总是正确的 并不是十分的分布式 对于负权环的问题 方案1:允许负权环的存在——得不到最短路 方案2:要求无环最短路的计算——汉密尔顿遍历问题,NP完全问题 方案3:允许负权边,但不允许负权环——BF算法 目标 计算所有顶点的单源最短路径长度——BF算法 或者输出负环 最优子

支锦铭的博客 317

视觉特征-自监督-同源不同crop视图一致性【2020-06】:BYOL(自举潜在表征)【在线网络+目标网络】【目标网络EMA更新】【停止梯度】【同图双视图预测一致】【无需负样本】【避免表征坍塌】

We introduce Bootstrap Your Own Latent (BYOL), a new approach to self-supervised image representation learning. BYOL relies on two neural networks, referred to as online and target networks, that interact and learn from each other. From an augmented view o

u013250861的博客 204

Max-Spacing k-clustering

这里主要用到的知识点是Union-find数据结构: In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k-clustering. Download the text file here. This fi

lsxpu的专栏 1890

【信息科学与工程学】【数据中心】第三十五篇 云计算数据中心的学科知识04

编号学科(课程)核心知识点在云计算/云存储/云网络/云安全/云MaaS中的作用代表教材/资料/论文 + 数学方程式列表工业界应用D1421​云原生数据库:TiDB​HTAP(混合事务/分析处理)、分布式SQL、水平扩展、强一致(Raft)、自动故障恢复、与MySQL兼容、TiFlash列式引擎提供弹性扩展的分布式数据库;支撑高并发在线交易与实时分析教材:《TiDB in Action》PingCAP(2020) 论文:《TiDB: A Raft-based HTAP Database》(2017)

weixin_49199313的博客 398

Stanford Algorithm Part4 PS4Q1

Stanford Algorithm Part4 PS4Q1,java实现代码!!!!!!!!!!!

Stanford - Algorithms: Design and Analysis, Part 2 - Week 2 Assignment: Clustering

本周作业是有关Clustering的。。 第一题如下: Question 1 In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k-clustering. Download the

Programming my life 2063

手把手教你用CubeMX给GD32F103点灯、调串口(附完整工程)

本文详细介绍了如何使用CubeMX为GD32F103开发板配置GPIO点灯和串口通信,包含完整的工程创建、代码构建和测试流程。特别强调了GD32与STM32的差异点及常见避坑技巧,帮助开发者快速上手GD32开发。

weixin_42566424的博客 313

Stanford AlgorithmsI 笔记

The Algorithm Designer’s Mantra: “Perhaps the most important principle for the good algorithm designer is to refuse to be content” -Aho,Hopcroft, and Ullman,The Design a...

Voidforall 734

ESP32S3学习——i2c,点亮0.96寸oled

ESP32S3学习——i2c,点亮0.96寸oled

HandBAI的博客 1万+

【基金量化研究系列】基金绩效归因模型——Brinson多期归因模型之python实现

文章目录1. 引言2. Brinson多期归因模型的Python实现2.1 基准数据读取模块2.2 持仓数据读取模块2.3 持仓收益与基准计算模块2.4 Brinson多期归因模型核心算法Brinson_Multiple2.5 主函数模块3. 归因结果写在最后 1. 引言 在上文中,我们已经介绍了Brinson归因模型的基本思想。那么,就让我们动起手来,实现这一方法吧! 在Brinson多期归因模型实现的过程中,本文使用模块化方法,将整个实现过程划分为如下五个功能板块: Module 1: 基准数据读取模

Mikey_Sun的博客 2万+

Stanford Algorithms学习:Clustering 2

这是紧接上面的一道题,比较有趣 Question 2 In this question your task is again to run the clustering algorithm from lecture, but on a MUCH bigger graph. So big, in fact, that the distances (i.e., edge costs

likecool21的专栏 2567

从萤石云到GB28181:海康4G摄像机接入第三方平台的曲折之路

本文深入探讨了海康4G摄像机接入第三方平台时遇到的协议冲突问题,特别是GB28181与萤石云服务的互斥性。通过技术分析揭示了4G模块的定向流量限制和协议栈资源竞争等核心问题,并提供了有线接入测试和萤石云API二次开发等解决方案。最后总结了设备选型的关键参数和协议兼容性检查清单,为安防监控系统集成提供实用指导。

mango的博客 991

[Stanford Algorithms: Design and Analysis, Part 2] c23 Clustering c24 Adv. Union-Find

第二题太难了,我参考了这个代码: https://github.com/dbarabanov/coursera/blob/master/algorithms_2/assignment_2/question_2.py (这个答案错了) https://github.com/...

weixin_30436891的博客 207

【深度学习驱动流体力学】采集OpenFOAM仿真数据作为AI模型训练数据集与卷积神经网络搭建到预测(一站式完整代码实现)

采集OpenFOAM仿真数据作为AI模型训练数据集与卷积神经网络搭建到预测(一站式完整代码实现)

源代码杀手的博客 1413

Palantir 凭什么两年涨 20 倍?深度解析解决 AI 幻觉的 “本体论“ 核心原理

本文深度解析了Palantir本体(Ontology)的核心原理及其在企业AI应用中的革命性价值。本体通过构建结构化的语义层与动态执行层,将企业分散的数字资产(数据集、虚拟表、模型)映射为现实世界的数字孪生,使大模型能够在**严格的业务规则与数据边界内**进行推理与决策,从而从架构层面彻底解决AI幻觉问题。这一技术架构不仅帮助Palantir实现股价两年增长20倍、市值突破4000亿美金的商业成功,更成为SAP、Salesforce等ERP巨头争相模仿的下一代企业智能标准范式。通过航空业飞机故障应急处理等实

program哲学 219

Python深度学习:从入门到实战

亲爱的读者,欢迎您翻开这本书。我们即将探索的,是深度学习的宇宙——一个由数据、算法与算力构筑的奇妙世界。它既是严谨的科学,也是创造的艺术,更是一条通往未来智慧的修行之路。本书将带您从最基础的数学原理出发,亲手搭建神经网络,驾驭Transformer等前沿模型,最终将智慧转化为现实世界的价值。请放下畏惧,保持好奇。这不仅是一次知识的学习,更是一场思维的远行。来,随我一起,开启这趟非凡的旅程吧。

weixin_45747731的博客 296

【Windows Server 2019】存储服务器的配置和管理——iSCSI的安装和配置(下)

博文介绍了如何使用Windows 10 和 ESXi 验证iSCSI服务器部署成功以及如何管理iSCSI服务 。

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 7999

Stanford Algorithms: Design and Analysis, Part 2[week 2]

Problem Set-2 Programming Assignment-2 Question 1 In this programming problem and the next you'll code up the clustering algorithm from lecture for computing a max-spacing k

无知的我 7770

Claude Code 100个真实案例 - 用AI搭建GIS地理信息系统(地图标注+热力图)

本案例展示如何使用 Claude Code 从零搭建一个完整的 GIS 地理信息系统。我们将使用 Python + Flask 作为后端,Leaflet.js 作为前端地图引擎,实现地图标注、热力图展示、区域绘制、坐标搜索等功能。全程通过与 Claude Code 对话完成,让你感受 AI 在地理信息领域的强大开发能力。

yueyeguzhuo的专栏 112

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

上一篇: LeetCode刷题笔录 Longest Substring Without Repeating Characters
下一篇: Stanford Algorithms学习:Clustering 2
likecool21
博客等级 码龄14年 14粉丝 123原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值