from PIL import Image
import random
def image_to_inputs(filename):
image = Image.open(filename)
image = image.convert("L")
pixels = list(image.getdata())
inputs = [1]
for y in range(20):
for x in range(20):
pixel = pixels[y * 20 + x]
if pixel > 128:
inputs.append(0)
else:
inputs.append(1)
return inputs
def create_weights():
weights = []
for i in range(401):
weights.append(random.uniform(-0.3, 0.3))
return weights
def calculate_sum(inputs, weights):
s = 0
for i in range(401):
s += inputs[i] * weights[i]
return s
def activation(s):
if s >= 0:
return 1
else:
return 0
def update_weights(inputs, weights, learning_rate, delta):
for i in range(401):
weights[i] = weights[i] + learning_rate * delta * inputs[i]
return weights
# Картинка
inputs = image_to_inputs("plus1.png")
# Начальные веса
weights = create_weights()
# Работа нейрона
s = calculate_sum(inputs, weights)
output = activation(s)
# Обучение на одном примере
PLUS = 0
MINUS = 1
target = PLUS
delta = target - output
learning_rate = 0.6
weights = update_weights(inputs, weights, learning_rate, delta)
print("Количество входов:", len(inputs))
print("Выход нейрона:", output)
print("Правильный ответ:", target)
print("Ошибка:", delta)