sklearn.decomposition.FastICA实现FastICA算法

关于sklearn.decomposition.FastICA的介绍http://lijiancheng0614.github.io/scikit-learn/modules/generated/sklearn.decomposition.FastICA.html

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import FastICA

C = 200  # 样本数
x = np.arange(C)
s1 = 2 * np.sin(0.02 * np.pi * x)  # 正弦信号

a = np.linspace(-2, 2, 25)
s2 = np.array([a, a, a, a, a, a, a, a]).reshape(200, )  # 锯齿信号
s3 = np.array(20 * (5 * [2] + 5 * [-2]))  # 方波信号
s4 = 4 * (np.random.random([1, C]) - 0.5).reshape(200, ) #随机信号
"""画出4种信号"""
ax1 = plt.subplot(411)
ax2 = plt.subplot(412)
ax3 = plt.subplot(413)
ax4 = plt.subplot(414)
ax1.plot(x,s1)
ax2.plot(x,s2)
ax3.plot(x,s3)
ax4.plot(x,s4)
plt.show()
"""将4种信号混合
其中mix矩阵是混合后的信号矩阵,shape=[4,200]"""
s=np.array([s1,s2,s3,s4])
ran=2*np.random.random([4,4])
mix=ran.dot(s)
ax1 = plt.subplot(411)
ax2 = plt.subplot(412)
ax3 = plt.subplot(413)
ax4 = plt.subplot(414)
ax1.plot(x,mix[0,:])
ax2.plot(x,mix[1,:])
ax3.plot(x,mix[2,:])
ax4.plot(x,mix[3,:])
plt.show()

ica = FastICA(n_components=4) #独立成分为4个
mix = mix.T #将信号矩阵转为[n_samples,n_features],即[200,4]
u = ica.fit_transform(mix) # u为解混后的4个独立成分,shape=[200,4]
u = u.T # shape=[4,200]
print(ica.n_iter_) # 算法迭代次数
"""画出解混后的4种独立成分"""
ax1 = plt.subplot(411)
ax2 = plt.subplot(412)
ax3 = plt.subplot(413)
ax4 = plt.subplot(414)
ax1.plot(x,u[0,:])
ax2.plot(x,u[1,:])
ax3.plot(x,u[2,:])
ax4.plot(x,u[3,:])
plt.show()

还有另外一种得到独立成分的写法,思路是将求得的解混矩阵和混合信号矩阵相乘得到独立成分,代码如下:

"""前面一样"""
ica = FastICA(n_components=4)
mix = mix.T
ica.fit(mix)
w = ica.components_ #解混矩阵,shape=[n_components, n_features],即[4,4]
u = np.dot(w,mix.T) #解混矩阵和混合信号相乘得到独立成分
print(ica.n_iter_)
ax1 = plt.subplot(411)
ax2 = plt.subplot(412)
ax3 = plt.subplot(413)
ax4 = plt.subplot(414)
ax1.plot(x,u[0,:])
ax2.plot(x,u[1,:])
ax3.plot(x,u[2,:])
ax4.plot(x,u[3,:])
plt.show()

 

 

  • 3
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值