Showing posts with label math. Show all posts
Showing posts with label math. Show all posts

Monday, May 26, 2025

Optimizing objective functions defined over partitions using the Genetic Algorithm

Earlier this year, I needed to find the best way to divide a set of $n$ things into $k$ subsets so that when an optimization is run in batches with the universe divided that way, the best overall result is achieved.  Mathematically, the problem is to optimize an objective function defined over partitions of a set.  A common instance of this problem is cluster analysis, where the objective function is a summary measure of within-cluster variation.  Another example is the multi-way number partitioning problem that arises in job scheduling, where the problem is to allocate jobs to processing units so that some characteristics of performance or throughput are optimized.  These problems are in general NP-hard, unless the objective function has nice properties or there is some natural way to limit the search space or to direct the search.

Brute force is never really an option even for small $n$.  The number of ways to divide a set with $n$ elements into $k$ subsets grows very, very fast.  For example, with $n =100$  and $k = 15$, there are more than $10^{100}$ ways to partition the set.   See Stirling Numbers of the Second Kind for the formula.

For the general problem, in which nothing useful is known about the objective function, dynamic programming, integer programming, greedy algorithms, local search, simulated annealing, multilevel k-way partitioning and genetic algorithms are all possible ways to attack the problem.  We focus here on the last one.

Solution using the Genetic Algorithm

One way to direct the search for good partitions is to represent partitions as chromosomes and use the Genetic Algorithm (GA) with chromosome fitness determined by the objective function.

This github repo contains a framework for optimizing objective functions defined over partitions using a Java implementation of GA.  The Apache Commons Math GA implementation that it uses is not optimized for performance or scale. Neither is the optimize-partition framework built on top of it.  This is proof of concept code to use in experiments to see if the GA can find good partitions.  The tl;dr is that it can as long as either $n$ is small or good partitions are not too sparse in the topology of pointwise convergence on $^n k$ (viewing $k$-size partitions as functions $n \to k$).  That is just a fancy way of saying that the implementation will find good solutions in reasonable time if given a random partition, one can turn it into a "good" partition by making a reasonably small number of element placement changes.  

The chromosome representation of a partition views the partition as a list of partition-piece values, one each for the elements in the universe.  Here is an example.

Suppose that $U = \{0, 1, 2, 3, 4, 5\}$ and $P = \{\{0,1\},\{2\}, \{3,4\}, \{5\}\}$  is a partition of $U.$

We can represent $P$ with the integer array $[0,0,1,2,2,3].$  The first two $0$ entries indicate that the first two elements of $U$ are assigned to the first partition piece in $P$.  The next value means that the third element of $U$ is assigned to the second partition piece.

The sets in a partition don't really have an order, so relabeling them results in a different chromosome representing the same partition.  For example, $[2,2,1,0,0,3]$  is another chromosome representation of partition represented by $[0,0,1,2,2,3].$   Every partition with $k$ pieces has $k!$ chromosome representations.  At first this looks like a suboptimal feature of the encoding, but it actually helps the search as each good partition ends up having $k!$ basins of attraction.

To apply the Genetic Algorithm, we need a way for chromosomes to "cross" with one another to create new chromosomes.  Our first attempt at crossover interleaves partition placement decisions of the parents.  So for example, 

$[0,0,1,2,2,3]$ crossed with $[2,0, 2, 3, 1, 3]$ gives $[0,0,1,3,2,3]$.  

The first chromosome determines the first value, the second one the second, the third comes from the first, and so on.  Sometimes, crossover defined this way results in "holes" (unused partition pieces).  Those have to be discarded when we are searching for fixed size partitions.

Our first idea for mutation is just random reassignment of a single value.

The algorithm starts with an initial population of chromosomes, usually randomly generated. 

Then successive populations are generated by

  1. Compute fitness for each chromosome in current generation
  2. Pass the top elitismRate chromosomes directly through to the next generation
  3. While next generation still has space, randomly select 2 parents from current generation and
    • With probability crossoverRate, replace the parents with each crossed with the other
    • With probability mutationRate, replace the crossed pair with mutation applied to each element.
Evolution continues until numGenerations generations have been created.

Experiments

Unit tests in optimize-partition apply the GA to some partition search problems with known optimal solutions.  In each case, with suitable parameters and enough generations, optimize-partition finds an optimal solution.


Spread the max value

Suppose $U = \{0, ..., 99\}$ and $g: U \to \mathbb{R}$ is defined by by $g(i)= 10$ for $i < 5$ and $g(i) = 0$ for $i \geq 5.$

Then define partition fitness by summing the max value of $g$ over each piece of the partition.  So for example,  given the $5$-piece partition is 

$P = \{\{0, 1\}, \{2,  3\}, \{4, 5\}, \{6\}, \{7, ..., 99\}\}$

$P$ has fitness $10 + 10 + 10 + 0 + 0 = 30$

Optimal $5$-piece partitions are those that take the five initial elements of $U$ (where $g$ takes the value $10$) and spread them across the pieces of the partition.  The maximum attainable fitness is $50$.

The test cases in the class TestOptimizePartition show that the GA consistently finds optimal partitions for this problem.

Cluster analysis

The test cases in the class TestClusterPartitionOptimizer test a form of GA-clustering on randomly generated test datasets.  The universe for each test consists of 50 random points in $\mathbb{R}^3$.  Each point is a random deviate from a pre-determined centroid created by adding Gaussian noise to each component.  Each centroid has 9 deviates around it.  The centroids are generated to be at least 10 units apart and the component noise has standard deviation $0.1$, so their is (almost certainly) a unique solution and the clustering problem is easy.  The objective function is the negated sum of intra-cluster pairwise Euclidean distances.  The tests show that the GA finds the unique optimal solution consistently after 100 generations.

Our implementation of this example is basically the same as that described in A Genetic Algorithm Approach to Cluster Analysis.  See that paper for more empirical performance and accuracy results.



Sunday, January 14, 2024

Why I love mathematics

Millie and Al's https://www.flickr.com/photos/27480193@N05/

I love mathematics because it never says one thing and does something else. If it ever seems to do that, it is always because I am missing some idea. I never stay mad at mathematics.

I love mathematics because it is always there, waiting for me. It will always be there even if I don't jump on it right now. It worn't run away or turn into some not fun thing. When I go back over mathematics that I haven't looked at in a while, it's like going back to the old neighborhood and having that warm and happy feeling you get when nothing has changed. 

I love mathematics because it loves me. Mathematics has infinite patience for me. I can be arbitrarily stupid for arbitrarily long. Mathematics keeps the light on for me.

I love mathematics because it surprises me and makes me think differently all the time. I feel like Aeneas in the world of mathematics, constantly meeting monstra mirable dictu, but without the carnage.

Sunday, October 11, 2020

A little dusting vs. getting buried - why variance matters in ranking risks

Some simple risk management frameworks recommend stack ranking risks based on expected loss should they materialize.  The simple formula $L(r) = P(r) E(C(r))$ is sometimes used, where $P(r)$ is the probability that a risk event of type $r$ materializes and $E(C(r))$ is an estimate of the cost associated with such an event.  So for example, if the cost of a data breach at a company is estimated to be $\$1m$ and the estimated probability of this happening is $.01$, then $L$ is in this case estimated to be $\$10k$.  Given estimates of $P(r)$ and $E(C(r))$ for the different risks faced by a company or individual, a natural way to rank them is by $L$ values.  The problem with this approach is that it fails to take into account the variance in $C$ and it also puts too much emphasis on the point estimate of $L$.

Consider the following example.  Suppose that a company has one risk $r$ with $P(r) = 0.01$ and $E(C(r)) = \$1m$ and another risk $s$ with $P(s) = 0.01$ and $E(C(s))= \$800k$.  Suppose further that a realized loss of more than $\$1.2m$ is catastrophic for the company, meaning losses of this amount or greater cannot be absorbed.  If $C$ has no variance for both $r$ and $s$, neither is a catastrophic threat and it makes sense to prioritize mitigating $r$ over $s$.

The problem is that in real world situations, $C$ always has variance and when what you really care about is guarding against large losses, that variance changes the equation.  In the example above, suppose that $C(r)$ is normally distributed with mean $1m$ and standard deviation $100k$ but $C(s)$ has a uniform distribution with minimum $0$ and maximum $1.6m$.  This means that the values of $C(r)$ should follow a bell-shaped curve clustering around the mean $E(C(r)) = 1m$ but the values of $C(s)$ are randomly spread across the interval $[0,1.6m]$ with no range of values any more likely than any other.

The probability that $r$ results in a catastrophic loss under these assumptions is $P(r) P(C(r) > 1.2m) = .01 \times P(N(1, 0.1) > 1.2)$ where $N(\cdot,\cdot)$ is the normal distribution.  Now $P(N(1, 0.1) > 1.2)$ is approximately $0.023$, so that means the probability that $r$ unmitigated will result in a catastrophic loss is approximately $0.01 \times 0.023 = 0.00023$.

For $s$, $P(C(s) > 1.2) = (1.6 - 1.2) / 1.6 = 0.25$, so the probability that $s$ results in a catastrophic loss is $0.01 \times 0.25 = 0.0025$, which is more than ten times higher. So if what the company wants to do is to minimize the probability of catastrophic loss, $s$ is actually a much more important risk to mitigate.  

The practical problem is that in general the distributions of the cost functions are unknown as are their expected values.  But just asking the question of how bad a loss can be and how likely a tail event is can lead to better risk prioritization decisions.  The example above is mathematically extreme.  The uniform distribution is just one big tail.  But it does illustrate what happens when there is a lot of probability mass in the bad part of the cost distribution.

I recently ran across this tragic, but beautiful post that illustrates the main point here very well.  The author puts it simply,

    "There are three distinct sides of risk 

  • The odds you will get hit
  • The average consequences of getting hit
  • The tail-end consequences of getting hit" 
The odds of getting hit are $P(r)$, the average consequences are $E(C(r))$ and the tail-end consequences of getting hit are the upper tail of the distribution of $C(r)$.

Wednesday, November 11, 2015

A very crowded corner

OK, time for a little math walk.  Imagine that Bolzano's grocery is running a special on Weirstrass' Premium Vegan Schnitzel.  People start converging on the corner in front of Bolzano's from all around.  Based on counts using awesome new really big data technology, the local news media makes the amazing announcement that there are infinitely many people in the city block around Bolzano's.  The subject of this walk is showing that there must be at least one location in that block where you can't move even the slightest distance without bumping into someone.

To simplify things, lets smash everything down into one dimension and pretend that the city block above is the closed interval $[0, 1]$ on the real number line.  Let's represent the infinite set of people as points in this interval.  Now consider the subintervals $(0, .1), (.1, .2), ... (.9, 1).$  At least one of these intervals must contain infinitely many people.  Suppose, for example, that the interval $(.5, .6)$ contains infinitely people.  Then split that interval into 10 segments, as shown in the picture below.   At least one of these has to contain infinitely many people.  Suppose, again for example, that this subinterval is $(.537, .538)$.

Now consider the number .537. We know that there are infinitely many people within .001 of .537.  There is nothing stopping us from continuing this process indefinitely, finding smaller and smaller subintervals with left endpoints $.5, .53, .537... $ each containing infinitely many people.  Let $r$ be the number whose infinite decimal expansion is what we end up with when we continue this process ad infinitum.  To make $r$ well-defined, let's say that in each case we choose the left-most subinterval that contains infinitely many people.  Depending on how the people are distributed, $r$ might be boring and rational or something exotic like the decimal expansion of $\pi$.  The point is that it is a well-defined real number and it has the property that no matter how small an interval you draw around it, that interval includes infinitely many people.   This is true because for each $n$, the interval starting at $r$ truncated to $n$ decimal digits and ending $1 / 10^n$ higher than that contains both $r$ and infinitely many other people by construction.  In the example above, for $n = 3$, this interval starts at $.537$ and ends at $.538$.

Now let's remove the simplification, one step at a time.  First, let's see how the same construction works if in place of $[0, 1]$ we use any bounded interval $[a, b]$.  Consider the function $f(x) = (x - a) / (b - a)$.  That function maps $[a, b]$ onto $[0, 1]$.   Its graph is a straight line with slope $1/(b - a)$.  If $b - a$ is larger than 1, points get closer together when you do this mapping; otherwise they get further apart.  But the expansion or contraction is by a constant factor, so the picture above looks exactly the same, just with different values for the interval endpoints.  So if we do the construction inside $[0, 1]$ using the mapped points, then the pre-image of the point $r$ we end up with will be an accumulation point for the set in $[a, b]$.

OK, now lets pick up our heads and get out of Flatland.  Imagine that the square block around Bolzano's is the set of points in the x-y plane with both x and y coordinates between 0 and 1.  Divide up the square containing those points into 10 equal-sized pieces.  One of those pieces has to contain infinitely many people. Suppose it is the square with bottom-left coordinates (.5, .2).   Now divide that little square into 10 subsquares.  Again, one of these has to contain infinitely many people.  Say it is the one with lower-left coordinates (.53, .22).   The picture below shows these points and a next one, say, (.537, .226).  Just like the one-dimensional case, this sequence of points converges to an accumulation point (x,y) that has infinitely many people within even the smallest distance from it.

The ideas presented above are the core of one proof of the Bolzano-Weierstrass Theorem, a beautiful and very useful result in Real Analysis.  The existence of the limiting values is guaranteed by the Least Upper Bound Axiom of the real numbers. 

Friday, October 28, 2011

Correlated failure in distributed systems

Every time I start to get mad at Google for being closed and proprietary, they release something really interesting.  The paper, Availability in Globally Distributed Storage Systems  is loaded with interesting data on component failures and it presents a nice framework for analyzing failure data.  The big takeaway is that naive reasoning about "HA" deployments can lead to inflated expectations about overall system availability.

Suppose you have a clustered pair of servers and each is 99% available.  What availability can you expect from the clustered pair?  "Obviously," $99.99\%.$

Unfortunately, that expectation assumes that the servers fail independently - i.e., component failures are not correlated.  The Google research shows that this can be a bad assumption in practice.  Referring to storage systems designed with good contemporary architecture and replication schemes, the authors say, "failing to account for correlation of node failures typically results in overestimating availability by at least two orders of magnitude."  They go on to report that due to high failure correlation, things like increasing the number of replicas or decreasing individual component failure probabilities have much weaker effects when you take correlation into account.

Steve Laughran does a nice job summarizing the practical implications of the specific area covered by this research.  What is interesting to me is the model proposed for quantifying correlation in component failure and estimating its impact on overall system availability.   Its easy to come up with scenarios that can lead to correlated component failures, e.g. servers on a rack served by a single power source that fails; switch failures; bad OS patches applied across a cluster.  What is not as obvious is how to tell from component-level availability data what counts as a correlated failure and how to adjust expectations of overall system availability based on the extent of correlation.

The first question you have to answer to get to a precise definition of correlation in component failure is what does it mean for two components to fail "at the same time" or equivalently what does it mean for two observed component failures to be part of a single failure event?  The Google authors define a "failure burst" to be a maximal sequence of node failures, all of which start within a given window-size, $w$, of one another.   They use $w=120$ seconds for their analysis, as this matches their internal polling interval and it also corresponds to an inflection point on the curve formed when they plot window size against percentage of failures that get clubbed into bursts.

We can define correlation among node failures by looking at how the nodes affected by bursts are distributed.  The practically relevant thing to look at is how often nodes from system architecture domains fail together - for example, to what extent do node failures occur together in the same rack.  If failures are highly rack-concentrated, for example, having system redundancy only within-rack is a bad idea.

Given a failure burst consisting of a set $N = {f_0,..., f_n}$ of failing nodes and a partition $D = {d_0, ... , d_m}$ of $N$ into domains, we will define the $D$-affinity of $N$ to be the probability that a random assignment of failing nodes across domains will look less concentrated than what we are observing.  High $D$-affinity means correlation, low means dispersion or anti-correlation.  If domains are racks, high rack-affinity means failures are concentrated within-rack.

To make the above definition precise, we need a measure of domain concentration.  The Google paper proposes a definition equivalent to the following.  For each $i = 0, ..., m$ let $k_i$ be the number of nodes in $N$ included in $d_i$.  So for example if the $d_i$ are racks, then $k_0$ is the number of nodes in rack $0$ that fail, $k_1$ counts the failures in rack $1$, etc.   Then set $x = \sum_{i=0}^{m}{k_i \choose 2}$.  This makes $x$ the number of "failure pairs" that can be defined by choosing pairs of failing nodes from the same domain.  Clearly this is maximized when all of the failures are in the same domain (every pairing is possible) and minimized when all failing nodes are isolated in different domains.  Increasing domain concentration of failures increases $x$ and disaggregating failing nodes decreases it.

Now let $X$ be a random variable whose values are the values of $x$ above.  For each possible value $x$ define $Pr(X = x)$ to be the likelihood that $X$ will take this value when failing nodes are randomly distributed across domains.  Then for each value $x$, define $r_x = Pr(X < x) + \frac{1}{2}Pr(X = x)$.  Then $r_x$ measures the likelihood that a random assignment of failing nodes to domains will result in concentration at least as large as $x$.  The $\frac{1}{2}$ is to prevent the measure from being biased, as we will see below.  A value of $r$ close to $1$ means that failures are highly correlated with respect to domain, while values close to $0$ indicate dispersion.  With domains equal to racks and $r$ called rack-affinity, the Google paper reports:
We find that, in general, larger failure bursts have higher rack affinity. All our failure bursts of more than 20 nodes have rack affinity greater than 0.7, and those of more than 40 nodes have affinity at least 0.9. It is worth noting that some bursts with high rack affinity do not affect an entire rack and are not caused by common network or power issues. This could be the case for a bad batch of components or new storage node binary or kernel, whose installation is only slightly correlated with these domains.
The authors point out that it can be shown that the expected value of $r$ is $.5$.  To see this, let $x_0, x_1, ..., x_t$ be the values of $X$ as defined above and for each $i = 0, ..., t$ let $p_i = Pr(X = x_i)$.  Then the expected value of $r$ is $$E(r) = \sum_{i=0}^{t}\left\{p_i \left(\sum_{j=0}^{i-1}p_j + \frac{1}{2}p_i\right)\right\}.$$Since $\sum p_i = 1$, we must have $(\sum p_i)^2 = 1$.  Expanding this last sum and the sum for $E(r)$, it is easy to see that $E(r) = \frac{1}{2}(\sum p_i)^2$.  Note that this applies to any discrete probability distribution - i.e., $r$ as above could be defined for any discrete distribution and its expectation will always be $.5$.  Note also that while $r$ can take the value $0$, its maximum value is $1 - \frac{1}{2}p_t.$  For $X$ as defined above, $p_t$ is the probability that all failures are in the same domain, which is $1/B_N$ where $N$ is the total number of nodes and $B_N,$ the $Nth$ Bell number, is the number of ways that the $N$ nodes can be partitioned.

Computing the value of $r$ given counts $c_0, c_1, ..., c_m$ of failing nodes by domain is non-trivial.  According to the Google authors,
It is possible to approximate the metric using simulation of random bursts. We choose to compute the metric exactly using dynamic programming because the extra precision it provides allows us to distinguish metric values very close to 1.
I have not been able to figure out a straightforward way to do this computation.  Maybe the Googlers will release some code to do the computation on Google Code.  The only way that I can see to do it is to fully enumerate partitions over the node set, compute $x$ for each partition and build the distribution of $X$ using frequency counts.  Patches welcome :)

The Google paper stops short of developing a framework for using estimates of node failure correlation in end-to-end system availability modelling.  That would be an interesting thing to do.  Here are some simple observations that might be useful in this regard and that also illustrate some of the practical implications.

Correlation cuts both ways - i.e., it is possible to do better than independence if a system's deployment architecture splits over domains with high failure affinity.  Consider, for example, an application that requires at least one database node to be available for it to provide service.  Suppose that database node failures are perfectly rack-correlated (i.e., all database node failures are concentrated on single racks).  Then if the application splits database nodes over racks (i.e. has at least one node in each of two different racks) it can deliver continuous availability (assuming the database is the only thing that can fail).

End-to-end HA requires splitting over all domains with high failure correlation. Suppose that in the example above, database node failures also show high switch affinity.  Then to deliver HA at the application level, you need to ensure that in addition to having database nodes in two different racks, you also need nodes connected to at least two different switches.

As always, correlation does not imply causation.  The Google paper makes this point in a couple of places.  Suppose that in our simple example all database failures are in fact due to database upgrades and the operational practice is to apply these upgrades one rack at a time.  That will result in high rack affinity among failures, but the failures have nothing to do with the physical characteristics or failure modes of the racks or their supporting infrastructure. 

The observations above are basic and consistent with the conventional wisdom applied by operations engineers every day.  In an ideal world, HA systems would be designed to split over every possible failure domain (rack, switch, power supply, OS image, data center...).  This is never practical and rarely cost-effective.  What is interesting is how quantitative measurements of failure correlation can be used to help estimate the benefit of splitting over failure domains.  Just measuring correlation as defined above is a good start.

Tuesday, July 19, 2011

Self-organization is "supra-optimal"

Thanks to a post shared by Eric Le Goff on Google+, I ran across a very interesting article describing some fundamental research on neuronal network organization.  The authors have developed a research "platform" that enables them to grow physical neuronal networks on chips.  They are using the platform to observe self-organizing behavior of the networks.  What is becoming clear from this and other research is that the large-scale architecture and macro behavior of our brains is most likely the result of self-organizing collaboration among a hierarchy of network clusters, each "operating" with locally conditioned architecture and control.

After reading the article, I was embarrassed to notice that I had not yet heard of Plos One, where it appeared.  Poking about Plos One, I stumbled on yet another article on self-organizing behavior.  Somebody must be trying to tell me something.   The second article is a nice visceral illustration of how we need to think differently about how to manage complex systems.   The authors look at train scheduling in public transportation systems.  They show that "global" scheduling systems for train arrival and departure times can be beaten by a system that imitates ant colony behavior - trains emitting "anti-pheromones" that signal trains behind them to modify their behavior.   What is interesting here is that independent decision-making based on locally available information can result in better global outcomes than a globally engineered solution.

These ideas are not new.  What these two articles illustrate, however, is how much change is going to be required in how we think about modelling and engineering to take advantage of them.  For example, the whole concept of "control" in the pure engineering sense is going to have to be transformed to engineer the kinds of systems that the second article hints at.  Imagine trying to apply six sigma to that transportation system.   Similarly, the first article indicates that it is likely hopeless to try to get much more than we already have from macro-level decomposition of the brain or functional/reductionist analysis of isolated neuronal networks.

I also notice that Plos.org has opened up their search APIs and (jointly with Mendeley) launched "a contest to build the best apps that make science more open."  Hmm...somebody is really trying to tell me something here.

Saturday, July 16, 2011

Remembering how to count

Today, rummaging through the boxes of books that follow me from house to house, I stumbled on a first edition, 1940 hardbound copy of Mathematics and the Imagination by Edward Kasner and James Newman that my mother gave me years ago.  Kasner is probably best known for having come up with the name - or more precisely goading a child into inventing the name - "googol."  The book begins with a delightful account of how the very large, but finite is sometimes confused by adults and "moderns" with the infinite, but small children and the ancient Greeks could see things more clearly.  I like this quote:
The Greeks had very definite ideas about the infinite.  Just as we are indebted to them for much of our wit and learning, so are we indebted to them for much of our sophistication about the infinite.  Indeed, had we always retained their clear-sightedness, many of the problems and paradoxes about the infinite would never have arisen.
The authors do a really nice job motivating what was to me as a student just a definition - that cardinality is based on one-to-one correspondences.  What they bring out really nicely is how this really is just counting.

Another great point that comes out in many places in the book is how mathematicians often choose what turn out to be stupid names for things, because we can name them before we know them.  A great example is "transcendental numbers."  Such a name suggests something exotic or rare.  It turns out that almost every real number is transcendental.

What does that mean, exactly?  I am going to try to explain this in less time than it takes you to get bored - in just a short walk through a truly beautiful neighborhood built by Georg Cantor.

A transcendental number is a number that cannot be expressed as a solution to a polynomial equation with rational coefficients.  The square root of two, for example, is not transcendental because it is a solution to the equation x2 - 2 = 0.   It turns out that both e and π are transcendental. Initially mathematicians thought this was a very special property worthy of such an exalted name.

Cantor saw two things: 1) algebraic numbers (the complement of transcedental numbers) can be put into one-one correspondence with the set of natural numbers (i.e., they are countable) 2) the whole set of real numbers is uncountable (cannot be put into 1-1 correspondence with the natural numbers).  That means that all but a comparatively tiny set of real numbers are transcendental!  You can take away all of the algebraic numbers without affecting the size of the set of real numbers (or leaving any "holes" in the real line).

Imagine a spreadsheet with an infinite number of rows and columns:
A0 A1 A2 A3 ...
B0 B1 B2 B3 ...
C0 C1 C2 C4 ...
D0 D1 D2 D3 ...
...
Cantor realized that as long as the row and column indexes were all natural numbers,  the entire set of cells could be put into 1-1 correspondence with the natural numbers (i.e. "counted") by just starting in the top left corner and following a path that snakes outward along the diagonals:  A0, A1, B0, C0, B1, A2, A3, B2, C1, D0, D1, C2, B3, A4, ...

Since the rational numbers are just numerator/denominator pairs of integers, the technique above can be used to count them - i.e., to show that the rationals are countable.  But really, what it shows is that 1) the set of ordered pairs of any countable set is countable and 2) the union of countably many countable sets is countable.  The second is clear when you think of the rows of the spreadsheet as enumerations of the elements in the sets over which the union is taken.

Now imagine a "spreadcube" - a rubix-cube like thing that has little subcubes for cells.  Again, imagine it as countably infinite in all three dimensions.  The "pick a corner and snake out" game works there too.  So the set of ordered triples (a, b, c) from any countable set is also countable.  To get to the next dimension, you can either just test your 4-dimensional intuition (too hard for me) or just look at (a, b, c, d) as ((a, b, c), d) and use the fact that there are only countably many (a, b, c) (note that we could have done this for n = 3 instead of imagining the spreadcube).  Obviously, there is no stopping us here, so we see that for each n, the set of n-tuples of elements from any countable set is countable.   Since the coefficients of a polynomial determine the polynomial, that means that for each n, there are only countably many polynomials of degree n with rational coefficients.  By 2) above that means that there are only countably many polynomials with rational coefficients.  Each of these has only finitely many roots, so the union of all of the sets of roots of all of the polynomials with rational coefficients is countable - i.e. there are only countably many algebraic numbers.

Now the coup de gras.  Since we seem to be able to count everything, lets suppose that via snakes, pairing or some other ruse we have managed to enumerate the real numbers - i.e., we have put them in a list that goes r0, r1, r2 ... and eventually hits every real number.   Every real number has a decimal expansion.  Some terminate, like 5.2, some repeat, like 0.333333 and some, like π do exotic things that keep computers busy for indefinite amounts of time; but all have decimal representations and two real numbers are equal if and only if they have exactly the same values in their decimal expansions in every digit [1].   Suppose that our enumeration looked like this:

r0 = 12.238769045
r1 =  3.1415923988888
r3 = 23.1783459823999
...
Consider the number r = 0.359 in relation to the three numbers above.  It is obviously not equal to any of them.  It was constructed to be different from any of them as follows.  Put a 3 in the first decimal digit because r0 has a 2 there; put a 5 in the second decimal digit because r1 has a 4 there; put a 9 in the third decimal digit because r3 has an 8 there.   Now imagine the list continuing.  We continue to define the decimal expansion of our "special" number r making it different from the nth element in the list in the nth decimal place.  The result will be a number that differs from every number in the list.  This is a contradiction,  proving that no such enumeration can exist.

This is not a satisfying place to leave Mr. Cantor's neigborhood, since we have not succeeded in counting the real numbers at all.  So even though you are likely, like my dog Casper, getting a little tired of this walk, I need to stop by one more place on the way home.   To count the real numbers, lets start by convincing ourselves that it suffices to count the elements of the open interval (0, 1).  Look at the middle section of the graph below of the tangent function


The middle section of this graph shows that (-π/2,π/2) can be mapped onto the full real line. Every y value in the graph corresponds to some x value in the bounded open interval above.   The graph depicts a one-to-one correspondence between the whole real line (the y axis) and the little π-length interval in the middle of the picture along the x axis. Just squishing the picture a little and moving it to the right shows that (0, 1) could similarly be mapped onto the whole real line.

Now, similarly to decimal representation, every real number has a binary expansion.  The number 1/2 is 0.1 in binary, 0.11 is 1/2 + 1/4 = 3/4, 0.101 is 1/2 + 0/4 + 1/8 = 3/8 and so on.  Like decimal expansions, binary expansions are unique, some terminate and some don't and two numbers between 0 and 1 are equal iff their binary expansions have 1's (or 0's) in all the same places.   Therefore, there is a one-one correspondence between the real numbers between 0 and 1 and the set of subsets of the natural numbers.  Let each real number correspond to the set of natural numbers where its binary expansion has a "1".  So 1/2 corresponds to {0}, 3/4 corresponds to {0, 1}, 3/8 corresponds to {0, 2} and so on.  The set of all subsets of a set is called the power set of the set.  The above shows two important things: 1) the power set of the natural numbers in uncountable and 2) the power set of the natural numbers has the same cardinality as the real numbers.   An interesting question is does there exist a size in between the natural numbers and the real numbers.  We are not going to see an answer to that question in this neighborhood.

[1] Strictly speaking, some numbers have two infinite decimal expansions.  For example 0.9999999 (repeating indefinitely) equals 1.  We are assuming above that all of the representations selected are minimum length (i.e. if there is a finite representation, choose that).