teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

修正

2020/06/19 14:49

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -4,6 +4,10 @@
4
4
 
5
5
  ![イメージ説明](66766755f398e249b1b85174ee9f8c00.png)
6
6
 
7
+ 以下の手順で作成しました。
8
+ 1. ペイントを開いて、100x100 とか縦横が同じ大きさのキャンバスを作成する
9
+ 2. 白い背景に黒いペンで数字を書く
10
+
7
11
  ```python
8
12
  import sklearn.datasets
9
13
  import sklearn.svm

2

修正

2020/06/19 14:49

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -31,6 +31,6 @@
31
31
  print("予測=", n)
32
32
 
33
33
 
34
- data = imageToData("92.png")
34
+ data = imageToData("9.png")
35
35
  predictDigits(data)
36
36
  ```

1

修正

2020/06/19 14:43

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -1,57 +1,36 @@
1
1
  手元で確認しましたが、SVM で推論できました。
2
2
 
3
- 自作した画像は**背景にい文字**で作成しましたか?
3
+ 自作した画像は**白い背景にい文字**で作成しましたか?
4
4
 
5
- ![イメージ説明](a59544f8f22371aff9fcab936cf47a3e.png)
5
+ ![イメージ説明](66766755f398e249b1b85174ee9f8c00.png)
6
6
 
7
- ![イメージ説明](1e07e8989750e6eb93cdbab39226abff.png)
8
-
9
7
  ```python
10
- import matplotlib.pyplot as plt
8
+ import sklearn.datasets
9
+ import sklearn.svm
10
+ import PIL.Image
11
- import numpy as np
11
+ import numpy
12
- from PIL import Image
13
- from sklearn.datasets import load_digits
14
- from sklearn.metrics import accuracy_score
15
- from sklearn.svm import SVC
16
12
 
17
13
 
18
- def load_img(filename):
14
+ def imageToData(filename):
19
- img = Image.open(filename).convert("L")
15
+ grayImage = PIL.Image.open(filename).convert("L")
20
- img = img.resize((8, 8), Image.ANTIALIAS)
16
+ grayImage = grayImage.resize((8, 8), PIL.Image.ANTIALIAS)
21
- # uint8 -> float
22
- img = np.array(img, dtype=float)
17
+ numImage = numpy.asarray(grayImage, dtype=float)
23
- # [0, 255] -> [0, 16] にスケールする。
24
- img = 16 * (img - img.min()) / (img.max() - img.min())
18
+ numImage = numpy.floor(16 - 16 * (numImage / 256))
25
- # (8, 8) -> (64,)
26
- img = img.flatten()
19
+ numImage = numImage.flatten()
27
20
 
28
- return img
21
+ return numImage
29
22
 
30
23
 
31
- def show_digit(x):
24
+ def predictDigits(data):
32
- x = x.reshape(8, 8)
25
+ digits = sklearn.datasets.load_digits()
33
26
 
34
- fig, ax = plt.subplots()
27
+ clf = sklearn.svm.SVC(gamma=0.001)
35
- ax.imshow(x, cmap="gray")
28
+ clf.fit(digits.data, digits.target)
36
- plt.show()
37
29
 
30
+ n = clf.predict([data])
31
+ print("予測=", n)
38
32
 
39
- def pred_img(filename):
40
- data = load_img(filename)
41
- pred = clf.predict([data])
42
33
 
43
- show_digit(data)
44
- print(pred)
45
-
46
-
47
- digits = load_digits()
48
- clf = SVC(gamma=0.001).fit(digits.data, digits.target)
49
- pred = clf.predict(digits.data)
50
-
51
- # 学習データに対する精度を確認
52
- accuracy = accuracy_score(digits.target, pred)
53
- print(f"{accuracy:.2%}")
54
-
55
- pred_img("2.png")
34
+ data = imageToData("92.png")
56
- pred_img("9.png")
35
+ predictDigits(data)
57
36
  ```