Python | Matlab | 功能 |
---|---|---|
str2 = str1.replace(old,new[,count]) |
dstStr= strrep(origStr,oldSubstr,newSubStr) filepath = 'E:/data/1.jpg'; filepath2 = strrep(filepath,'data','lfw/data'); disp(filepath2); |
替换子串 |
随机打乱:
Matlabs:
nsample = 10;
if ~exist('rand_ind.mat','file')
rand_ind = randperm(nsample);
save('rand_ind.mat','rand_ind');
else
load('rand_ind.mat');% load rand_ind
disp('load successfully!')
end
disp(rand_ind);
Python:
import random
import os
import numpy as np
rand_ind = range(10)
if not os.path.exists('rand_ind.npy'):
random.shuffle(rand_ind) # 操作该对象本身
np.save('rand_ind.npy',rand_ind)
else:
rand_ind = np.load('rand_ind.npy')
print 'load successfully!'
print rand_ind
在进行实验的时候,我们经常希望对数据集进行随机的打乱,但是又希望这种随机打乱的结果具有可重现性。下面给出matlab和python的实现方法:
Matlab:
nsample = 10;
feat_len = 1000;
train_data = rand(nsample,feat_len);%随机生成一个样本矩阵,含有10个样本,特征维数为1000
if ~exist('rand_ind.mat','file')
rand_ind = randperm(nsample);
save('rand_ind.mat','rand_ind');
else
load('rand_ind.mat');% load rand_ind
disp('load successfully!')
end
% 将样本按照生成的随机序列打乱
train_data = train_data(rand_ind,:);
disp(rand_ind);
Python:
import random
import os
import numpy as np
nsample = 10
feat_len = 1000
train_data = np.random.random((nsample,feat_len))
print train_data.shape
rand_ind = range(nsample)
if not os.path.exists('rand_ind.npy'):
random.shuffle(rand_ind) # 操作该对象本身
np.save('rand_ind.npy',rand_ind)
else:
rand_ind = np.load('rand_ind.npy')
print 'load successfully!'
print rand_ind
train_data2 = np.zeros(train_data.shape,dtype=train_data.dtype)
print train_data2.shape
print rand_ind[1]
for i in xrange(len(rand_ind)):
train_data2[i,:] = train_data[rand_ind[i],:]
对于list的话,可以使用列表推导式,如;
mylist = ['a','b','c','d','e']
myorder = [3,2,0,1,4]
mylist =[mylist[i] for i in myorder]
print mylist