TypeError:类型'generator'的对象没有len()Python random.shuffle(param)错误

问题描述 投票:0回答:2
 import random

 import math

 import time

 import csv

 class AIRS:

   """AIRS (Artificial Immune Recognition System) class
 Main class for this algorithm

Params:
    hyper_clonal_rate (float) : Define the number of clones an ARB is allowed to produce

    clonal_rate (float) : Define the number of ressources an ARB can obtain

    class_number (int) : The number of classes (3 in this case)
    mc_init_rate (float) : Define the number of training data to be copied in memory cells

    total_num_resources (float) : The total numbers of resources to share between ARBs

    affinity_threshold_scalar  (float) : Give a cut-off value for cell replacement

     k (int) : The number of memory cells to use for classification

      test_size (float) : The percentage of global data to take as test data
"""

def __init__(self, hyper_clonal_rate, clonal_rate, class_number, mc_init_rate,
             total_num_resources, affinity_threshold_scalar, k, test_size):

    self.HYPER_CLONAL_RATE = hyper_clonal_rate

    self.CLONAL_RATE = clonal_rate

    self.AFFINITY_THRESHOLD = 0

    self.CLASS_NUMBER = class_number

    self.MC_INIT_RATE = mc_init_rate

    self.TOTAL_NUM_RESOURCES = total_num_resources

    self.AFFINITY_THRESHOLD_SCALAR = affinity_threshold_scalar

    self.TEST_SIZE = test_size

    self.K = k

    self.MC = None

    self.AB = None

@staticmethod
def affinity(vector1, vector2):
    """Compute the affinity (Normalized !! distance) between two features vectors
    :param vector1: First features vector
    :param vector2: Second features vector
    :return: The affinity between the two vectors [0-1]
    """

    d = 0
    for i, j in zip(vector1, vector2):
        d += (i - j) ** 2
    euclidian_distance = math.sqrt(d)
    return euclidian_distance / (1 + euclidian_distance)

def train_test_split(self):
    with open("/Users/user_name/Downloads/iris.data", "r") as data:
        content = data.readlines()
        ret = (((float(x.split[","][i]) for i in range(4)), mapping(x.split[","][4][:-1])) for x in content)
        random.seed()
        random.shuffle(ret)
    return ret[:int((1 - self.TEST_SIZE) * len(ret))], ret[int((1 - self.TEST_SIZE) * len(ret)):]

运行这些代码时,出现这样的错误

  File "/Users/user_name/.spyder-py3/AIRS.py", line 67, in train_test_split
    random.shuffle(ret)

  File "/Users/user_name/anaconda3/lib/python3.7/random.py", line 275, in shuffle
    for i in reversed(range(1, len(x))):

TypeError: object of type 'generator' has no len()

有人可以帮我吗?因为我不明白该怎么办。

**注意:**我从https://github.com/AghilesAzzoug/Artificial-Immune-System/blob/master/main.py中克隆了这些代码>

导入随机导入数学导入时间导入csv类AIRS:“”“ AIRS(人工免疫识别系统)类此算法的主要类参数:hyper_clonal_rate(浮点数:...

python python-3.7 shuffle
2个回答
1
投票

range的工作多年来已经改变。它最初返回一个list,现在返回一个生成器。只需将生成器变成一个列表即可。


0
投票

我编辑了代码,但现在出现了另一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.