[英]Why does this inline loop not work in python?
我试图将我的数据集以 80:20 的比例拆分为训练和测试。 我的产品有不同的等级,每个等级文件夹都有一堆文件。 最终结果应该有两个文件夹Training和Testing,每个文件夹都将所有成绩作为子文件夹和相应数量的文件。
我想了解为什么最后一个 while 循环不起作用。
# Split Data set into testing and training
train_ratio = 80
test_ratio = 20
# For each grade , determine no of training and testing images.
for grade_type in GRADES:
grade_folder_path = os.path.join(prep_folder, grade_type)
img_count_grade_folder = len(os.listdir(grade_folder_path))
train_count: int = round(img_count_grade_folder * train_ratio / 100)
test_count : int = img_count_grade_folder - train_count
print(grade_type, "Total images :", img_count_grade_folder, "Train Images: ", train_count, "Test images: ",
test_count)
# Create Train and Test folders.
train_grade_type = os.path.join(prep_folder, "Train", "", grade_type, "")
os.makedirs(train_grade_type, exist_ok=True)
test_grade_type = os.path.join(prep_folder, "Test", "", grade_type, "")
os.makedirs(test_grade_type, exist_ok=True)
# Copy Data to Train and Test folders.
b : int = 0
while b < train_count:
print(b)
images = os.listdir(grade_folder_path)
src_img = images[b]
src_img_path = os.path.join(grade_folder_path, src_img)
train_target = os.path.join(train_grade_type)
train_target_img = os.path.join(train_target, src_img)
print("train_", src_img_path, train_target)
# b = b+1
if os.path.isfile(train_target_img):
print("skipping", src_img)
else:
try:
shutil.copy(src_img_path, train_target)
except:
print("error copying to train target", train_target)
else:
print(src_img, "Copy successful !")
b = b + 1
print("next", b)
if b >= train_count:
continue
c : int = train_count
while c < test_count:
print(c)
images = os.listdir(grade_folder_path)
src_img = images[c]
src_img_path = os.path.join(grade_folder_path, src_img)
test_target = os.path.join(test_grade_type)
test_target_img = os.path.join(test_target, src_img)
print("Test_", src_img_path, test_target)
# c = c+1
if os.path.isfile(test_target_img):
print("skipping", src_img)
else:
try:
shutil.copy(src_img_path, test_target)
except:
print("error copying to test target", test_target)
else:
print(src_img, "Copy successful !")
c = c + 1
print("next", c)
if c == test_count:
break
因为train_count
大于test_count
,并且 c 的初始值是: c : int = train_count
那么它不满足 while 循环条件。 这就是 while 循环不起作用的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.