0

I am currently doing some experiment for my research. And I want to change the labeling of the MNIST data --- to have number 0 labeled as 1, and all the other numbers labeled as -1.

I found in the mnist.py file how the labels are extracted.

def extract_labels(f, one_hot=False, num_classes=10 ,zero=True):
    print('Extracting', f.name)
    with gzip.GzipFile(fileobj=f) as bytestream:
        magic = _read32(bytestream)
        if magic != 2049:
            raise ValueError('Invalid magic number %d in MNIST 
                                    label file: %s' % (magic, f.name))

    num_items = _read32(bytestream)
    buf = bytestream.read(num_items)
    labels = numpy.frombuffer(buf, dtype=numpy.uint8)

    if zero:
        labels[labels != 0] = -1
        labels[labels == 0 ] = 1

    if one_hot:
        return dense_to_one_hot(labels, num_classes)
    return labels

My modification is adding the if zero statement.

However, it says that

ValueError: assignment destination is read-only

Could anyone help with this?

cs95
  • 379,657
  • 97
  • 704
  • 746
Andre
  • 116
  • 9
  • Did you try converting it? `labels = np.asarray(labels)`? – cs95 Nov 16 '17 at 21:48
  • @cᴏʟᴅsᴘᴇᴇᴅ I just tried, and there's no bug reported. This makes me even more confused about the **read only** statement – Andre Nov 16 '17 at 23:02
  • Meaning that it works? – cs95 Nov 16 '17 at 23:06
  • @cᴏʟᴅsᴘᴇᴇᴅ Yes, it works for `labels = np.asarray(labels)`, however, it will output `File "D:\Python\lib\site-packages\tensorflow\contrib\learn\python\learn\datasets\mnist.py", line 102, in extract_labels labels[labels != 0] = -1` `ValueError: assignment destination` is read-only for my code. – Andre Nov 16 '17 at 23:33
  • See if https://stackoverflow.com/questions/39554660/np-arrays-being-immutable-assignment-destination-is-read-only helps. – cs95 Nov 16 '17 at 23:34
  • Seems like temporarily setting the writable flag is a cleaner option. It will make for less chances of unexpected behavior down the line. – Mad Physicist Nov 16 '17 at 23:42
  • @cᴏʟᴅsᴘᴇᴇᴅ Thx, it worked! Now there is another issue: my code `labels[labels != 0] = -1` now makes those labels that not equal to 0 become 255 now. How can I make them to be -1? – Andre Nov 16 '17 at 23:44
  • @MadPhysicist Yes, it worked well. Thx1 – Andre Nov 16 '17 at 23:45
  • @HaiwenHuang try: `dtype=numpy.int8` (not unsigned) – cs95 Nov 16 '17 at 23:53

0 Answers0