Aleenaben commited on
Commit
c7044a4
·
1 Parent(s): 96e4f82

Upload 4 files

Browse files
Files changed (4) hide show
  1. BackPropogation.py +53 -0
  2. app.py +156 -0
  3. back-propagation_model.pkl +3 -0
  4. dnn_model.h5 +3 -0
BackPropogation.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from tqdm import tqdm
3
+
4
+
5
+ class BackPropogation:
6
+ def __init__(self,learning_rate=0.01, epochs=100,activation_function='step'):
7
+ self.bias = 0
8
+ self.learning_rate = learning_rate
9
+ self.max_epochs = epochs
10
+ self.activation_function = activation_function
11
+
12
+
13
+ def activate(self, x):
14
+ if self.activation_function == 'step':
15
+ return 1 if x >= 0 else 0
16
+ elif self.activation_function == 'sigmoid':
17
+ return 1 if (1 / (1 + np.exp(-x)))>=0.5 else 0
18
+ elif self.activation_function == 'relu':
19
+ return 1 if max(0,x)>=0.5 else 0
20
+
21
+ def fit(self, X, y):
22
+ error_sum=0
23
+ n_features = X.shape[1]
24
+ self.weights = np.zeros((n_features))
25
+ for epoch in tqdm(range(self.max_epochs)):
26
+ for i in range(len(X)):
27
+ inputs = X[i]
28
+ target = y[i]
29
+ weighted_sum = np.dot(inputs, self.weights) + self.bias
30
+ prediction = self.activate(weighted_sum)
31
+
32
+ # Calculating loss and updating weights.
33
+ error = target - prediction
34
+ self.weights += self.learning_rate * error * inputs
35
+ self.bias += self.learning_rate * error
36
+
37
+ print(f"Updated Weights after epoch {epoch} with {self.weights}")
38
+ print("Training Completed")
39
+
40
+ def predict(self, X):
41
+ predictions = []
42
+ for i in range(len(X)):
43
+ inputs = X[i]
44
+ weighted_sum = np.dot(inputs, self.weights) + self.bias
45
+ prediction = self.activate(weighted_sum)
46
+ predictions.append(prediction)
47
+ return predictions
48
+
49
+
50
+
51
+
52
+
53
+
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pickle
3
+ import tensorflow as tf
4
+ from PIL import Image
5
+ import numpy as np
6
+ import cv2
7
+ import pandas as pd
8
+ from tensorflow.keras.datasets import imdb
9
+ from tensorflow.keras.preprocessing.text import Tokenizer
10
+ from tensorflow.keras.models import save_model, load_model
11
+ from BackPropogation import BackPropogation
12
+ from sklearn.model_selection import train_test_split
13
+
14
+
15
+
16
+
17
+ def cnn_tumor(img):
18
+ img=Image.open(img)
19
+ img=np.array(img)
20
+ img=cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
21
+ img_array = cv2.medianBlur(img, 5)
22
+ img = Image.fromarray(cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB))
23
+ img=img.resize((128,128))
24
+ input_img = np.expand_dims(img, axis=0)
25
+ st.image(input_img, caption='Image Processing', use_column_width=True)
26
+ loaded_model = tf.keras.models.load_model('cnn_model.h5')
27
+ predictions = loaded_model.predict(input_img)
28
+ if predictions:
29
+ st.write("Tumor Detected")
30
+ else:
31
+ st.write("No Tumor")
32
+
33
+ def perceptron():
34
+ with open('perceptron_model.pkl', 'rb') as file:
35
+ loaded_model = pickle.load(file)
36
+
37
+ top_words = 5000
38
+ (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
39
+ word_index = imdb.get_word_index()
40
+ reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
41
+
42
+ user_input = st.text_input("Enter your movie review:")
43
+
44
+ if st.button("Predict"):
45
+
46
+ if user_input:
47
+ st.write("Review:", user_input)
48
+
49
+ user_input_sequence = [word_index.get(word, 0) for word in user_input.split()]
50
+ processed_input = tf.keras.preprocessing.sequence.pad_sequences([user_input_sequence], maxlen=500, padding='post', truncating='post')
51
+
52
+ prediction = loaded_model.predict(processed_input)
53
+
54
+ sentiment = 'Positive' if prediction[0] > 0.5 else 'Negative'
55
+ st.write("Predicted Sentiment:", sentiment)
56
+ else:
57
+ st.warning("Please enter a movie review.")
58
+
59
+ def backprop():
60
+
61
+ with open('back-propagation_model.pkl', 'rb') as file:
62
+ loaded_model = pickle.load(file)
63
+
64
+ top_words = 5000
65
+ (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
66
+
67
+ word_index = imdb.get_word_index()
68
+ reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
69
+
70
+ user_input = st.text_input("Enter your movie review:")
71
+
72
+ if st.button("Predict"):
73
+
74
+ if user_input:
75
+ st.write("Review:", user_input)
76
+
77
+ user_input_sequence = [word_index.get(word, 0) for word in user_input.split()]
78
+ processed_input = tf.keras.preprocessing.sequence.pad_sequences([user_input_sequence], maxlen=500, padding='post', truncating='post')
79
+
80
+ prediction = loaded_model.predict(processed_input)
81
+
82
+ sentiment = 'Positive' if prediction[0] > 0.5 else 'Negative'
83
+ st.write("Predicted Sentiment:", sentiment)
84
+ else:
85
+ st.warning("Please enter a movie review.")
86
+
87
+ def dnn_model():
88
+ user_input = st.text_input('Enter a sentence:')
89
+ tokenizer = Tokenizer(num_words=10000, oov_token='<OOV>')
90
+ tokenizer.fit_on_texts([user_input])
91
+ sequences = tokenizer.texts_to_sequences([user_input])
92
+ padded_sequence = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=500, padding='post', truncating='post')
93
+ loaded_model = tf.keras.models.load_model('dnn_model.h5')
94
+ if st.button('Predict'):
95
+ prediction = loaded_model.predict(np.array(padded_sequence))
96
+ sentiment = 'Positive' if prediction > 0.5 else 'Negative'
97
+ st.success(f'Sentiment: {sentiment}, Confidence: {prediction[0][0]:.4f}')
98
+
99
+
100
+ def rnn_model():
101
+ loaded_model = tf.keras.models.load_model('rnn_model.h5')
102
+ user_input_sequence = st.text_area("Enter your text message:")
103
+ if st.button('Predict'):
104
+ if user_input_sequence:
105
+ tokenizer = Tokenizer(num_words=5000)
106
+ tokenizer.fit_on_texts([user_input_sequence])
107
+ sequences = tokenizer.texts_to_sequences([user_input_sequence])
108
+ processed_input = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=10, padding='post', truncating='post')
109
+
110
+ prediction = loaded_model.predict(np.array(processed_input))
111
+
112
+ is_spam = 'Spam' if prediction[0] > 0.5 else 'Not Spam'
113
+ st.write("Predicted Label:", is_spam)
114
+ else:
115
+ st.warning("Please enter a text message.")
116
+
117
+
118
+ def lstm_model():
119
+ user_input = st.text_input('Enter a sentence:')
120
+ tokenizer = Tokenizer(num_words=10000, oov_token='<OOV>')
121
+ tokenizer.fit_on_texts([user_input])
122
+ sequences = tokenizer.texts_to_sequences([user_input])
123
+ padded_sequence = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=500, padding='post', truncating='post')
124
+ loaded_model = tf.keras.models.load_model('lstm_model.h5')
125
+ if st.button('Predict Sentiment'):
126
+ prediction = loaded_model.predict(np.array(padded_sequence))
127
+ sentiment = 'Positive' if prediction > 0.5 else 'Negative'
128
+ st.success(f'Sentiment: {sentiment}, Confidence: {prediction[0][0]:.4f}')
129
+
130
+
131
+
132
+
133
+ st.title('Model Prediction')
134
+ option = st.selectbox("Select One",['Tumor Detection','Sentiment Classification'])
135
+
136
+ if option=='Tumor Detection':
137
+ st.title('CNN Tumor Detection Model')
138
+ img=st.file_uploader("Upload your file here.....", type=['png', 'jpeg', 'jpg'])
139
+ cnn_tumor(img)
140
+ else:
141
+ opt=st.radio("Select your prediction",key="visibility",options=["Perceptron",'Backpropogation','DNN','RNN','LSTM'])
142
+ if opt=="Perceptron":
143
+ st.title('Perceptron Model')
144
+ perceptron()
145
+ elif opt=="Backpropogation":
146
+ st.title('Backpropogation Model')
147
+ backprop()
148
+ elif opt=='RNN':
149
+ st.title('RNN Spam Detection')
150
+ rnn_model()
151
+ elif opt=='DNN':
152
+ st.title('DNN Text Classification')
153
+ dnn_model()
154
+ else:
155
+ st.title('LSTM Sentiment Analysis')
156
+ lstm_model()
back-propagation_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25ea2c6a11d5e28877ca644fe12d8da841b60df39cf1defffe654f23a1100530
3
+ size 4300
dnn_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:681d680affa87af6fe68547754edd9e7209e6cabcaf3c4d7ba5d2c7cf236cf01
3
+ size 10735120