Cognitive Radio (CR) technique has been proposed for improving spectrum efficiency by dynamic spectrum access. In Cognitive Radio Networks (CRNs), unlicensed Secondary Users (SUs) with CR can utilize licensed spectrum without interfering licensed Primary Users (PUs). For effectively avoiding interference with licensed PUs and malicious attacks from jammers, a two-stage Learning-based Optimal Channel Selection (LOCS) algorithm for unlicensed SUs in distributed heterogeneous CRNs is proposed in this paper. The LOCS algorithm enables SUs to obtain real states of the licensed channels without knowing their information. Hence, SUs using LOCS algorithm can efficiently avoid collision and attack with PUs and jammers. Besides, the LOCS algorithm considers hardware limitation of the SUs, i.e., SUs can only sense and access parts of the license spectrum during any given time. SUs can select the optimal channels for spectrum sensing and data transmission by using the LOCS algorithm. Simulation results show the efficiency of our proposed algorithm in terms of collision and attack avoidance.