我们怎样才能只从文件的行中读取浮点值?

How can we Read just float values from the lines of a file?

我想逐行读取一个文件,并使用该文件中写入的一些元素作为我的神经网络中的学习率、时期和批量大小来配置它。 我的代码是这样的:

file_config = open("myfile", "r")
lines = myfile.readlines()
for line in lines: 
  print(line)

结果是这样的:

--learning_rate 0.1 --epochs 300 
--learning_rate 0.01 --epochs 300 
--learning_rate 0.1 --epochs 500 
--learning_rate 0.01 --epochs 500

您知道如何将每行中写入的值分配给模型的学习率和周期吗? 事实上,如何从文件的行中检索值?

也许你可以这样使用:

import re
file_config = open("myfile", "r")
lines = myfile.readlines()
for line in lines:
    nums = re.findall(r'\d+\.\d+|\d+', line)
    print(f"learning_rate:{nums[0]} and  epochs:{nums[1]}")

这是结果:

learning_rate:0.1 and  epochs:300
learning_rate:0.01 and  epochs:300
learning_rate:0.1 and  epochs:500
learning_rate:0.01 and  epochs:500

如果文件格式固定,可以通过索引获取学习率和epochs的值。

data.txt:

--learning_rate 0.1 --epochs 300
--learning_rate 0.01 --epochs 300
--learning_rate 0.1 --epochs 500
--learning_rate 0.01 --epochs 500

代码:

def read_lr_epochs(file_path):
    data = []
    with open(file_path) as data_file:
        lines = data_file.readlines()
        for line in lines:
            line = line.strip()
            if line:
                line = line.split(" ")
                data.append([float(line[1]), int(line[3])])
    return data


if __name__ == "__main__":
    print(read_lr_epochs("data.txt"))

输出:

[[0.1, 300], [0.01, 300], [0.1, 500], [0.01, 500]]

然后您可以根据需要访问列表的值。