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

汽车底盘技术解析:从悬架调校到智能化,如何评价国产车底盘实力

汽车底盘作为决定车辆驾驶质感、安全性和耐久性的核心系统,其技术内涵远不止于悬架结构。从行驶系、转向系到制动系的协同工作,底盘调校是一门融合机械原理与工程实践的艺术。在电动化与智能化浪潮下,底盘技术正经历从被动适应到主动响应的变革,CDC可变阻尼减震器和空气悬架等技术的应用,让底盘具备了通过OTA升级实现性能优化的可能。国产汽车品牌如奇瑞、吉利等,通过平台化架构研发与调校经验积累,正推动底盘技术从“能用”向“好用”乃至“塑造独特驾驶风格”迈进。理解底盘技术,需超越简单的结构对比,关注其在实际路况中的滤震性、支

weixin_34413103的博客 387

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

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

weixin_45747731的博客 299

Megatron单机多卡Qwen2.5:pre-train+sft

英伟达:https://github.com/NVIDIA/Megatron-LM/releases/tag/core_r0.8.0阿里:https://github.com/alibaba/Pai-Megatron-Patch/releases/tag/v0.10.2。

weixin_46873015的博客 2180

易灵思Trion FPGA实战:5分钟搞定MIPI硬核配置(附Interface Designer避坑指南)

本文详细介绍了易灵思Trion FPGA中MIPI硬核的快速配置方法,通过Interface Designer工具实现从时钟配置到数据收发的全流程实战。特别针对初次接触Trion系列的设计师,提供了六个关键配置陷阱及解决方案,帮助开发者高效完成嵌入式视觉和高速数据传输项目。

eee77的博客 791

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万+

Coze知识库搭建:智能化管理与高效检索实践

知识管理系统是现代企业信息资产管理的核心基础设施,其核心原理是通过结构化存储和智能检索技术实现知识的快速流转。在技术实现上,基于NLP的语义理解引擎和知识图谱构建是关键,能够显著提升检索准确率和知识关联性。以Coze平台为例,其针对中文场景优化的分词算法和多模态处理能力,可有效解决技术文档管理中的术语识别和格式兼容问题。这类系统在开发团队知识沉淀、新员工培训等场景中价值显著,特别是当集成RBAC权限模型和自动化备份策略后,既能保障信息安全,又能实现持续的知识迭代。通过合理配置同义词扩展和权重调整,可使搜索命

weixin_29041195的博客 262

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万+

DEM高程数据的获取、合并与坐标转换

DEM高程数据的获取、合并与坐标转换一、DEM数据的获取二、数据合并三、投影转换方法一四、投影转换方法二 今天用DEM数据做了一个坡度分析,数据使用过程中涉及到投影坐标转换,由于不是很熟悉所以费了一番功夫。经过一番折腾总结出两个方法,方法一自认为比较便捷的方法,即通过BIGMAP软件中工具列表中的投影转换功能进行。方法二为传统方法,即在Arcgis中用投影栅格工具进行转换。 一、DEM数据的获取 在地理空间数据云网站下载DEM数据(精度包括30米和90米),数据格式为tif格式或img格式,坐标为WGS_1

weixin_48625651的博客 1万+

rk3576 点亮 LCD(mipi)

瑞芯微 RK3576 是一款面向中高端 AIoT 市场的 SoC,其 MIPI DSI (Display Serial Interface) 接口在性能和灵活性上相比前代(如 RK3399/RK3568)有显著提升,特别是在物理层协议的支持上更加现代化。相比RK3399 RK3568的mipi 接口少了 8lane,但是RK3576 MIPI DSI 增加更低功耗的 C-PHY。

weixin_35723192的博客 364

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

Windows 下运行 openclaw 出现“‘openclaw‘ 不是内部或外部命令,也不是可运行的程序或批处理文件“的解决方案

方案适用场景推荐指数检查并手动添加 PATH明确知道全局安装目录,只是没加进PATH⭐⭐⭐⭐⭐pnpm setup 自动配置使用 pnpm 安装,想要省心的自动化方式⭐⭐⭐⭐⭐npx 免安装临时运行快速验证核心程序是否正常,排除法排查⭐⭐⭐⭐清理残留后重装npm/pnpm 混用导致版本混乱⭐⭐⭐⭐改用 WSL2不熟悉 Windows 路径体系,长期使用⭐⭐⭐'openclaw' 不是内部或外部命令这类报错,本质上不是"程序坏了",而是。

一键难忘的博客 1万+
上一篇: 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、付费专栏及课程。

余额充值