Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/datasets/reuters.py: 28%

47 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-03 07:57 +0000

1# Copyright 2015 The TensorFlow Authors. All Rights Reserved. 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================== 

15"""Reuters topic classification dataset.""" 

16 

17import json 

18 

19import numpy as np 

20 

21from keras.src.preprocessing.sequence import _remove_long_seq 

22from keras.src.utils.data_utils import get_file 

23 

24# isort: off 

25from tensorflow.python.platform import tf_logging as logging 

26from tensorflow.python.util.tf_export import keras_export 

27 

28 

29@keras_export("keras.datasets.reuters.load_data") 

30def load_data( 

31 path="reuters.npz", 

32 num_words=None, 

33 skip_top=0, 

34 maxlen=None, 

35 test_split=0.2, 

36 seed=113, 

37 start_char=1, 

38 oov_char=2, 

39 index_from=3, 

40 **kwargs, 

41): 

42 """Loads the Reuters newswire classification dataset. 

43 

44 This is a dataset of 11,228 newswires from Reuters, labeled over 46 topics. 

45 

46 This was originally generated by parsing and preprocessing the classic 

47 Reuters-21578 dataset, but the preprocessing code is no longer packaged 

48 with Keras. See this 

49 [GitHub discussion](https://github.com/keras-team/keras/issues/12072) 

50 for more info. 

51 

52 Each newswire is encoded as a list of word indexes (integers). 

53 For convenience, words are indexed by overall frequency in the dataset, 

54 so that for instance the integer "3" encodes the 3rd most frequent word in 

55 the data. This allows for quick filtering operations such as: 

56 "only consider the top 10,000 most 

57 common words, but eliminate the top 20 most common words". 

58 

59 As a convention, "0" does not stand for a specific word, but instead is used 

60 to encode any unknown word. 

61 

62 Args: 

63 path: where to cache the data (relative to `~/.keras/dataset`). 

64 num_words: integer or None. Words are 

65 ranked by how often they occur (in the training set) and only 

66 the `num_words` most frequent words are kept. Any less frequent word 

67 will appear as `oov_char` value in the sequence data. If None, 

68 all words are kept. Defaults to `None`. 

69 skip_top: skip the top N most frequently occurring words 

70 (which may not be informative). These words will appear as 

71 `oov_char` value in the dataset. 0 means no words are 

72 skipped. Defaults to `0`. 

73 maxlen: int or None. Maximum sequence length. 

74 Any longer sequence will be truncated. None means no truncation. 

75 Defaults to `None`. 

76 test_split: Float between `0.` and `1.`. Fraction of the dataset to be 

77 used as test data. `0.2` means that 20% of the dataset is used as 

78 test data. Defaults to `0.2`. 

79 seed: int. Seed for reproducible data shuffling. 

80 start_char: int. The start of a sequence will be marked with this 

81 character. 0 is usually the padding character. Defaults to `1`. 

82 oov_char: int. The out-of-vocabulary character. 

83 Words that were cut out because of the `num_words` or 

84 `skip_top` limits will be replaced with this character. 

85 index_from: int. Index actual words with this index and higher. 

86 **kwargs: Used for backwards compatibility. 

87 

88 Returns: 

89 Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. 

90 

91 **x_train, x_test**: lists of sequences, which are lists of indexes 

92 (integers). If the num_words argument was specific, the maximum 

93 possible index value is `num_words - 1`. If the `maxlen` argument was 

94 specified, the largest possible sequence length is `maxlen`. 

95 

96 **y_train, y_test**: lists of integer labels (1 or 0). 

97 

98 Note: The 'out of vocabulary' character is only used for 

99 words that were present in the training set but are not included 

100 because they're not making the `num_words` cut here. 

101 Words that were not seen in the training set but are in the test set 

102 have simply been skipped. 

103 """ 

104 # Legacy support 

105 if "nb_words" in kwargs: 

106 logging.warning( 

107 "The `nb_words` argument in `load_data` " 

108 "has been renamed `num_words`." 

109 ) 

110 num_words = kwargs.pop("nb_words") 

111 if kwargs: 

112 raise TypeError(f"Unrecognized keyword arguments: {str(kwargs)}") 

113 

114 origin_folder = ( 

115 "https://storage.googleapis.com/tensorflow/tf-keras-datasets/" 

116 ) 

117 path = get_file( 

118 path, 

119 origin=origin_folder + "reuters.npz", 

120 file_hash=( # noqa: E501 

121 "d6586e694ee56d7a4e65172e12b3e987c03096cb01eab99753921ef915959916" 

122 ), 

123 ) 

124 with np.load(path, allow_pickle=True) as f: 

125 xs, labels = f["x"], f["y"] 

126 

127 rng = np.random.RandomState(seed) 

128 indices = np.arange(len(xs)) 

129 rng.shuffle(indices) 

130 xs = xs[indices] 

131 labels = labels[indices] 

132 

133 if start_char is not None: 

134 xs = [[start_char] + [w + index_from for w in x] for x in xs] 

135 elif index_from: 

136 xs = [[w + index_from for w in x] for x in xs] 

137 

138 if maxlen: 

139 xs, labels = _remove_long_seq(maxlen, xs, labels) 

140 

141 if not num_words: 

142 num_words = max(max(x) for x in xs) 

143 

144 # by convention, use 2 as OOV word 

145 # reserve 'index_from' (=3 by default) characters: 

146 # 0 (padding), 1 (start), 2 (OOV) 

147 if oov_char is not None: 

148 xs = [ 

149 [w if skip_top <= w < num_words else oov_char for w in x] 

150 for x in xs 

151 ] 

152 else: 

153 xs = [[w for w in x if skip_top <= w < num_words] for x in xs] 

154 

155 idx = int(len(xs) * (1 - test_split)) 

156 x_train, y_train = np.array(xs[:idx], dtype="object"), np.array( 

157 labels[:idx] 

158 ) 

159 x_test, y_test = np.array(xs[idx:], dtype="object"), np.array(labels[idx:]) 

160 

161 return (x_train, y_train), (x_test, y_test) 

162 

163 

164@keras_export("keras.datasets.reuters.get_word_index") 

165def get_word_index(path="reuters_word_index.json"): 

166 """Retrieves a dict mapping words to their index in the Reuters dataset. 

167 

168 Actual word indices starts from 3, with 3 indices reserved for: 

169 0 (padding), 1 (start), 2 (oov). 

170 

171 E.g. word index of 'the' is 1, but the in the actual training data, the 

172 index of 'the' will be 1 + 3 = 4. Vice versa, to translate word indices in 

173 training data back to words using this mapping, indices need to substract 3. 

174 

175 Args: 

176 path: where to cache the data (relative to `~/.keras/dataset`). 

177 

178 Returns: 

179 The word index dictionary. Keys are word strings, values are their 

180 index. 

181 """ 

182 origin_folder = ( 

183 "https://storage.googleapis.com/tensorflow/tf-keras-datasets/" 

184 ) 

185 path = get_file( 

186 path, 

187 origin=origin_folder + "reuters_word_index.json", 

188 file_hash="4d44cc38712099c9e383dc6e5f11a921", 

189 ) 

190 with open(path) as f: 

191 return json.load(f) 

192 

193 

194@keras_export("keras.datasets.reuters.get_label_names") 

195def get_label_names(): 

196 """Returns labels as a list of strings with indices matching training data. 

197 

198 Reference: 

199 

200 - [Reuters Dataset](https://martin-thoma.com/nlp-reuters/) 

201 """ 

202 return ( 

203 "cocoa", 

204 "grain", 

205 "veg-oil", 

206 "earn", 

207 "acq", 

208 "wheat", 

209 "copper", 

210 "housing", 

211 "money-supply", 

212 "coffee", 

213 "sugar", 

214 "trade", 

215 "reserves", 

216 "ship", 

217 "cotton", 

218 "carcass", 

219 "crude", 

220 "nat-gas", 

221 "cpi", 

222 "money-fx", 

223 "interest", 

224 "gnp", 

225 "meal-feed", 

226 "alum", 

227 "oilseed", 

228 "gold", 

229 "tin", 

230 "strategic-metal", 

231 "livestock", 

232 "retail", 

233 "ipi", 

234 "iron-steel", 

235 "rubber", 

236 "heat", 

237 "jobs", 

238 "lei", 

239 "bop", 

240 "zinc", 

241 "orange", 

242 "pet-chem", 

243 "dlr", 

244 "gas", 

245 "silver", 

246 "wpi", 

247 "hog", 

248 "lead", 

249 ) 

250