为了账号安全,请及时绑定邮箱和手机立即绑定

如何在大型文本文件中查找特定元素的平均值

如何在大型文本文件中查找特定元素的平均值

慕尼黑的夜晚无繁华 2021-10-26 15:52:03
我正在尝试实现以下预期输出部分中的说明。文本文件每行包含 5 个浮点数,最后一个没有用,因为它只是对前面的数字表示它是真钞还是假钞票进行分类(0 是假的,1 是真的)。我想创建一个循环,它可以取每行的第一个数字(有 600 多行)并找到平均值,与每行的第二个数字、第三个和第四个数字相同。输出应该是一个列表,显示每个平均值 [avg1 avg2 avg3 avg4]。下面的代码可以成功执行此操作,但一次只能执行一个。例如。在这行 sum += float(line.split()[0]) 中,将 0 更改为 1 将给出每行中第二个数字的平均值,依此类推。我如何创建一个有效的循环来一次给我所有的平均值?我已经尝试复制循环并为每个数字“列”粘贴 4 次,但它效率低下且不起作用。import web_scraperimport urllib.requestimport mathdef data_text_files():page = 'http://archive.ics.uci.edu/ml/machine-learning- databases/00267/data_banknote_authentication.txt'stream = urllib.request.urlopen(page)samples = web_scraper.get_all_data(stream, ',')training = open("training2.txt", "w")testing = open ("testing2.txt", "w")for i in range(len(samples)):    if i % 2 == 0:        #write data to training file        count = 1        for bill in samples[i]:            bill_str = str(bill)            if(count == 5):                training.write(bill_str + "\n")                count = 1            else:                training.write(bill_str + " ")                count += 1    else:        #write data to testing file        count = 1        for bill in samples[i]:            bill_str = str(bill)            if(count == 5):                testing.write(bill_str + "\n")                count = 1            else:                testing.write(bill_str + " ")                count += 1data_text_files()with open('training2.txt') as fh:    sum = 0  # initialize here, outside the loop    count = 0  # and a line counter    for line in fh:        count += 1  # increment the counter        sum += float(line.split()[0])  # add here, not in a nested loop每个数据样本有4个属性(不包括最后一个表示样本分类的属性)。所以,数据看起来像这样:  [ [2, 4, 6, 8, 0],    [4, 6, 8, 10,  0],    [1, 3, 5, 7, 1]    [3, 5, 7, 9,  1]]要构建分类器,您将使用“training.txt”中的数据:计算具有相同分类(0 或 1)的所有样本的每个属性的平均值。对于上面显示的数据,伪造样本 (0) 中每个属性的平均值为 [3, 5, 7, 9],而真实样本 (1) 的平均值为 [2, 4, 6, 8]。通过将伪造品的平均值和真实样品的平均值相加,找出两组平均值之间的中点,然后将结果除以二。这将为每个属性完成。因此,对于显示的数据,中点将是 [2.5, 4.5, 6.5, 8.5 ]。中点是我们将用作分类器的东西。
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

您不需要安装的库,例如pandas,尽管它们确实具有易于使用的函数来计算表的平均值。


您的代码计算单个总和并计算行数,然后从中计算单个平均值。您想在同一个循环中计算所有四个平均值。通过一次性阅读整个文件,您可以更轻松地做到这一点,但我会坚持您的方法,因为这对于超大文件很重要:


with open('training2.txt') as fh:

    n = 4  # number of fields we're interested in

    sums = [0] * n  # initialize here, outside the loop

    count = 0  # and a line counter

    for line in fh:

        count += 1  # increment the counter

        fields = line.split()  # split the line outside the loop, only once

        for i in range(n):

            sums[i] += float(fields[i])  # add here, not in a nested loop


    averages = [s / count for s in sums]  # not using the name sum, as it is a built-in


    print(averages)

这是假设您的代码有效并且您的文本文件实际上具有由空格分隔的值,否则您需要类似的东西 .split(',')


查看完整回答
反对 回复 2021-10-26
  • 2 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信