-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMnistDataSet.java
More file actions
290 lines (259 loc) · 9.11 KB
/
MnistDataSet.java
File metadata and controls
290 lines (259 loc) · 9.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//package lib;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
/**
* MNISTの手書き文字の画像データを扱うクラス.
*/
public class MnistDataSet implements Serializable {
public static final String TRAIN_IMAGE_FILE = "train-images-idx3-ubyte.gz";
public static final String TRAIN_LABEL_FILE = "train-labels-idx1-ubyte.gz";
public static final String TEST_IMAGE_FILE = "t10k-images-idx3-ubyte.gz";
public static final String TEST_LABEL_FILE = "t10k-labels-idx1-ubyte.gz";
public static final String BASE_PATH = "./dataset/mnist/";
private static final String BASE_URL = "http://yann.lecun.com/exdb/mnist/";
private static final String SERIALIZED_FILE = "_mnist.ser";
private static final long serialVersionUID = 1L;
private String prefix;
private int numImages;
private int numDimensions;
private double[][] features;
private int[] labels;
public static void main(String... args) throws IOException, ClassNotFoundException {
// トレーニングデータセット
MnistDataSet trainDataSet = MnistDataSet.createInstance("train");
// 概形を表示する
//trainDataSet.showImageAsText(0);
// 画像を表示する
//trainDataSet.showImage(1);
// 画像を保存する
//trainDataSet.saveImage(MnistDataSet.BASE_PATH, 2);
// テストデータセット
MnistDataSet testDataSet = MnistDataSet.createInstance("test");
// 概形を表示する
//testDataSet.showImageAsText(0);
// 画像を表示する
//testDataSet.showImage(1);
// 画像を保存する
//testDataSet.saveImage(MnistDataSet.BASE_PATH, 2);
}
private MnistDataSet(String prefix) {
this.prefix = prefix;
}
public static MnistDataSet createInstance(String prefix) throws IOException, ClassNotFoundException {
if ("train".equals(prefix)) {
return createInstance(prefix, TRAIN_IMAGE_FILE, TRAIN_LABEL_FILE);
} else if ("test".equals(prefix)) {
return createInstance(prefix, TEST_IMAGE_FILE, TEST_LABEL_FILE);
} else {
throw new IllegalArgumentException("Prefix must be 'train' or 'test'.");
}
}
/**
* Mnistデータセットのインスタンスを作成する.
*
* @param prefix プレフィックス
* @param imageFile 画像データのファイル名
* @param labelFile 正解ラベルデータのファイル名
* @return Mnistデータセットのインスタンス
*/
public static MnistDataSet createInstance(String prefix, String imageFile, String labelFile) throws IOException, ClassNotFoundException {
File baseDir = new File(BASE_PATH);
if (!baseDir.exists()) {
baseDir.mkdirs();
}
download(BASE_URL, BASE_PATH, imageFile);
download(BASE_URL, BASE_PATH, labelFile);
String serFilePath = BASE_PATH + prefix + SERIALIZED_FILE;
if (new File(serFilePath).exists()) {
System.out.println("Deserializing object from " + prefix + SERIALIZED_FILE + " ...");
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));) {
return (MnistDataSet) ois.readObject();
}
} else {
MnistDataSet dataSet = new MnistDataSet(prefix);
System.out.println("Loading feature data from " + imageFile + " ...");
dataSet.loadFeatures(imageFile);
System.out.println("Loading label data from " + labelFile + " ...");
dataSet.loadLabels(labelFile);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));) {
oos.writeObject(dataSet);
}
return dataSet;
}
}
/**
* 画像数を取得する.
*
* @return 画像数
*/
public int getNumImages() {
return numImages;
}
/**
* 特徴量の次元数を取得する.
*
* @return 特徴量の次元数
*/
public int getNumDimensions() {
return numDimensions;
}
/**
* 特徴量データを取得する.
*
* @return 特徴量データ
*/
public double[][] getFeatures() {
System.out.println(features.length);
return features;
}
/**
* 正解ラベルデータを取得する.
*
* @return 正解ラベルデータ
*/
public int[] getLabels() {
return labels;
}
public double[][] getLabels_onehot(){
double[][] onehot = new double[labels.length][10];
for(int i = 0; i < labels.length; i++){
for(int j = 0; j < 10; j++){
onehot[i][j] = 0.0;
}
onehot[i][labels[i]] = 1.0;
}
System.out.println(onehot.length);
return onehot;
}
/**
* 標準出力に画像の概形を表示する.
*
* @param index 画像の番号.
*/
public void showImageAsText(int index) {
System.out.println("Label: " + labels[index]);
for (int i = 0; i < 28; i++) {
for (int j = 0; j < 28; j++) {
double value = features[index][i * 28 + j];
if (value > 0.0) {
System.out.print("**");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
/**
* 画像を表示する.
*
* @param index 画像の番号
*/
public void showImage(int index) {
BufferedImage image = makeImage(index);
Icon icon = new ImageIcon(image);
try {
JOptionPane.showMessageDialog(null, labels[index], "MnistImageViewer", JOptionPane.PLAIN_MESSAGE, icon);
} catch (HeadlessException e) {
System.out.println("Image dialog can't be displayed on CUI environment.");
}
}
/**
* 画像をファイルに保存する.
*
* @param dir ファイルを保存するディレクトリ
* @param index 画像の番号
*/
public void saveImage(String dir, int index) throws IOException {
BufferedImage image = makeImage(index);
File file = new File(dir + "/" + prefix + "_" + String.format("%05d", index) + "_" + labels[index] + ".gif");
if (file.exists()) file.delete();
ImageIO.write(image, "gif", file);
}
/**
* 数値データから画像オブジェクトを生成する.
*
* @param index 画像の番号
* @return 画像オブジェクト
*/
private BufferedImage makeImage(int index) {
BufferedImage image =
new BufferedImage(28, 28, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < 28; i++) {
for (int j = 0; j < 28; j++) {
int value = (int) (features[index][i * 28 + j] * 255.0);
image.setRGB(j, i, 0xff000000 | value << 16 | value << 8 | value);
}
}
return image;
}
/**
* 特徴量データを読み込む.
*
* @param imageFile 画像データのファイル名
*/
private void loadFeatures(String imageFile) throws IOException {
try (DataInputStream is = new DataInputStream(new GZIPInputStream(new FileInputStream(BASE_PATH + imageFile)));) {
is.readInt();
numImages = is.readInt();
if(numImages == 60000) numImages = 5000;
else numImages = 1000;
numDimensions = is.readInt() * is.readInt();
features = new double[numImages][numDimensions];
for (int i = 0; i < numImages; i++) {
for (int j = 0; j < numDimensions; j++) {
features[i][j] = (double) is.readUnsignedByte() / 255.0;
}
}
}
}
/**
* 正解ラベルデータを読み込む.
*
* @param labelFile 正解ラベルデータのファイル名
*/
private void loadLabels(String labelFile) throws IOException {
try (DataInputStream is = new DataInputStream(new GZIPInputStream(new FileInputStream(BASE_PATH + labelFile)));) {
is.readInt();
int numLabels = is.readInt();
if(numLabels == 60000) numLabels = 5000;
else numLabels = 1000;
labels = new int[numLabels];
for (int i = 0; i < numLabels; i++) {
labels[i] = is.readUnsignedByte();
}
}
}
/**
* ファイルをダウンロードする.
*
* @param baseUrl ダウンロード元のベースURL
* @param basePath ダウンロード先のベースパス
* @param fileName ファイル名
*/
private static void download(String baseUrl, String basePath, String fileName) throws IOException {
if (!new File(basePath + fileName).exists()) {
System.out.println("Downloading " + baseUrl + fileName + " ...");
URL url = new URL(baseUrl + fileName);
URLConnection conn = url.openConnection();
File file = new File(basePath + fileName);
try (InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream(file, false);) {
byte[] data = new byte[1024];
while (true) {
int ret = in.read(data);
if (ret == -1) {
break;
}
out.write(data, 0, ret);
}
}
}
}
}