oleksiikondus commited on
Commit
124ab99
·
1 Parent(s): 80568ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -101
app.py CHANGED
@@ -1,107 +1,10 @@
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
-
33
- word_to_index = imdb.get_word_index()
34
- word_to_index['great']
35
-
36
- index_to_word = {index: word for (word, index) in word_to_index.items()}
37
-
38
- print([index_to_word[i] for i in range(1, 51)])
39
-
40
- print(X_train[123])
41
- print(' '.join([index_to_word.get(i-3, '?') for i in X_train[123]]))
42
- print(y_train[123])
43
 
 
44
  words_per_review = 200
45
- text = [2, 4, 5, 6]
46
- X_train = pad_sequences(X_train, maxlen = words_per_review)
47
- print(X_train.shape)
48
- X_test = pad_sequences(X_test, maxlen = words_per_review)
49
- print(X_test.shape)
50
- print(X_train[123])
51
-
52
- X_test, X_val, y_test, y_val = train_test_split(X_test, y_test, random_state = 11, test_size = 0.20)
53
-
54
- print(X_test.shape)
55
- print(X_val.shape)
56
-
57
- rnn = Sequential()
58
- rnn.add(Embedding(input_dim = number_of_words, output_dim = 128, input_length = words_per_review))
59
- rnn.add(LSTM(units = 128, dropout = 0.2, recurrent_dropout = 0.2))
60
- rnn.add(Dense(units = 1, activation = 'sigmoid'))
61
-
62
- rnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
63
- rnn.summary()
64
-
65
- class TimingCallback(Callback):
66
- def on_train_begin(self, logs={}):
67
- self.start_time = time.time()
68
-
69
- def on_train_end(self, logs={}):
70
- elapsed_time = time.time() - self.start_time
71
- print('Витрачений час на навчання: ', round(elapsed_time, 2), ' секунд')
72
-
73
- history_rrn = rnn.fit(X_train, y_train, epochs = 10, batch_size = 32, validation_data = (X_test, y_test), callbacks=[TimingCallback()])
74
-
75
- result = rnn.evaluate(X_test, y_test)
76
- print(result)
77
-
78
- def evaluate_model(model, history, X_test, Y_test):
79
- loss, accuracy = model.evaluate(X_test, Y_test, verbose = 0)
80
- print("Значення функції точності: ", accuracy)
81
-
82
- # Обчислення тривалості навчання моделі (в епохах)
83
- training_time = history.epoch[-1] + 1
84
- print('Тривалість навчання: ', training_time, ' епох')
85
-
86
-
87
- Y_pred = model.predict(X_test)
88
- # Показує наскільки сильно відрізняються передбачення моделі від фактичних значень цільової змінної
89
- print('Mean Absolute Error (MAE) - середня абсолютна помилка:', mean_absolute_error(Y_test, Y_pred))
90
- # Показує середнє значення квадрата різниці між фактичними та передбаченими значеннями
91
- print('Mean Squared Error (MSE) - середня квадратична помилка:', mean_squared_error(Y_test, Y_pred))
92
- # Показує, наскільки добре модель відповідає даним
93
- print('R-squared (R2) – коефіцієнт детермінації:' + str(r2_score(Y_test, Y_pred)))
94
-
95
- #Побудова графіка
96
- plt.plot(history.history['loss'], label='Training loss')
97
- plt.title('Model loss')
98
- plt.ylabel('Loss')
99
- plt.xlabel('Epoch')
100
- plt.legend()
101
- plt.show()
102
-
103
- evaluate_model(rnn, history_rrn, X_test, y_test)
104
-
105
 
106
  # Створення функції для оцінки коментаря
107
  def predict_comment_score(comment):
 
 
 
 
 
 
 
 
1
  from tensorflow.keras.datasets import imdb
2
+ from tensorflow import keras
3
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ rnn = keras.models.load_model('model.h5')
6
  words_per_review = 200
7
+ word_to_index = imdb.get_word_index()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # Створення функції для оцінки коментаря
10
  def predict_comment_score(comment):