The Somali government has declared victory in Mogadishu after African Union peacekeepers drove al-Shabaab rebels out of the city.

Around 9,000 troops, both government forces and soldiers from the African Union Mission in Somalia, engaged in rebel fighters in battle early this week, eventually them out of the city, the government said. President Sheikh Sharif Ahmed touted the battle as a triumph for Somalia, but al-Shabaab said it made only a tactical retreat.

"We have abandoned Mogadishu but we remain in other towns," rebel spokesman Sheikh Ali Mohamud Rage said on the al-Shabaab-run Andalus radio station.

"We aren't leaving you, but we have changed our tactics. Everyone of you will feel the change in every corner and every street in Mogadishu. We will defend you and continue the fighting," Rage said.

Prior to the battle, al-Shabaab was the dominant force in the capital. With backing from al-Qaida, they have been occupying Mogadishu for the past four years and have thrived in a nation that hasn't had an effective central government for 20 years.

"It was not the strength of al-Shabaab that kept them in Mogadishu for so long, it was the incompetence and weakness" of the transitional national government, Afyare Elmi, a professor at Qatar University's international affairs department, told Reuters.

"I'm worried the (government) may not be able to step into the vacated areas and other clan militia step in. The challenge ... is to expand into these areas and install law and order," he said.

Troops are now clearing buildings of explosives, and are asking displaced residents not to return home until the work is complete.

Somalia is currently suffering from a massive and growing famine, which is being considered the worst humanitarian disaster in Africa in two decades. Thousands of Somalis have flocked to Mogadishu in the past two months, hoping to find work, food and safety.

Al-Shabaab still controls at least two of the five famine-struck regions of Somalia, Bakool and Lower Shabelle.

"The retreat by our forces is only aiming to counterattack the enemy," Rage said. "People will hear happy news in the coming hours,"

"We shall fight the enemy wherever they are."

A total of 12.4 million people in Somalia require immediate assistance, according to the U.N. Office for the Coordination of Humanitarian Affairs, and the number of people needing lifesaving humanitarian assistance could reach 15 million before the situation begins to turn around. One quarter of Somalia's 7.5 million people have been displaced internally or abroad.