oleksiikondus commited on
Commit
7556992
·
1 Parent(s): 2b594bc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import time
3
+ import numpy as np
4
+ import pandas as pd
5
+ import gradio as gr
6
+ import tensorflow as tf
7
+ import matplotlib.pyplot as plt
8
+ from tensorflow.keras.datasets import imdb
9
+ from tensorflow.keras.callbacks import Callback
10
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
11
+ from sklearn.model_selection import train_test_split
12
+ from tensorflow.keras.models import Sequential
13
+ from tensorflow.keras.layers import Dense, LSTM, Embedding
14
+ from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
15
+
16
+ # Завантаження датасету з CSV-файлу
17
+ url = 'https://s3.amazonaws.com/amazon-reviews-pds/tsv/amazon_reviews_us_Books_v1_02.tsv.gz'
18
+ df = pd.read_csv(url, sep='\t', compression='gzip', error_bad_lines=False)
19
+
20
+ # Відображення перших 5 рядків датасету
21
+ print(df.head())
22
+
23
+ number_of_words = 10000
24
+ (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words = number_of_words)
25
+
26
+ print(X_train.shape)
27
+ print(y_train.shape)
28
+ print(X_test.shape)
29
+ print(y_test.shape)
30
+ print(y_test[8])
31
+
32
+ %pprint
33
+
34
+ word_to_index = imdb.get_word_index()
35
+ word_to_index['great']
36
+
37
+ index_to_word = {index: word for (word, index) in word_to_index.items()}
38
+
39
+ print([index_to_word[i] for i in range(1, 51)])
40
+
41
+ print(X_train[123])
42
+ print(' '.join([index_to_word.get(i-3, '?') for i in X_train[123]]))
43
+ print(y_train[123])
44
+
45
+ words_per_review = 200
46
+ text = [2, 4, 5, 6]
47
+ X_train = pad_sequences(X_train, maxlen = words_per_review)
48
+ print(X_train.shape)
49
+ X_test = pad_sequences(X_test, maxlen = words_per_review)
50
+ print(X_test.shape)
51
+ print(X_train[123])
52
+
53
+ X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, random_state = 11, test_size = 0.20)
54
+
55
+ print(X_test.shape)
56
+ print(X_val.shape)
57
+
58
+ rnn = Sequential()
59
+ rnn.add(Embedding(input_dim = number_of_words, output_dim = 128, input_length = words_per_review))
60
+ rnn.add(LSTM(units = 128, dropout = 0.2, recurrent_dropout = 0.2))
61
+ rnn.add(Dense(units = 1, activation = 'sigmoid'))
62
+
63
+ rnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
64
+ rnn.summary()
65
+
66
+ class TimingCallback(Callback):
67
+ def on_train_begin(self, logs={}):
68
+ self.start_time = time.time()
69
+
70
+ def on_train_end(self, logs={}):
71
+ elapsed_time = time.time() - self.start_time
72
+ print('Витрачений час на навчання: ', round(elapsed_time, 2), ' секунд')
73
+
74
+ history_rrn = rnn.fit(X_train, y_train, epochs = 10, batch_size = 32, validation_data = (X_test, y_test), callbacks=[TimingCallback()])
75
+
76
+ result = rnn.evaluate(X_test, y_test)
77
+ print(result)
78
+
79
+ def evaluate_model(model, history, X_test, Y_test):
80
+ loss, accuracy = model.evaluate(X_test, Y_test, verbose = 0)
81
+ print("Значення функції точності: ", accuracy)
82
+
83
+ # Обчислення тривалості навчання моделі (в епохах)
84
+ training_time = history.epoch[-1] + 1
85
+ print('Тривалість навчання: ', training_time, ' епох')
86
+
87
+
88
+ Y_pred = model.predict(X_test)
89
+ # Показує наскільки сильно відрізняються передбачення моделі від фактичних значень цільової змінної
90
+ print('Mean Absolute Error (MAE) - середня абсолютна помилка:', mean_absolute_error(Y_test, Y_pred))
91
+ # Показує середнє значення квадрата різниці між фактичними та передбаченими значеннями
92
+ print('Mean Squared Error (MSE) - середня квадратична помилка:', mean_squared_error(Y_test, Y_pred))
93
+ # Показує, наскільки добре модель відповідає даним
94
+ print('R-squared (R2) – коефіцієнт детермінації:' + str(r2_score(Y_test, Y_pred)))
95
+
96
+ #Побудова графіка
97
+ plt.plot(history.history['loss'], label='Training loss')
98
+ plt.title('Model loss')
99
+ plt.ylabel('Loss')
100
+ plt.xlabel('Epoch')
101
+ plt.legend()
102
+ plt.show()
103
+
104
+ evaluate_model(rnn, history_rrn, X_test, y_test)
105
+
106
+
107
+ # Створення функції для оцінки коментаря
108
+ def predict_comment_score(comment):
109
+ class_names = ["Negative", "Positive"]
110
+ words = comment.split()
111
+ print(len(words))
112
+ indexes = np.zeros(words_per_review).astype(int)
113
+ indexes[words_per_review -len(words) - 1] = 1
114
+ for i, word in enumerate(words):
115
+ indexes[words_per_review -len(words) + i] = word_to_index.get(word, 0) + 3
116
+ indexes = np.expand_dims(indexes, axis=0)
117
+ predictions = rnn.predict(indexes)
118
+ prediction = { }
119
+ prediction["Negative"] = float(np.round(1 - predictions[0], 3))
120
+ prediction["Positive"] = float(np.round(predictions[0], 3))
121
+ return prediction
122
+
123
+ demo = gr.Blocks()
124
+
125
+ # Створення інтерфейсу Gradio
126
+ with demo:
127
+ with gr.Tab("Predict comment score"):
128
+ image_input = gr.TextArea(label="Enter a comment")
129
+ output = gr.Label(label="Comment score")
130
+ image_button = gr.Button("Predict")
131
+ image_button.click(predict_comment_score, inputs=image_input, outputs=output)
132
+
133
+ demo.launch(debug=True)