Improvising music is like giving a speech off the cuff. Before you can do it, you need to know some vocabulary and grammar. In music, the vocabulary is riffs, phrases, scales, sequences and other melodic building blocks. The grammar is music theory. It’s not necessary to learn either one formally, you can figure them out on your own through trial and error. But a good teacher can make the process a lot easier.
You can build up your vocabulary by studying other people’s improvisation, especially by transcribing from recordings. Working out melodies by ear is another good way to build vocabulary — as you stumble around and try to determine which note comes next, you’re doing a lot of experiential learning.
Music theory is the improviser’s best friend. Knowing the relationship between scales and chords frees your imagination, opening up new musical areas for you to explore. When you’re up on stage playing a solo, it’s not like you’re explicitly thinking “okay, a D7 chord is coming up, so I need to play mixolydian.” But having that knowledge thoroughly mastered means that when you get on stage you’ll have a bunch of notes under your fingers that you know will sound good. It’s up to you whether you want to stay in safe territory or venture out into crazier sounds, but it helps to know where the safe territory is.