#划分数据集 m=1 while True: if m==0: break m=0 #random_split()函数说明:这个函数的作用是划分数据集 train_dataset,test_dataset=random_split(dataset=data_set,lengths=[8200,2049]) #将数据集分为5份,其中训练集--4,测试集---1 a=np.zeros(16) b=np.zeros(16) for i in range(8200): if i<8200: a[int(train_dataset[i][1])]+=1 if i<2049: b[int(test_dataset[i][1])]+=1 for p in range(16): if a[p]/b[p]>5 or a[p]/b[p]<3: m=1 break for p in range(16): print( "第 {:^4} 个标签 标签数{:4} 训练集{:4} 测试集{:4} {:6.2f}".format(p,int(a[p]+b[p]),int(a[p]),int(b[p]), a[p]/b[p]))
时间: 2024-04-26 07:23:02 浏览: 5
这段代码的作用是将一个数据集随机分成训练集和测试集,并检查每个标签在训练集和测试集的分布是否合理。其中,数据集共有16个标签,分别用0-15表示。如果某个标签在训练集和测试集的数量比例大于5或小于3,则认为分布不合理,需要重新随机划分数据集。最后,代码会输出每个标签在整个数据集、训练集和测试集中的数量以及训练集和测试集中该标签的比例。
相关问题
降低这段代码重复率:def crossSol(model): sol_list=copy.deepcopy(model.sol_list) model.sol_list=[] while True: f1_index = random.randint(0, len(sol_list) - 1) f2_index = random.randint(0, len(sol_list) - 1) if f1_index!=f2_index: f1 = copy.deepcopy(sol_list[f1_index]) f2 = copy.deepcopy(sol_list[f2_index]) if random.random() <= model.pc: cro1_index=int(random.randint(0,len(model.demand_id_list)-1)) cro2_index=int(random.randint(cro1_index,len(model.demand_id_list)-1)) new_c1_f = [] new_c1_m=f1.node_id_list[cro1_index:cro2_index+1] new_c1_b = [] new_c2_f = [] new_c2_m=f2.node_id_list[cro1_index:cro2_index+1] new_c2_b = [] for index in range(len(model.demand_id_list)): if len(new_c1_f)<cro1_index: if f2.node_id_list[index] not in new_c1_m: new_c1_f.append(f2.node_id_list[index]) else: if f2.node_id_list[index] not in new_c1_m: new_c1_b.append(f2.node_id_list[index]) for index in range(len(model.demand_id_list)): if len(new_c2_f)<cro1_index: if f1.node_id_list[index] not in new_c2_m: new_c2_f.append(f1.node_id_list[index]) else: if f1.node_id_list[index] not in new_c2_m: new_c2_b.append(f1.node_id_list[index]) new_c1=copy.deepcopy(new_c1_f) new_c1.extend(new_c1_m) new_c1.extend(new_c1_b) f1.nodes_seq=new_c1 new_c2=copy.deepcopy(new_c2_f) new_c2.extend(new_c2_m) new_c2.extend(new_c2_b) f2.nodes_seq=new_c2 model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) else: model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) if len(model.sol_list)>model.popsize: break
可以将其中的重复代码提取出来,写成一个函数,然后在需要使用的地方调用即可。比如,可以将以下部分提取出来:
```
for index in range(len(model.demand_id_list)):
if len(new_c1_f)<cro1_index:
if f2.node_id_list[index] not in new_c1_m:
new_c1_f.append(f2.node_id_list[index])
else:
if f2.node_id_list[index] not in new_c1_m:
new_c1_b.append(f2.node_id_list[index])
```
写成一个名为 `split_list` 的函数,如下所示:
```
def split_list(demand_id_list, node_id_list, split_start, split_end):
new_c1_f = []
new_c1_m = node_id_list[split_start:split_end+1]
new_c1_b = []
for index in range(len(demand_id_list)):
if len(new_c1_f)<split_start:
if node_id_list[index] not in new_c1_m:
new_c1_f.append(node_id_list[index])
else:
if node_id_list[index] not in new_c1_m:
new_c1_b.append(node_id_list[index])
return new_c1_f + new_c1_m + new_c1_b
```
然后在需要使用的地方调用 `split_list` 函数即可,如下所示:
```
new_c1 = split_list(model.demand_id_list, f2.node_id_list, cro1_index, cro2_index)
new_c2 = split_list(model.demand_id_list, f1.node_id_list, cro1_index, cro2_index)
```
这样可以大大降低代码的重复率,让代码更加简洁易懂。
#随机抽奖 import random x=open("chojiang.txt","r",encoding="UTF-8") #x是文件对象 y=x.read() shulist=y.split('\n')#把字符串y里面的字符串分割为多个放在列表 shulist = list(set(shulist)) # 去重 print("开始抽奖") while True: if not shulist: shulist.remove(random.choice(shulist)) break print("本次抽奖结果为:", random.choice(shulist)) shulist.remove(random.choice(shulist)) # 抽到过的不会再被点到 print(shulist) a = input("是否继续抽奖[1续/0结束]: ") while a not in ['0', '1']: a = input("请输入正确选项[0或1]: ") if a == '0': break
这段代码主要是实现了一个简单的抽奖功能,但是可以进行一些优化和完善。以下是一些可能的改进:
1. 在抽奖前对输入的文件路径进行检查,以避免出现文件不存在等异常情况。
2. 在打开文件时,可以使用 with 语句来确保文件对象被正确关闭,避免文件泄漏等问题。
3. 可以将文件读取和去重的操作封装成函数,以提高代码的可读性和复用性。
4. 可以添加一些异常处理机制,以避免出现不可预知的错误。
5. 可以增加一些用户交互界面,如输入抽奖人数、奖项等,以使程序更加灵活。
6. 可以将抽奖结果写入文件,以便后续查看。
下面是一个可能的改进版本的代码:
```python
import os
import random
def read_file(path):
"""
读取文件内容并去重
:param path: 文件路径
:return: 包含不重复字符串的列表
"""
if not os.path.exists(path):
raise FileNotFoundError("文件不存在")
with open(path, "r", encoding="utf-8") as f:
content = f.read()
content = content.strip().split("\n")
return list(set(content))
def draw_lottery(data):
"""
抽奖函数
:param data: 包含抽奖对象的列表
"""
print("开始抽奖")
while True:
if not data:
break
result = random.choice(data)
data.remove(result)
print("本次抽奖结果为:", result)
a = input("是否继续抽奖[1续/0结束]: ")
while a not in ['0', '1']:
a = input("请输入正确选项[0或1]: ")
if a == '0':
break
print("抽奖结束")
if __name__ == "__main__":
path = input("请输入文件路径:")
try:
data = read_file(path)
except FileNotFoundError:
print("文件不存在,请重新输入")
else:
draw_lottery(data)
```