Ratings come from randomly selected housholds that are given a box to monitor their TV viewing for a set period of time. You probably have to fill out a form identifying demographic information before you are able to participate. It's administered by the Nielsen company.
Focus groups are probably similar but on a much more specific level.
It's kind of silly that these things determine what stays on TV and what is canceled since a lot of people get their viewing from other means, and these things are never truly random anyway (families are oversampled for instance), but this is how it's been for the last 50 years. =/