import numpy as np import pickle import math f = open(r'C:\Users\sdnugeo\Desktop\target2.pkl','rb') bi = pickle.load(f) # bi = np.array(bi) data = np.arange(0, 156) print(data) data = data.tolist() # print(data) # 每次抽取1000个数值,共抽取10次 samples = [] c = [] a = 11 r = math.ceil(len(data)/a) print(r) for i in range(a): if len(data) > r : sample = np.random.choice(data, r, replace=False) else: sample = np.random.choice(data, len(data), replace=False) # for s in sample: # data.remove(s) # continue # print(type(sample)) # sample2 = np.array(sample) b = [bi[j] for j in list(sample)] # d = np.array(b) print(type(b)) c.append(b) # c = np.concatenate(c, axis=0) # c = bi[0] print(sample) # print(b) samples.append(sample) for s in sample: data.remove(s) # sample = [s for s in sample if s in data] samples = [np.array(s) for s in samples] samples = np.concatenate(samples, axis=0) c = [np.array(e) for e in c] c = np.concatenate(c, axis=0) # samples = np.array(samples).reshape(-1) print(samples) print(c.shape) 请帮我把这段代码修改成可调用的函数
时间: 2024-03-16 11:46:58 浏览: 150
好的,你想要将这段代码封装成一个函数,可以尝试以下的实现:
```python
import numpy as np
import pickle
import math
def sample_data(filepath):
f = open(filepath, 'rb')
bi = pickle.load(f)
data = np.arange(0, 156)
data = data.tolist()
samples = []
c = []
a = 11
r = math.ceil(len(data)/a)
for i in range(a):
if len(data) > r:
sample = np.random.choice(data, r, replace=False)
else:
sample = np.random.choice(data, len(data), replace=False)
b = [bi[j] for j in list(sample)]
c.append(b)
samples.append(sample)
for s in sample:
data.remove(s)
samples = [np.array(s) for s in samples]
samples = np.concatenate(samples, axis=0)
c = [np.array(e) for e in c]
c = np.concatenate(c, axis=0)
return samples, c
```
你可以将这个函数保存在一个.py文件中,然后在其他的python文件中,通过import导入并调用该函数。调用方法如下:
```python
from your_module import sample_data
filepath = r'C:\Users\sdnugeo\Desktop\target2.pkl'
samples, c = sample_data(filepath)
```
其中,filepath是你想要读取的pickle文件的路径。函数返回两个变量,分别为samples和c。
阅读全文