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

Nvidia Jetson AGX Orin 如何进入 Recovery Mode(刷机注意事项)

Jetson Orin 如何进入Recovery mode + 刷机注意事项

Pandako's Blog 1万+

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

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

weixin_45747731的博客 299

基于YOLOv5与海康工业相机的高分辨率实时检测实践

本文详细介绍了基于YOLOv5与海康工业相机的高分辨率实时检测实践,通过优化相机配置、网络传输和YOLOv5模型适配,实现了每秒15帧以上的实时检测性能,缺陷识别准确率高达99.2%。特别适用于电子元件焊接点检测、精密齿轮齿痕检查等对微小缺陷敏感的场景。

weixin_30872499的博客 474

机载电脑与飞控串口通信(实测读取飞控IMU数据)《一、香橙派5max启动串口UART通信与飞控板通信,一次必通!》《二、allspark1与PIX6C通信踩坑及出坑》《三、orinnx载板与飞控通信》

机载电脑与飞控串口通信(实测读取飞控IMU数据)《一、香橙派5max启动串口UART通信与雷迅v5nano飞控板通信,一次必通!》《二、阿木机载电脑allspark1与PIX6C通信踩坑及出坑》,还有如何打开飞控串口以及如何提高飞控IMU频率。

2402_82745259的博客 3471

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

DEV-C++调试设置

       昨天用C/C++去考了CSP,结果用DEV-C++调试总是闪退,按照我的记忆打开了调试参数,迷迷糊糊搞了一通,还是没办法调试,难受了几个小时。所以今天痛下决心,一定要写下DEV-C++设置调试的过程,警示自己! 解决步骤 1.打开DevC++找到上方工具栏 2.点击选择编译选项,再按下图所示设置即可

懒羊羊的快乐小屋 1029

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

k3s快速搭建k8s集群环境

k8s 搭建方式有多种,如果你是内网环境,希望占用服务器资源少或是边缘系统(如ARM系统),强烈推荐您使用 k3s进行安装 目录k3s 简介k3s架构中文官方文档三台服务器快速搭建k8s集群安装说明步骤1 修改主机名,保持唯一步骤2 安装docker步骤3 安装master节点步骤4 安装worker节点加入集群步骤5 查看集群步骤6 部署 k8s仪表盘 dashboard k3s 简介 轻量级 Kubernetes。安装简单,内存只有一半,所有的二进制都不到 100MB K3s 是一个完全符合 Ku.

gzt19881123的专栏 2445

MinerU PDF解析工具:从安装配置到本地部署与API调用的全流程指南

MinerU是由上海人工智能实验室开源的高质量PDF解析工具,可将包含图片、公式、表格的复杂PDF转换为Markdown和JSON格式。安装前需准备Python 3.10-3.13环境,推荐使用8核CPU和32GB内存。支持通过HuggingFace或ModelScope下载模型,国内用户建议使用ModelScope源加速下载。配置文件中可设置本地模型路径,支持多种语言识别和两种解析后端(Pipeline和VLM)。输出包含可视化文件、内容文件和中间结果文件,并提供了完整的Python API调用示例。

算法工程师 2027

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

【系统架构设计师-2026上半年真题】综合知识-参考答案及详解(75题完全回忆版)

【系统架构设计师-2026上半年真题】综合知识-参考答案及详解(75题完全回忆版)

数据知道的博客 3106
上一篇: 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、付费专栏及课程。

余额充值