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

56 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"""IMDB sentiment 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.imdb.load_data") 

30def load_data( 

31 path="imdb.npz", 

32 num_words=None, 

33 skip_top=0, 

34 maxlen=None, 

35 seed=113, 

36 start_char=1, 

37 oov_char=2, 

38 index_from=3, 

39 **kwargs, 

40): 

41 """Loads the [IMDB dataset](https://ai.stanford.edu/~amaas/data/sentiment/). 

42 

43 This is a dataset of 25,000 movies reviews from IMDB, labeled by sentiment 

44 (positive/negative). Reviews have been preprocessed, and each review is 

45 encoded as a list of word indexes (integers). 

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

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

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

49 "only consider the top 10,000 most 

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

51 

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

53 to encode the pad token. 

54 

55 Args: 

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

57 num_words: integer or None. Words are 

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

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

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

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

62 skip_top: skip the top N most frequently occurring words 

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

64 `oov_char` value in the dataset. When 0, no words are 

65 skipped. Defaults to `0`. 

66 maxlen: int or None. Maximum sequence length. 

67 Any longer sequence will be truncated. None, means no truncation. 

68 Defaults to `None`. 

69 seed: int. Seed for reproducible data shuffling. 

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

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

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

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

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

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

76 **kwargs: Used for backwards compatibility. 

77 

78 Returns: 

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

80 

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

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

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

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

85 

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

87 

88 Raises: 

89 ValueError: in case `maxlen` is so low 

90 that no input sequence could be kept. 

91 

92 Note that the 'out of vocabulary' character is only used for 

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

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

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

96 have simply been skipped. 

97 """ 

98 # Legacy support 

99 if "nb_words" in kwargs: 

100 logging.warning( 

101 "The `nb_words` argument in `load_data` " 

102 "has been renamed `num_words`." 

103 ) 

104 num_words = kwargs.pop("nb_words") 

105 if kwargs: 

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

107 

108 origin_folder = ( 

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

110 ) 

111 path = get_file( 

112 path, 

113 origin=origin_folder + "imdb.npz", 

114 file_hash=( # noqa: E501 

115 "69664113be75683a8fe16e3ed0ab59fda8886cb3cd7ada244f7d9544e4676b9f" 

116 ), 

117 ) 

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

119 x_train, labels_train = f["x_train"], f["y_train"] 

120 x_test, labels_test = f["x_test"], f["y_test"] 

121 

122 rng = np.random.RandomState(seed) 

123 indices = np.arange(len(x_train)) 

124 rng.shuffle(indices) 

125 x_train = x_train[indices] 

126 labels_train = labels_train[indices] 

127 

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

129 rng.shuffle(indices) 

130 x_test = x_test[indices] 

131 labels_test = labels_test[indices] 

132 

133 if start_char is not None: 

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

135 x_test = [[start_char] + [w + index_from for w in x] for x in x_test] 

136 elif index_from: 

137 x_train = [[w + index_from for w in x] for x in x_train] 

138 x_test = [[w + index_from for w in x] for x in x_test] 

139 

140 if maxlen: 

141 x_train, labels_train = _remove_long_seq(maxlen, x_train, labels_train) 

142 x_test, labels_test = _remove_long_seq(maxlen, x_test, labels_test) 

143 if not x_train or not x_test: 

144 raise ValueError( 

145 "After filtering for sequences shorter than maxlen=" 

146 f"{str(maxlen)}, no sequence was kept. Increase maxlen." 

147 ) 

148 

149 xs = x_train + x_test 

150 labels = np.concatenate([labels_train, labels_test]) 

151 

152 if not num_words: 

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

154 

155 # by convention, use 2 as OOV word 

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

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

158 if oov_char is not None: 

159 xs = [ 

160 [w if (skip_top <= w < num_words) else oov_char for w in x] 

161 for x in xs 

162 ] 

163 else: 

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

165 

166 idx = len(x_train) 

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

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

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

170 

171 

172@keras_export("keras.datasets.imdb.get_word_index") 

173def get_word_index(path="imdb_word_index.json"): 

174 """Retrieves a dict mapping words to their index in the IMDB dataset. 

175 

176 Args: 

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

178 

179 Returns: 

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

181 index. 

182 

183 Example: 

184 

185 ```python 

186 # Use the default parameters to keras.datasets.imdb.load_data 

187 start_char = 1 

188 oov_char = 2 

189 index_from = 3 

190 # Retrieve the training sequences. 

191 (x_train, _), _ = keras.datasets.imdb.load_data( 

192 start_char=start_char, oov_char=oov_char, index_from=index_from 

193 ) 

194 # Retrieve the word index file mapping words to indices 

195 word_index = keras.datasets.imdb.get_word_index() 

196 # Reverse the word index to obtain a dict mapping indices to words 

197 # And add `index_from` to indices to sync with `x_train` 

198 inverted_word_index = dict( 

199 (i + index_from, word) for (word, i) in word_index.items() 

200 ) 

201 # Update `inverted_word_index` to include `start_char` and `oov_char` 

202 inverted_word_index[start_char] = "[START]" 

203 inverted_word_index[oov_char] = "[OOV]" 

204 # Decode the first sequence in the dataset 

205 decoded_sequence = " ".join(inverted_word_index[i] for i in x_train[0]) 

206 ``` 

207 """ 

208 origin_folder = ( 

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

210 ) 

211 path = get_file( 

212 path, 

213 origin=origin_folder + "imdb_word_index.json", 

214 file_hash="bfafd718b763782e994055a2d397834f", 

215 ) 

216 with open(path) as f: 

217 return json.load(f) 

218