AttributeError: ‘builtin_function_or_method‘ object has no attribute ‘shuffle‘

今天在复现深度学习的代码的时候,遇到了一个问题,百思不得其解:

Traceback (most recent call last):
  File "d:\Code Project\15.动手学深度学习代码手撸\线性回归.py", line 34, in <module>
    for X, y in data_iter(batch_size, features, labels):
  File "d:\Code Project\15.动手学深度学习代码手撸\线性回归.py", line 21, in data_iter
    random.shuffle(indices)
AttributeError: 'builtin_function_or_method' object has no attribute 'shuffle'

没有找到shuffle模块!

我们回头看一下源代码:

import math
from random import random
import time
import numpy as np
import torch
from d2l import torch as d2l
import matplotlib.pyplot as plt
from matplotlib_inline import backend_inline


def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    # 这些样本是随机读取的,没有特定的顺序
    random.shuffle(indices)
    for i in range(0, num_examples, batch_size):
        batch_indices = torch.tensor(indices[i : min(i + batch_size, num_examples)])
        yield features[batch_indices], labels[batch_indices]

这里我们可以看出来,错误的原因是调包调错了,应该把from random import random改为import random

改正后的结果如下:

tensor([[ 0.7425,  0.1878],
        [ 0.0685, -2.4066],
        [-0.6766,  1.4171],
        [ 1.1995, -1.2895],
        [ 0.9222,  2.1167],
        [ 1.4341, -2.5776],
        [ 0.1866,  0.3323],
        [-1.3769,  1.3391],
        [ 0.6745,  0.6171],
        [ 0.9577,  0.7001]]) 
 tensor([[ 5.0335],
        [12.5133],
        [-1.9797],
        [10.9888],
        [-1.1390],
        [15.8354],
        [ 3.4411],
        [-3.1252],
        [ 3.4511],
        [ 3.7230]])

问题得到顺利解决!

你可能感兴趣的:(错误或者警告类型解决办法总结,深度学习,python,人工智能)