uci_housing.py 3.8 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import six
import numpy as np

20
import paddle
K
Kaipeng Deng 已提交
21
from paddle.io import Dataset
22
from paddle.dataset.common import _check_exists_and_download
K
Kaipeng Deng 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

__all__ = ["UCIHousing"]

URL = 'http://paddlemodels.bj.bcebos.com/uci_housing/housing.data'
MD5 = 'd4accdce7a25600298819f8e28e8d593'
feature_names = [
    'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX',
    'PTRATIO', 'B', 'LSTAT'
]


class UCIHousing(Dataset):
    """
    Implementation of `UCI housing <https://archive.ics.uci.edu/ml/datasets/Housing>`_
    dataset

    Args:
        data_file(str): path to data file, can be set None if
            :attr:`download` is True. Default None
        mode(str): 'train' or 'test' mode. Default 'train'.
        download(bool): whether to download dataset automatically if
            :attr:`data_file` is not set. Default True

    Returns:
        Dataset: instance of UCI housing dataset.

    Examples:
        
        .. code-block:: python

53 54
            import paddle
            from paddle.text.datasets import UCIHousing
K
Kaipeng Deng 已提交
55

56 57 58
            class SimpleNet(paddle.nn.Layer):
                def __init__(self):
                    super(SimpleNet, self).__init__()
K
Kaipeng Deng 已提交
59

60 61
                def forward(self, feature, target):
                    return paddle.sum(feature), target
K
Kaipeng Deng 已提交
62

63
            paddle.disable_static()
K
Kaipeng Deng 已提交
64

65
            uci_housing = UCIHousing(mode='train')
K
Kaipeng Deng 已提交
66

67 68 69 70
            for i in range(10):
                feature, target = uci_housing[i]
                feature = paddle.to_tensor(feature)
                target = paddle.to_tensor(target)
K
Kaipeng Deng 已提交
71

72 73 74
                model = SimpleNet()
                feature, target = model(feature, target)
                print(feature.numpy().shape, target.numpy())
K
Kaipeng Deng 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    """

    def __init__(self, data_file=None, mode='train', download=True):
        assert mode.lower() in ['train', 'test'], \
                "mode should be 'train' or 'test', but got {}".format(mode)
        self.mode = mode.lower()

        self.data_file = data_file
        if self.data_file is None:
            assert download, "data_file is not set and downloading automatically is disabled"
            self.data_file = _check_exists_and_download(data_file, URL, MD5,
                                                        'uci_housing', download)

        # read dataset into memory
        self._load_data()

92 93
        self.dtype = paddle.get_default_dtype()

K
Kaipeng Deng 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    def _load_data(self, feature_num=14, ratio=0.8):
        data = np.fromfile(self.data_file, sep=' ')
        data = data.reshape(data.shape[0] // feature_num, feature_num)
        maximums, minimums, avgs = data.max(axis=0), data.min(axis=0), data.sum(
            axis=0) / data.shape[0]
        for i in six.moves.range(feature_num - 1):
            data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])
        offset = int(data.shape[0] * ratio)
        if self.mode == 'train':
            self.data = data[:offset]
        elif self.mode == 'test':
            self.data = data[offset:]

    def __getitem__(self, idx):
        data = self.data[idx]
109 110
        return np.array(data[:-1]).astype(self.dtype), \
                np.array(data[-1:]).astype(self.dtype)
K
Kaipeng Deng 已提交
111 112 113

    def __len__(self):
        return len(self.data)