It could be a number of issues but when you said it mainly happens when it rains then i would put money on it being a bad connection in the wiring harness to the transmission. Maybe water causing a short circuit & then once it’s dried out the transmission control unit thinks the fault has cleared.
I would follow the wiring harness from the left side of the dash, through to the gearbox. Checking for any breaks in insulation & also the security of any connector blocks outside of the interior of the vehicle. I know the Subaru Forester has 2 BIG connector blocks on the top of the gearbox around the bell housing area. It maybe the problem lies in those. Google your transmission wiring harness & see what the photos show you.
Good luck