64 lines
1.3 KiB
Python
64 lines
1.3 KiB
Python
import numpy as np
|
|
from PIL import Image
|
|
import matplotlib.pyplot as plt
|
|
from sklearn import datasets
|
|
from sklearn.metrics import accuracy_score
|
|
from sklearn.neural_network import MLPClassifier
|
|
import cv2
|
|
|
|
|
|
# training
|
|
# recznie napisane cyfry
|
|
digits = datasets.load_digits()
|
|
|
|
y = digits.target
|
|
x = digits.images.reshape((len(digits.images), -1))
|
|
|
|
x_train = x[:1000000]
|
|
y_train = y[:1000000]
|
|
x_test = x[1000:]
|
|
y_test = y[1000:]
|
|
|
|
mlp = MLPClassifier(hidden_layer_sizes=(15,), activation='logistic', alpha=1e-4,
|
|
solver='sgd', tol=1e-4, random_state=1,
|
|
learning_rate_init=.1, verbose=True)
|
|
|
|
mlp.fit(x_train, y_train)
|
|
|
|
predictions = mlp.predict(x_test)
|
|
print(accuracy_score(y_test, predictions))
|
|
|
|
|
|
# image
|
|
|
|
img = cv2.cvtColor(cv2.imread('test3.png'), cv2.COLOR_BGR2GRAY)
|
|
img = cv2.GaussianBlur(img, (5, 5), 0) # poprawia jakosc
|
|
img = cv2.resize(img, (8, 8), interpolation=cv2.INTER_AREA)
|
|
|
|
print(type(img))
|
|
print(img.shape)
|
|
print(img)
|
|
plt.imshow(img ,cmap='binary')
|
|
plt.show()
|
|
|
|
data = []
|
|
|
|
rows, cols = img.shape
|
|
for i in range(rows):
|
|
for j in range(cols):
|
|
k = img[i, j]
|
|
if k == 255:
|
|
k = 0 # brak czarnego
|
|
else:
|
|
k = 1
|
|
|
|
data.append(k)
|
|
|
|
data = np.asarray(data, dtype=np.float32)
|
|
print(data)
|
|
|
|
predictions = mlp.predict([data])
|
|
|
|
print("Liczba to:", predictions[0])
|
|
|