Why do players take the baseball and shake it in front of the umpire after the last out of an inning?

They are not shaking the ball at them so much as they are making sure the umpire sees that they are going to toss them the ball. The umpires like to inspect them before putting them back into play. The fielder is telling the umpire that he (the fielder) is removing the ball from the game. Either because, in the fielder's opinion, the ball is dirty or he is going to give the ball to a fan.