32412
以下のリンクにあるCIFAR-10(ラベル付されたサイズが32x32のカラー画像8000万枚のデータセット)を読み取り、Nearest Neighbor
Classifierによりクラス分けしその精度を%で出力させたいのですが以下のエラー出てしまいました。問題は58行目のxrangeにあるようですが解決方法がみつからず、何かアドバイス頂けると幸いです。

以下データ元:  
<http://www.cs.toronto.edu/~kriz/cifar.html>

以下コードです:

```

    import pickle
    import numpy as np
    import os
    
    def unpickle(file):
        fo = open(file, 'rb')
        u = pickle._Unpickler(fo)
        u.encoding = 'latin1'
        dict = u.load()
        fo.close()
        return dict
    
    def conv_data2image(data):
        return np.rollaxis(data.reshape((3,32,32)),0,3)
    
    def get_cifar10(folder):
        tr_data = np.empty((0,32*32*3))
        tr_labels = np.empty(1)
        '''
        32x32x3
        '''
        for i in range(1,6):
            fname = os.path.join(folder, "%s%d" % ("data_batch_", i))
            data_dict = unpickle(fname)
            if i == 1:
                tr_data = data_dict['data']
                tr_labels = data_dict['labels']
            else:
                tr_data = np.vstack((tr_data, data_dict['data']))
                tr_labels = np.hstack((tr_labels, data_dict['labels']))
    
        data_dict = unpickle(os.path.join(folder, 'test_batch'))
        te_data = data_dict['data']
        te_labels = np.array(data_dict['labels'])
    
        bm = unpickle(os.path.join(folder, 'batches.meta'))
        label_names = bm['label_names']
        return tr_data, tr_labels, te_data, te_labels, label_names
    
    
    class NearestNeighbor(object):
      def __init__(self):
        pass
    
      def train(self, X, y):
        """ X is N x D where each row is an example. Y is 1-dimension of size N """
        # the nearest neighbor classifier simply remembers all the training data
        self.Xtr = X
        self.ytr = y
    
      def predict(self, X):
        """ X is N x D where each row is an example we wish to predict label for """
        num_test = X.shape[0]
        # lets make sure that the output type matches the input type
        Ypred = np.zeros(num_test, dtype = self.ytr.dtype)
    
        # loop over all test rows
        for i in xrange(num_test):
          # find the nearest training image to the i'th test image
          # using the L1 distance (sum of absolute value differences)
          distances = np.sum(np.abs(self.Xtr - X[i,:]), axis = 1)
          min_index = np.argmin(distances) # get the index with smallest distance
          Ypred[i] = self.ytr[min_index] # predict the label of the nearest example
    
        return Ypred
    
    if __name__ == '__main__':
        datapath = "./data/cifar-10-batches-py"
    
        tr_data10, tr_labels10, te_data10, te_labels10, label_names10 = get_cifar10(datapath)
        Xtr, Ytr, Xte, Yte, label_names10 = get_cifar10(datapath)
        Xtr_rows = Xtr.reshape(Xtr.shape[0], 32 * 32 * 3)
        Xte_rows = Xte.reshape(Xte.shape[0], 32 * 32 * 3)
        nn = NearestNeighbor()  # create a Nearest Neighbor classifier class
        nn.train(Xtr_rows, Ytr)  # train the classifier on the training images and labels
        Yte_predict = nn.predict(Xte_rows)  # predict labels on the test images
        # and now print the classification accuracy, which is the average number
        # of examples that are correctly predicted (i.e. label matches)
        print(Yte_predict)
    
```

以下エラー

> "C:\…\AppData\Local\Programs\Python\Python35\python.exe"  
>  "C:/…/PycharmProjects/Convolutional Neural  
>  Networks for Visual Recognition/input_cifar.py"  
>  Traceback (most recent  
>  call last): File "C:/…/PycharmProjects/Convolutional Neural Networks for
> Visual  
>  Recognition/input_cifar.py", line 76, in  
>  Yte_predict = nn.predict(Xte_rows) # predict labels on the test images File
> "C:/Users/Naoki Ishibashi/PycharmProjects/Convolutional  
>  Neural Networks for Visual Recognition/input_cifar.py", line 58, in  
>  predict  
>  for i in xrange(num_test): NameError: name 'xrange' is not defined
CC BY-SA 3.0
2017-02-05T17:00:51.510
32410
2017-02-06T06:07:17.403
2017-02-05T22:08:35.057
19110
20523
question
python 深層学習 機械学習
NameError: name 'xrange' is not defined -- CIFAR-10を使ったクラスわけでエラー, Python2.7.12
`xrange()`は Python2.x 系のメソッドです。Python3.x 系では `range()` を使います。

実行している`python`のパスを見る限り、今回動かしているものは Python3.5 のように見えます。

同じ環境に Python2.x 系と Python3.x
系が同時に入っている場合は、どちらが実行されるのか分かりやすくするためにコマンド名で区別したり(`python2`,
`python3`)、エラーが起こったときはまずバージョンを疑ったり (`python --version`) などすると良いと思います。

また、エラーが起こったときはそのエラー名でググるのも良い戦略です。今回の場合、

> NameError: name 'xrange' is not defined

でググると「バージョンが違います」という回答が載ったページがいくつか出てきます。
CC BY-SA 3.0
2017-02-05T19:01:38.773
32412
2017-02-06T06:07:17.403
2017-02-06T06:07:17.403
19110
19110
32410
answer