Stanford Algorithms学习:Clustering 2

Stanford Algorithms 斯坦福算法课 Stanford Algorithms 笔记@TOC Divide & Conquer Algorithms Brute force: O(n2n^2n2) time Better methods: a. Divide and conquer: 1. We call an inversion (i,j)(i,j)(i,j) with [i<j][i < j][... 阅读详情

这是紧接上面的一道题,比较有趣

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) are only defined  implicitly, rather than being provided as an explicit list.

The data set is here. The format is:
[# of nodes] [# of bits for each node's label]
[first bit of node 1] ... [last bit of node 1]
[first bit of node 2] ... [last bit of node 2]
...
For example, the third line of the file "0 1 1 0 0 1 1 0 0 1 0 1 1 1 1 1 1 0 1 0 1 1 0 1" denotes the 24 bits associated with node #2.

The distance between two nodes  u  and  v  in this problem is defined as the Hamming distance--- the number of differing bits --- between the two nodes' labels. For example, the Hamming distance between the 24-bit label of node #2 above and the label "0 1 0 0 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1" is 3 (since they differ in the 3rd, 7th, and 21st bits).

The question is: what is the largest value of  k  such that there is a  k -clustering with spacing at least 3? That is, how many clusters are needed to ensure that no pair of nodes with all but 2 bits in common get split into different clusters?

NOTE: The graph implicitly defined by the data file is so big that you probably can't write it out explicitly, let alone sort the edges by cost. So you will have to be a little creative to complete this part of the question. For example, is there some way you can identify the smallest distances without explicitly looking at every pair of nodes?

这道题也是要用到Kruskal's MST的算法的思想,只不过,这次没有给出每条边的cost,因此也无法对cost进行排序。事实上,这次的cost的定义就不大一样(见题目中的Hamming distance)。


首先这些点的存储是二进制的,因此用一个BitSet来表示每一个节点是一个很直接的选择。

这道题的问题可以解释为:把所有Hamming Distance为0,1,2的点都聚合到一起,剩下多少个点?很自然地,利用Union Find,把距离为0,1,2的点都union到一起,剩下的节点数就是结果。

剩下的问题就是如何快速找到距离为0,1,2的点。对每个pair进行暴力搜索显然不大行,因为文本中一共有200000个点,每个点有24个bit,这耗时太长了。其实仔细想想,对每一个节点,只需要找到与其每个bit都相同,只有一个bit不相同以及有两个bit不同的节点即可。这其实并没有很多种可能性(1 + 24 + 276 = 301)。所以启用作弊神器hashmap就可以进行“暴力”搜索了,耗时不长。


建立一个hashmap,利用每一个BitSet作key,相应的index(即这个节点在union find结构中的编号)作为value,可以很快地得到答案。其中用到的UnionFind和上篇文章中得一样。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;

public class Clustering2 {
	private HashMap<BitSet, Integer> dataSet;
	private UnionFind uf;
	private int numberOfBits;
	private int numberOfNodes;
	private String filename = "/Users/Zhusong/Documents/Study/AlgorithmsDesignAndAnalysis/Assignments/Ass2/Ass2Prob2/clustering_big.txt";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Clustering2 clustering2 = new Clustering2();
		clustering2.run();
	}
	
	private void run(){
		dataSet = new HashMap<BitSet, Integer>();
		build();
		calDis1();
		calDis2();
		System.out.println(uf.count());
	}
	
	/**
	 * find nodes that have a distance of 2
	 */
	private void calDis2(){
		Set<BitSet> keySet = dataSet.keySet();
		Iterator<BitSet> iterator = keySet.iterator();
		while (iterator.hasNext()) {
			BitSet bitSet = (BitSet) iterator.next();
			for (int i = 0; i < numberOfBits; i++) {
				for (int j = 0; (j < numberOfBits) && (j != i); j++) {
					BitSet temp = (BitSet) bitSet.clone();
					temp.flip(i);
					temp.flip(j);
					if (dataSet.containsKey(temp)) {
						uf.union(dataSet.get(bitSet), dataSet.get(temp));
					}
				}
			}
		}
	}
	
	/**
	 * find nodes that have a distance of 1
	 */
	private void calDis1(){
		Set<BitSet> keySet = dataSet.keySet();
		Iterator<BitSet> iterator = keySet.iterator();
		while (iterator.hasNext()) {
			BitSet bitSet = (BitSet) iterator.next();
			for (int i = 0; i < numberOfBits; i++) {
				BitSet temp = (BitSet) bitSet.clone();
				temp.flip(i);
				if (dataSet.containsKey(temp)) {
					uf.union(dataSet.get(bitSet), dataSet.get(temp));
				}
			}
		}
	}
	
	/**
	 * 1. read in the text file
	 * 2. create a union find structure
	 * 3. build the hash map and union the nodes that have 0 distances
	 */
	private void build(){
		File file = new File(filename);
		try {
			BufferedReader rd = new BufferedReader(new FileReader(file));
			String line = rd.readLine();
			StringTokenizer tokenizer = new StringTokenizer(line);
			numberOfNodes = Integer.parseInt(tokenizer.nextToken());
			uf = new UnionFind(numberOfNodes);
			numberOfBits = Integer.parseInt(tokenizer.nextToken());
			//
			int index = 0;
			while ((line = rd.readLine()) != null) {
				tokenizer = new StringTokenizer(line);
				BitSet bitSet = new BitSet(numberOfBits);
				//creates a bit set demonstrating the current node
				for (int i = 0; i < numberOfBits; i++) {
					if (tokenizer.nextToken().equals("1")) {
						bitSet.set(i);
					}
				}
				//put it in the hash map if no identical nodes are already in there
				if (!dataSet.containsKey(bitSet)) {
					dataSet.put(bitSet, index);
				}
				//union the two nodes if the current node has a duplicate in the hash map
				else {
					uf.union(index, dataSet.get(bitSet));										
				}
				index++;		
			}
			rd.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


视觉特征-自监督-同源不同crop视图一致性【2023-04】:DINOv2(无监督学习鲁棒视觉特征)【12 亿张互不重复的图像】【判别式自监督方法】【交叉熵损失+iBOT损失】 近期,自然语言处理领域在大量数据上进行模型 Pretraining 取得的突破,为计算机视觉中类似Foundation Model 的发展开辟了道路。这些模型能够生成通用视觉特征,即无需微调即可跨图像分布和任务发挥作用的特征,从而大幅简化图像在任何系统中的使用。本研究表明,现有的 Pretraining 方法,尤其是自监督方法,如果在来自多样化来源的充足精选数据上进行训练,便能够产生此类特征。我们重新审视了现有方法,并结合不同技术,从数据规模和模型规模两方面扩展我们的 Pretraining。 阅读详情

相关推荐

视觉特征-自监督-对比学习:SimCLR(在潜空间用对比损失最大化同一样本经不同数据增强所得视图间的一致性来学习表示)【Loss:对比损失函数】【同批次非同源样本作为负样本】【2020-02】

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

u013250861的博客 82

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 2064

视觉特征-自监督-同源不同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的博客 206

Stanford Algorithms学习:Clustering

第二周的第一个编程作业,是利用贪婪算法来实现一个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

likecool21的专栏 2507

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

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

weixin_49199313的博客 406

Stanford Algorithm Part4 PS4Q1

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

[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

芯片低功耗设计的两种常用EDA流程

如题。

EricWZY2008的专栏 5557

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

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

weixin_45747731的博客 299

低成本主从机械臂系统构建:6D位姿数据采集与VLA模型训练实战

本文详细介绍了如何构建低成本主从机械臂系统,实现高精度6D位姿数据采集与VLA模型训练。通过300美元级别的硬件组合,系统达到±1mm位置精度和≤0.5°姿态误差,满足Vision-Language-Action模型的多模态训练需求。文章涵盖硬件选型、数据采集技巧、模型训练实战经验,为机器人研究提供经济高效的解决方案。

r7s8t的博客 267

SAP SD信贷管理实战:从配置到风险控制的完整指南(附后台路径)

本文详细解析了SAP SD信贷管理的完整配置流程与风险控制策略,涵盖信贷控制范围设置、风险分级机制及动态控制配置。通过实战案例和后台路径指引,帮助企业实现从客户信用评估到实时监控的全流程管理,有效降低坏账风险并优化资金安全。

3a9bq4r8t2y的博客 213

LeetCode刷题笔录 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. Fo

likecool21的专栏 1万+

告别迷茫!手把手教你用Altova XMLSpy编写EtherCAT从站ESI文件(附避坑指南)

本文详细介绍了如何使用Altova XMLSpy高效编写EtherCAT从站ESI文件,涵盖核心架构、通信通道配置、过程数据映射等关键步骤,并提供了常见问题排查与性能优化建议。通过实战案例和避坑指南,帮助工程师快速掌握EtherCAT从站开发技巧,提升工作效率。

weixin_42570484的博客 395

LeetCode刷题笔录 Two Sum

Two Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the

likecool21的专栏 1万+

实战:RK3568 Android14 调试 ES8388 音频驱动 (MIC 篇)

这个板子的MIC设计使用了硬件自动切换方案,极大简化了软件层面的逻辑。我们不需要根据耳机插拔事件去编写复杂的路由切换代码,只需要守住 LIN1/RIN1 这一个入口,配置好增益,剩下的交给那颗 SGM3157 芯片即可。祝您的录音功能调试顺利!

qq_33427070的博客 1681

X电容与Y电容,看这一篇就够了

本文详细介绍了X电容与Y电容的定义、作用、位置、分类,以及它们在实际应用中的容值选取和计算方法。通过汽车电子应用和X电容放电电路的实例,帮助读者深入理解这两种安规电容的重要性。文章还探讨了电容放电电阻的计算,确保符合安全规范。

让你爱上电路设计 7020

LeetCode刷题笔录 Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key.Th

likecool21的专栏 6928

SAP CBC 集成质量系统初始化接入实战指南

摘要 本文探讨了SAP S/4HANA Cloud Public Edition项目中质量系统的初始接入过程。质量系统并非开箱即用,而是需要经过SAP Central Business Configuration(CBC)的Scope and Organizational Structure阶段部署后才能具备完整功能。文章重点分析了几个关键环节:CBC里程碑确认的时机选择、Identity Authentication的初始管理员设置、Business Role Template的创建规范等。实施过程中需特

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1408
上一篇: Stanford Algorithms学习:Clustering
下一篇: LeetCode 刷题笔录 Add Two Numbers
likecool21
博客等级 码龄14年 14粉丝 123原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值