Tuesday, July 31, 2012

Surfacing good comments

Comments are supposed to make digital media more engaging and interactive. Somewhere in the crowd of readers and viewers are ideas, insight and thoughtful criticism. However, the comments found on popular internet sites like YouTube or news sites generally inspire a loss of faith in humanity. From the comfort and pseudo-anonymity of thousands of living rooms comes a stream of abuse, wingnuttery and outright stupidity that overwhelms etiquette and common sense.

Clay Shirky thinks Gawker is on to something with its attempts to surface quality comments. Gawker redesigned their comments section to serve the people reading the comments, rather than the people writing them, moving most comments off the main page of an article and enabling enhanced curation.

Manual curation is labor intensive. I wonder whether a machine learning approach might be able to do a reasonable job of identifying good comments, or at least weeding out most of the inane ones. It's not really much different than spam filtering. That might make a fun little project.

Thursday, July 26, 2012

Linear regression by gradient descent

In Andrew Ng's Machine Learning class, the first section demonstrates gradient descent by using it on a familiar problem, that of fitting a linear function to data.

Let's start off, by generating some bogus data with known characteristics. Let's make y just a noisy version of x. Let's also add 3 to give the intercept term something to do.

# generate random data in which y is a noisy function of x
x <- runif(1000, -5, 5)
y <- x + rnorm(1000) + 3

# fit a linear model
res <- lm( y ~ x )
print(res)

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
     2.9930       0.9981

Fitting a linear model, we should get a slope of 1 and an intercept of 3. Sure enough, we get pretty close. Let's plot it and see how it looks.

# plot the data and the model
plot(x,y, col=rgb(0.2,0.4,0.6,0.4), main='Linear regression by gradient descent')
abline(res, col='blue')

As a learning exercise, we'll do the same thing using gradient descent. As discussed previously, the main idea is to take the partial derivative of the cost function with respect to theta. That gradient, multiplied by a learning rate, becomes the update rule for the estimated values of the parameters. Iterate and things should converge nicely.

# squared error cost function
cost <- function(X, y, theta) {
  sum( (X %*% theta - y)^2 ) / (2*length(y))
}

# learning rate and iteration limit
alpha <- 0.01
num_iters <- 1000

# keep history
cost_history <- double(num_iters)
theta_history <- list(num_iters)

# initialize coefficients
theta <- matrix(c(0,0), nrow=2)

# add a column of 1's for the intercept coefficient
X <- cbind(1, matrix(x))

# gradient descent
for (i in 1:num_iters) {
  error <- (X %*% theta - y)
  delta <- t(X) %*% error / length(y)
  theta <- theta - alpha * delta
  cost_history[i] <- cost(X, y, theta)
  theta_history[[i]] <- theta
}

print(theta)

          [,1]
[1,] 2.9928978
[2,] 0.9981226

As expected, theta winds up with the same values as lm returned. Let's do some more plotting:

# plot data and converging fit
plot(x,y, col=rgb(0.2,0.4,0.6,0.4), main='Linear regression by gradient descent')
for (i in c(1,3,6,10,14,seq(20,num_iters,by=10))) {
  abline(coef=theta_history[[i]], col=rgb(0.8,0,0,0.3))
}
abline(coef=theta, col='blue')

Taking a look at how quickly the cost decreases, I might have done with fewer iterations.

plot(cost_history, type='line', col='blue', lwd=2, main='Cost function', ylab='cost', xlab='Iterations')

That was easy enough. The next step is to look into some of the more advanced optimization methods available within R. I'll try to translate more of the Machine Learning class into R. I know others are doing that as well.

  • The code for this post is available on GitHub as a gist

Tuesday, July 10, 2012

Katy Börner's Plug and Play Macroscopes

Two Cytoscape engineers pointed me towards Plug and Play Macroscopes by Katy Börner. The paper envisions highly flexible and configurable software tools for science through the mechanism of plugin architecture, and is highly worth reading if you're involved in building scientific software.

Decision making in science, industry, and politics, as well as in daily life, requires that we make sense of data sets representing the structure and dynamics of complex systems. Analysis, navigation, and management of these continuously evolving data sets require a new kind of data-analysis and visualization tool we call a macroscope...

A macroscope is a modular software framework enabling end users - biologists, physicists, social scientists - to assemble customized tools reusing and recombining data sources, algorithms and visualizations. These tools consist of reconfigurable bundles of software plug-ins, using the same OSGi framework as the Eclipse IDE. Once a component has been packaged as a plug-in, it can be shared and combined with other components in new and creative ways to make sense of complexity, synthesizing related elements, finding patterns and detecting outliers. Börner sees these software tools as instruments on par with the microscope and the telescope.

CIShell

These concepts are implemented in a framework called Cyberinfrastructure Shell (CIShell), who's source is in the CIShell repo on GitHub. The core abstraction inside CIShell is that of an algorithm - something that can be executed, might throw exceptions, and returns some data. Data is some object that has a format and key/value metadata.

public interface Algorithm {
   public Data[] execute() throws AlgorithmExecutionException; 
}

public interface Data {
  public Dictionary getMetadata();
  public Object getData();
  public String getFormat();
}

Parenthetically, it's too bad there's no really universal abstraction for a function in Java... Callable, Runnable, Method, Function. In general, trying to wedge dynamic code into the highly static world of Java is not the most natural fit.

I'm guessing that integrating a tool involves wrapping it's functionality in a set of algorithm implementations.

The framework also features what looks to be support for dynamic GUI construction, a database abstraction with a slot for a named schema and support for scripting in Python.

An upcoming version of Cytoscape is built on OSGi. Someone should write a genome browser along these same lines.

"To serve the needs of scientists the core architecture must empower non-programmers to plug, play, and share their algorithms and to design custom macroscopes and other tools. " In my experience, scientists who are capable of designing workflows in visual tools are not afraid of learning enough R or Python to accomplish much the same thing. I'm not saying it's obvious that they should do that. Just that the trade-offs are worth considering. The real benefit comes from raising the level of abstraction, rather than replacing command-line code with point-and-click GUIs.

Means of composition

Plugin architecture isn't the only way to compose independently developed software tools. My lab's Gaggle framework links software through messaging. Service oriented architecture boils down to composition of web services, for example Taverna and MyGrid. GenePattern and Galaxy both fit into this space, although I'm not sure I can do a good job of characterizing them. If I understand correctly, both seem to use common file formats and conversions between them as the intermediary between programs. The classic means of composition are Unix pipes and filters - small programs loosely joined - and scripting.

Visualization

In a keynote on Visual Design Principles at VIZBI in March of this year, Börner channeled inspiration from Yann Arthus-Bertrand's Home and Earth from Above, Drew Berry and Edward Tufte, and advised students of visualization to study human visual perception and cognitive processing first in order to "design for the human system".

Her workflow combines data-centric steps similar to processes outlined by Jeffrey Heer and Hadley Wickham with a detailed breakdown of the elements of visualization.

Katy Börner directs the Cyberinfrastructure for Network Science Center at Indiana University. Not content to have written the Atlas of Science (MIT press 2010), she is currently hanging out in Amsterdam writing an Atlas of Knowledge.

More

Thursday, June 28, 2012

Institute for Systems Biology at Google I/O

The Shmulevich Lab scored a nice feature in the day 2 keynote at Google I/O. (See video starting at about 40:25 and again at 46:05.) Their work on the The Cancer Genome Atlas (TCGA) was part of the introduction of Google Compute Engine.

Ilya and Hector are quoted in the case study, Cancer Investigators Use Google Compute Engine to Accelerate Life-Saving Research.

The machine learning component is a random forest application called RF-ACE and the visualization is circvis. More Shmulevich lab code can be found at Code for Systems Biology.

Sunday, June 24, 2012

Data analysis workflow patterns

About a year ago, I ran a kooky idea past some colleagues. They gave it a big WTF, so I sat on it for a while. Not to be deterred, I still like the idea, so here it is.

Workflows are key to bioinformatics. For example, an analysis of gene expression might go something like the following. Measure gene expression using arrays or RNA-seq. After a bit of normalization, cluster genes by correlated expression. Then compute functional enrichment on the clusters. This helps get at questions about how the cell reacts to some stimulus. Whether that's nutrients, toxins, pH, sunlight, whatever. Or, what's the difference between a sick cell and a healthy one. The answer is in terms of processes or pathways up or down regulated.

You might implement our analysis of gene expression in R or Python. You could do it with point and click software like MeV and web tools like DAVID or workflow tools like Galaxy. You might use k-means, hierarchical clustering or something fancier. You might use GO terms to annotate gene function or KEGG pathways. There are lots of options, but the central idea is conserved.

The notion of a data analysis workflow is something like the concept of a software design pattern, an idea that software engineers borrowed from architects. A design pattern is a general reusable template for how to solve a commonly occurring problem. Naming and documenting a design pattern makes sharing knowledge easier and lets you talk and think at a higher level of abstraction.

Thinking of the workflow as an asset, it follows that they should be collected, documented and published. "In bioinformatics, we are familiar with the idea of curated data as a prerequisite for data integration. We neglect, often to our cost, the curation and cataloguing of the processes that we use to integrate and analyse our data." (Carol Goble et al. 2008) Both Taverna and Galaxy have mechanisms for doing this, albeit within the context of those tools. Maybe a better place to document workflows would be in journals. Philip Bourne, Editor in chief of PLOS Computational Biology says, "I want the publisher of the future to be the guardian of these workflows create a better scholarly record." He's speaking here of scientific workflows in a more general context than just data analysis.

Design patterns are documented in a specific format, detailing the scenarios in which that pattern applies, the intent behind it, its structure, implementation and consequences. Examples are usually given of real usages of the pattern along with discussion of alternatives or related patterns and its risks and pitfalls. For data analysis workflows, we'd probably want to discuss possible sources of error, required conditions and statistical properties.

This is not to say we need formalism for the sake of formalism. It's tempting to get caught up with impractical methodological hoo-ha, focusing on process to the exclusion of real and practical goals. A workflow should be a tool in a researcher's toolbox, a pragmatic way to package a bite-sized piece of knowledge. To be avoided is the over-abstraction and questionable utility that some (i.e. me) see in BPEL, BPM, MDA and related (increasingly defunct) technology trends.

Rather than design patterns, maybe a more biologist-friendly term is a protocol. Plus, there's already a long history of journals dedicated to lab protocols. Why not do the same for protocols for data analysis?

More

Like every idea, good or crackpot, people have thought of this one before me.

Saturday, June 23, 2012

Composition methods compared

Clojurist, technomancer and Leiningen creator, Phil Hagelberg does a nice job of dissecting "two ways to compose a number of small programs into a coherent system". Read the original in which three programming methods are compared. These are my notes, quoted mostly verbatim:

The Unix way

Consists of many small programs which communicate by sending text over pipes or using the occasional signal. Around this compelling simplicity and universality has grown a rich ecosystem of text-based processes with a long history of well-understood conventions. Anyone can tie into it with programs written in any language. But it's not well-suited for everything: sometimes the requirement of keeping each part of the system in its own process is too high a price to pay, and sometimes circumstances require a richer communication channel than just a stream of text.

The Emacs way

A small core written in a low-level language implements a higher-level language in which most of the rest of the program is implemented. Not only does the higher-level language ease the development of the trickier parts of the program, but it also makes it much easier to implement a good extension system since extensions are placed on even ground with the original program itself.

The core Mozilla platform is implemented mostly in a gnarly mash of C++, but applications like Firefox and Conkeror are primarily written in JavaScript, as are extensions.

Sunday, June 10, 2012

Scientific imaging with Hanchuan Peng

Hanchuan Peng of Janelia Farm spoke on bioimaging at ISB a couple weeks back. He's doing some very cool work mining microscopy images doing registration - aligning individual cells across images. They've created a 3D atlas of C. elegans which tracks every cell. The still pictures don't don't do it justice. Check out the movies.

By localizing and registering neural fibers in 2,954 fly brains, Peng's group constructing this wiring diagram of the fly's 100,000 neurons.

More