Найти тему
Чебурнет

Какая-то нейронка

!pip install tensorflow matplotlib numpy

import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf

from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

img_height = 80
img_width = 80
batch_size = 256

train = tf.keras.utils.image_dataset_from_directory(
'dataset/train',
image_size=(img_height, img_width),
batch_size=batch_size)
val = tf.keras.utils.image_dataset_from_directory(
'dataset/val',
image_size=(img_height, img_width),
batch_size=batch_size)

class_names = train.class_names
print(f"Class names: {class_names}")

# cache
AUTOTUNE = tf.data.AUTOTUNE
train = train.cache().prefetch(buffer_size=AUTOTUNE)
val = val.cache().prefetch(buffer_size=AUTOTUNE)

num_classes = len(class_names)
model = Sequential([
# т.к. у нас версия TF 2.6 локально
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),

# дальше везде одинаково
layers.Conv2D(16, 1, padding='same', activation='relu'),
layers.MaxPooling2D(2),

layers.Dropout(0.2),

layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(2),

layers.Conv2D(64, 7, padding='same', activation='relu'),
layers.MaxPooling2D(2),
layers.Conv2D(128, 6, padding='same', activation='relu'),
layers.MaxPooling2D(2),
layers.Dropout(0.2),

layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(30, activation='relu'),
layers.Dense(4, activation='relu'),
layers.Dense(num_classes),
layers.Softmax()
])

# compile the model
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])

# print model summary
model.summary()

# train the model
epochs = 20 # количество эпох тренировки
history = model.fit(
train,
validation_data=val,
epochs=epochs)

# visualize training and validation results
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(epochs)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

model.save('model')

model.predict([0,0])