import cv2 import time import numpy as np import pandas as pd import gradio as gr import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.keras.datasets import imdb from tensorflow.keras.callbacks import Callback from tensorflow.keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM, Embedding from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score # Завантаження датасету з CSV-файлу url = 'https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_us_Books_v1_02.tsv.gz' df = pd.read_csv(url, sep='\t', compression='gzip', error_bad_lines=False) # Відображення перших 5 рядків датасету print(df.head()) number_of_words = 10000 (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words = number_of_words) print(X_train.shape) print(y_train.shape) print(X_test.shape) print(y_test.shape) print(y_test[8]) word_to_index = imdb.get_word_index() word_to_index['great'] index_to_word = {index: word for (word, index) in word_to_index.items()} print([index_to_word[i] for i in range(1, 51)]) print(X_train[123]) print(' '.join([index_to_word.get(i-3, '?') for i in X_train[123]])) print(y_train[123]) words_per_review = 200 text = [2, 4, 5, 6] X_train = pad_sequences(X_train, maxlen = words_per_review) print(X_train.shape) X_test = pad_sequences(X_test, maxlen = words_per_review) print(X_test.shape) print(X_train[123]) X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, random_state = 11, test_size = 0.20) print(X_test.shape) print(X_val.shape) rnn = Sequential() rnn.add(Embedding(input_dim = number_of_words, output_dim = 128, input_length = words_per_review)) rnn.add(LSTM(units = 128, dropout = 0.2, recurrent_dropout = 0.2)) rnn.add(Dense(units = 1, activation = 'sigmoid')) rnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) rnn.summary() class TimingCallback(Callback): def on_train_begin(self, logs={}): self.start_time = time.time() def on_train_end(self, logs={}): elapsed_time = time.time() - self.start_time print('Витрачений час на навчання: ', round(elapsed_time, 2), ' секунд') history_rrn = rnn.fit(X_train, y_train, epochs = 10, batch_size = 32, validation_data = (X_test, y_test), callbacks=[TimingCallback()]) result = rnn.evaluate(X_test, y_test) print(result) def evaluate_model(model, history, X_test, Y_test): loss, accuracy = model.evaluate(X_test, Y_test, verbose = 0) print("Значення функції точності: ", accuracy) # Обчислення тривалості навчання моделі (в епохах) training_time = history.epoch[-1] + 1 print('Тривалість навчання: ', training_time, ' епох') Y_pred = model.predict(X_test) # Показує наскільки сильно відрізняються передбачення моделі від фактичних значень цільової змінної print('Mean Absolute Error (MAE) - середня абсолютна помилка:', mean_absolute_error(Y_test, Y_pred)) # Показує середнє значення квадрата різниці між фактичними та передбаченими значеннями print('Mean Squared Error (MSE) - середня квадратична помилка:', mean_squared_error(Y_test, Y_pred)) # Показує, наскільки добре модель відповідає даним print('R-squared (R2) – коефіцієнт детермінації:' + str(r2_score(Y_test, Y_pred))) #Побудова графіка plt.plot(history.history['loss'], label='Training loss') plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend() plt.show() evaluate_model(rnn, history_rrn, X_test, y_test) # Створення функції для оцінки коментаря def predict_comment_score(comment): class_names = ["Negative", "Positive"] words = comment.split() print(len(words)) indexes = np.zeros(words_per_review).astype(int) indexes[words_per_review -len(words) - 1] = 1 for i, word in enumerate(words): indexes[words_per_review -len(words) + i] = word_to_index.get(word, 0) + 3 indexes = np.expand_dims(indexes, axis=0) predictions = rnn.predict(indexes) prediction = { } prediction["Negative"] = float(np.round(1 - predictions[0], 3)) prediction["Positive"] = float(np.round(predictions[0], 3)) return prediction demo = gr.Blocks() # Створення інтерфейсу Gradio with demo: with gr.Tab("Predict comment score"): image_input = gr.TextArea(label="Enter a comment") output = gr.Label(label="Comment score") image_button = gr.Button("Predict") image_button.click(predict_comment_score, inputs=image_input, outputs=output) demo.launch(debug=True)