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) 请帮我把这段代码修改成可调用的函数,要求可以调用每一个b
时间: 2024-03-16 10:47:01 浏览: 72
好的,可以将这段代码封装成一个函数,并返回每次抽样的b值,代码如下:
```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 = []
bs = []
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)]
bs.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)
bs = [np.array(e) for e in bs]
bs = np.concatenate(bs, axis=0)
return samples, bs
```
你可以将这个函数保存在一个.py文件中,然后在其他的python文件中,通过import导入并调用该函数。调用方法如下:
```python
from your_module import sample_data
filepath = r'C:\Users\sdnugeo\Desktop\target2.pkl'
samples, bs = sample_data(filepath)
# 获取第i次抽样的b值
i = 0 # 假设想要获取第1次抽样的b值
b_i = bs[i*r:(i+1)*r]
```
其中,filepath是你想要读取的pickle文件的路径。函数返回两个变量,分别为samples和bs,bs是每次抽样的b值所组成的数组。你可以通过bs[i*r:(i+1)*r]获取第i次抽样的b值。
阅读全文