File size: 5,155 Bytes
7556992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
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)