本文整理汇总了Python中sklearn.decomposition.FastICA.inverse_transform方法的典型用法代码示例。如果您正苦于以下问题:Python FastICA.inverse_transform方法的具体用法?Python FastICA.inverse_transform怎么用?Python FastICA.inverse_transform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.decomposition.FastICA
的用法示例。
在下文中一共展示了FastICA.inverse_transform方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_inverse_transform
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
def test_inverse_transform():
"""Test FastICA.inverse_transform"""
rng = np.random.RandomState(0)
X = rng.random_sample((100, 10))
rng = np.random.RandomState(0)
X = rng.random_sample((100, 10))
n_features = X.shape[1]
expected = {(True, 5): (n_features, 5),
(True, 10): (n_features, 10),
(False, 5): (n_features, 10),
(False, 10): (n_features, 10)}
for whiten in [True, False]:
for n_components in [5, 10]:
ica = FastICA(n_components=n_components, random_state=rng,
whiten=whiten)
Xt = ica.fit_transform(X)
expected_shape = expected[(whiten, n_components)]
assert_equal(ica.mixing_.shape, expected_shape)
X2 = ica.inverse_transform(Xt)
assert_equal(X.shape, X2.shape)
# reversibility test in non-reduction case
if n_components == X.shape[1]:
assert_array_almost_equal(X, X2)
示例2: test_inverse_transform
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
def test_inverse_transform():
# Test FastICA.inverse_transform
n_features = 10
n_samples = 100
n1, n2 = 5, 10
rng = np.random.RandomState(0)
X = rng.random_sample((n_samples, n_features))
expected = {(True, n1): (n_features, n1),
(True, n2): (n_features, n2),
(False, n1): (n_features, n2),
(False, n2): (n_features, n2)}
for whiten in [True, False]:
for n_components in [n1, n2]:
n_components_ = (n_components if n_components is not None else
X.shape[1])
ica = FastICA(n_components=n_components, random_state=rng,
whiten=whiten)
with warnings.catch_warnings(record=True):
# catch "n_components ignored" warning
Xt = ica.fit_transform(X)
expected_shape = expected[(whiten, n_components_)]
assert_equal(ica.mixing_.shape, expected_shape)
X2 = ica.inverse_transform(Xt)
assert_equal(X.shape, X2.shape)
# reversibility test in non-reduction case
if n_components == X.shape[1]:
assert_array_almost_equal(X, X2)
示例3: ICA
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
class ICA(method.Method):
def __init__(self, params):
self.params = params
self.ica = FastICA(**params)
def __str__(self):
return "FastICA"
def train(self, data):
"""
Train the FastICA on the withened data
:param data: whitened data, ready to use
"""
self.ica.fit(data)
def encode(self, data):
"""
Encodes the ready to use data
:returns: encoded data with dimension n_components
"""
return self.ica.transform(data)
def decode(self, components):
"""
Decode the data to return whitened reconstructed data
:returns: reconstructed data
"""
return self.ica.inverse_transform(components)
示例4: var_test_ica
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
def var_test_ica(flux_arr_orig, exposure_list, wavelengths, low_n=3, hi_n=100, n_step=1, show_plots=False,
show_summary_plot=False, save_summary_plot=True, test_ind=7, real_time_progress=False,
idstr=None):
start_ind = np.min(np.nonzero(flux_arr_orig[test_ind]))
end_ind = np.max(np.nonzero(flux_arr_orig[test_ind]))
perf_table = Table(names=["n", "avg_diff2", "max_diff_scaled"], dtype=["i4", "f4", "f4"])
if hi_n > flux_arr_orig.shape[0]-1:
hi_n = flux_arr_orig.shape[0]-1
for n in range(low_n, hi_n, n_step):
ica = FastICA(n_components = n, whiten=True, max_iter=750, random_state=1234975)
test_arr = flux_arr_orig[test_ind].copy()
flux_arr = np.vstack([flux_arr_orig[:test_ind], flux_arr_orig[test_ind+1:]])
ica_flux_arr = flux_arr.copy() #keep back one for testing
ica.fit(ica_flux_arr)
ica_trans = ica.transform(test_arr.copy(), copy=True)
ica_rev = ica.inverse_transform(ica_trans.copy(), copy=True)
avg_diff2 = np.ma.sum(np.ma.power(test_arr-ica_rev[0],2)) / (end_ind-start_ind)
max_diff_scaled = np.ma.max(np.ma.abs(test_arr-ica_rev[0])) / (end_ind-start_ind)
perf_table.add_row([n, avg_diff2, max_diff_scaled])
if real_time_progress:
print "n: {:4d}, avg (diff^2): {:0.5f}, scaled (max diff): {:0.5f}".format(n, avg_diff2, max_diff_scaled)
if show_plots:
plt.plot(wavelengths, test_arr)
plt.plot(wavelengths, ica_rev[0])
plt.plot(wavelengths, test_arr-ica_rev[0])
plt.legend(['orig', 'ica', 'orig-ica'])
plt.xlim((wavelengths[start_ind], wavelengths[end_ind]))
plt.title("n={}, avg (diff^2)={}".format(n, avg_diff2))
plt.tight_layout()
plt.show()
plt.close()
if show_summary_plot or save_summary_plot:
plt.plot(perf_table['n'], perf_table['avg_diff2'])
plt.plot(perf_table['n'], perf_table['max_diff_scaled'])
plt.title("performance")
plt.tight_layout()
if show_summary_plot:
plt.show()
if save_summary_plot:
if idstr is None:
idstr = random.randint(1000000, 9999999)
plt.savefig("ica_performance_{}.png".format(idstr))
plt.close()
return perf_table
示例5: ica
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
def ica(input_matrix: np.array, inverse: bool=False):
"""
Performs ICA on an input in
order to reduce dimensionality.
"""
trials, channels, samples = np.shape(input_matrix)
ica = FastICA(n_components=None)
transform = ica.fit_transform(np.vstack(input_matrix))
transform = np.reshape(transform, (-1, channels, samples))
covariance = np.corrcoef(np.mean(transform, axis=0))
high, low = _correlate(covariance)
stacked = np.vstack(transform[:, low, :])
if inverse:
stacked = ica.inverse_transform(stacked)
return np.reshape(inverse, (trials, -1, samples))
示例6: range
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
sp1.plot(t,signal2)
plt.show()
cpath='/home/bejar/MEG/Data/control/'
cres='/home/bejar/Documentos/Investigacion/MEG/res/'
#name='MMN-201205251030'
name='control1-MEG'
mats=scipy.io.loadmat( cpath+name+'.mat')
data= mats['data']
chann=mats['names']
samplerate=500
length=5000
chann=120
width=25
dbuffer=data[[149,43,48,27,29,109,128],5000:10000]
fica=FastICA(n_components=6,algorithm='deflation',fun='exp',max_iter=1000)
res=fica.fit_transform(dbuffer.transpose())
#for i in range(res.shape[1]):
# plotOneSignal(res[:,i])
plotOneSignal(res[:,0])
res[:,0]=0
inv=fica.inverse_transform(res)
plotTwoSignal(data[149,5000:10000],inv[:,0])
示例7: ICA
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
class ICA(object):
"""
Wrapper for sklearn package. Performs fast ICA (Independent Component Analysis)
ICA has 4 methods:
- fit(waveforms)
update class instance with ICA fit
- fit_transform()
do what fit() does, but additionally return the projection onto ICA space
- inverse_transform(A)
inverses the decomposition, returns waveforms for an input A, using Z
- get_params()
returns metadata used for fits.
"""
def __init__(self, num_components=10,
catalog_name='unknown',
whiten=True,
fun = 'logcosh',
fun_args = None,
max_iter = 600,
tol = .00001,
w_init = None,
random_state = None,
algorithm = 'parallel'):
self._decomposition = 'Fast ICA'
self._num_components = num_components
self._catalog_name = catalog_name
self._whiten = whiten
self._fun = fun
self._fun_args = fun_args
self._max_iter = max_iter
self._tol = tol
self._w_init = w_init
self._random_state = random_state
self._algorithm = algorithm
self._ICA = FastICA(n_components=self._num_components,
whiten = self._whiten,
fun = self._fun,
fun_args = self._fun_args,
max_iter = self._max_iter,
tol = self._tol,
w_init = self._w_init,
random_state = self._random_state,
algorithm = self._algorithm)
def fit(self,waveforms):
# TODO make sure there are more columns than rows (transpose if not)
# normalize waveforms
self._waveforms = waveforms
self._ICA.fit(self._waveforms)
def fit_transform(self,waveforms):
# TODO make sure there are more columns than rows (transpose if not)
# normalize waveforms
self._waveforms = waveforms
self._A = self._ICA.fit_transform(self._waveforms)
return self._A
def inverse_transform(self,A):
# convert basis back to waveforms using fit
new_waveforms = self._ICA.inverse_transform(A)
return new_waveforms
def get_params(self):
# TODO know what catalog was used! (include waveform metadata)
params = self._ICA.get_params()
params['num_components'] = params.pop('n_components')
params['Decompositon'] = self._decomposition
return params
def get_basis(self):
""" Return the ICA basis vectors (Z^\dagger)"""
return self._ICA.get_mixing_matrix()
示例8: ica
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
def ica(self):
fica = FastICA()
utility_normal_fica = fica.fit_transform(self.ds.utility_normal)
self.utility_normal_back = fica.inverse_transform(utility_normal_fica)
示例9: __init__
# 需要导入模块: from sklearn.decomposition import FastICA [as 别名]
# 或者: from sklearn.decomposition.FastICA import inverse_transform [as 别名]
#.........这里部分代码省略.........
## Right average potential ##
rightChannels = channelPositions[:,rightBorder:]
rightChannels = [list(y for y in x if y) for x in rightChannels]
sumRight = 0
sumChanRight = 0
for m in range(len(rightChannels)):
for n in rightChannels[m]:
sumRight+=abs(component[n-1])
sumChanRight+=1
averageRight = sumRight/sumChanRight
ratioSum = (averageFront+averageRight+averageLeft)/averageCenter
ratioFrontalBack = (averageFront+averageCenter)/(averageLeft+averageRight)
toUse = 0
### heuristiky na základe priestorového rozloženia
if self.chanNum == 64:
if int(ratioSum) == 1:
toUse = 1
if ratioFrontalBack > 1 and ratioFrontalBack < 3 and not (averageFront/averageCenter > 2):
toUse = 1
if ratioSum < 1:
toUse = 1
else:
totalAverage = abs(component.mean())
maxChan = abs(max(component.min(), component.max(), key=abs))
if totalAverage*3 > maxChan and ratioSum < 5:
toUse = 1
if averageCenter > averageFront and averageCenter > averageRight and averageCenter > averageLeft and ratioSum < 5:
toUse = 1
if ratioSum < 2:
toUse = 1
if toUse == 0:
toRejectFound.append(i+1)
print "IC"+str(i+1)+"\t Front:"+str(int(averageFront))+"\t Center:"+str(int(averageCenter))\
+"\t Right:"+str(int(averageRight))+"\t Left:"+str(int(averageLeft))+"\t Ratio:"+str(ratioSum)
else:
print "USED: IC"+str(i+1)+"\t Front:"+str(int(averageFront))+"\t Center:"+str(int(averageCenter))\
+"\t Right:"+str(int(averageRight))+"\t Left:"+str(int(averageLeft))+"\t Ratio:"+str(ratioSum)
#### Zobrazenie komponentov (Heatmapa, časový rad, ) ######
# visualizer = Visualizer()
# visualizer.plotComponents(self.ica,channelPositions,components)
#################### Odstránenie nežiadúcich komponentov z mixovacej matice ##################
compNums = toRejectFound
compNums.sort(reverse=True)
### Výber komponentov ručne
# rejected = raw_input("Enter numbers of rejected components")
# compNums = rejected.split()
# for m in range (len(compNums)):
# compNums[m] = int(compNums[m])
# compNums.sort(reverse=True)
for i in compNums:
self.ica.mixing_[:,i-1] = 0
reconstructed = self.ica.inverse_transform(components)
### Zobrazenie grafu filtrovaného signálu ###
# visualizer.plotSignalRepairing(signal,reconstructed)
return reconstructed.T
# spriemerovany char list pre jeden cielovy typ vysvietenia, vystupom je single element z povodnych N elektrod
# mode = 0 - reduce, z 64 elektrod zober len tie z najdeneho subsetu
# mode = 1 - guess, zober vsetky elektrody, signal co si dostal uz je len zo subsetu
def grandAveragingFilter (self,isiBinList,subset,mode, isiCount = 12):
chl = [IsiBin() for i in range(isiCount)]
chl = isiBinList
output = []
for i in range(len(chl)):
#print "Grand averaging letter:",i,"\n"
charChannList = chl[i]
epoch = []
for m in range(len(charChannList.channelsSignalsAveraged[0])):
tmp = []
if mode == 0:
for l in subset:
tmp.append(charChannList.channelsSignalsAveraged[l][m])
else:
for l in range (len(charChannList.channelsSignalsAveraged)):
tmp.append(charChannList.channelsSignalsAveraged[l][m])
epoch.append(np.mean(tmp))
output.append(epoch)
return output