P-Tech/NeuralNetworks
1
1library(shiny)
2library(shinyjs)
3library(bslib)
4library(dplyr)
5library(ggplot2)
6library(readxl)
7library(htmlwidgets)
8library(shinydashboard)
9library(neuralnet)
10library(rsample)
11options(width = 150)
12options(digits = 4, scipen = 1000000000)
13options(shiny.maxRequestSize=30*1024^2)
14
15
16
17ui <- fluidPage(
18 theme = bs_theme(version = 5, bootswatch = "spacelab"),
19 useShinyjs(), # Initialize shinyjs
20 titlePanel("PtteM Data Science"),
21 tags$head(tags$link(rel = "stylesheet", href="https://fonts.googleapis.com/css?family=Montserrat:100,300,400,700&display=swap"),
22 tags$style(HTML("
23 body, h1, h2, h3, h4, h5, h6, .nav, p, a, .shiny-input-container {
24 font-family: 'Montserrat'; /* Font type for the title attribute */
25 font-weight: 385;
26 color: #007c9e !important;
27 }
28 * {
29 font-family: 'Montserrat', sans-serif;
30 font-weight: 385;
31 color: #195576; /* Blue color */
32 }
33 body {
34 background-color: #f7f7f7; /* Light gray background */
35 }
36 .icon-btn {
37 border: 1px solid #0d6efd; /* Example border: solid, 2 pixels, #555 color */
38 border-radius: 15%; /* Circular border */
39 color: #00969e; /* Icon color */
40 font-family: 'Montserrat'; /* Font type for the title attribute */
41 font-weight: 385;
42 background-color: #f7f7f7;
43 padding: 125px; /* Space around the icon */
44 margin: 25px; /* Space around the button */
45 font-size: 24px; /* Icon size */
46 box-shadow: 0 2px 4px rgba(0,0,0,0.2);
47 }
48 .icon-btn:hover {
49 color: #00969e; /* Icon color on hover */
50 border-color: #007c9e;
51 background-color: #ebfbfd;/* Border color on hover */
52 }
53 /* Add custom styles here */
54 .shiny-input-container {
55 margin-bottom: 15px;
56 }
57 .box {
58 border: 1px solid #ddd;
59 padding: 20px;
60 border-radius: 50px;
61 margin-bottom: 200px;
62 gap: 200px;
63 align-items: center;
64 }
65 #statsTable_wrapper {
66 margin: 0 auto;
67 }
68 .shiny-output-error {
69 border: 1px solid #FF0000; /* Red border on error */
70 }
71 /* If you want to change the font size of the tooltip, you can add custom CSS for the 'title' attribute's default styling. */
72 "))),
73 tags$head(
74 # Include JavaScript to reload the page
75 tags$script(HTML("
76 document.addEventListener('DOMContentLoaded', function() {
77 document.getElementById('myElement').style.color = '#0d6efd'; // Change to your desired color
78 });
79"))
80 ),
81 tags$head(
82 tags$script(HTML("
83 function reloadPage() {
84 window.location.reload();
85 }
86 "))
87 ),
88 # Refresh button that calls the JavaScript function
89 actionButton("refresh", "Refresh Analysis", onclick = "reloadPage();"),
90 # Help Text or Information for the user
91 helpText("Bu uygulama ile metin analizi başlığı altındaki veri bilimi fonksiyonlarına erişebilirsiniz."),
92 #Neural Networks
93 h2("Neural Networks Section"),
94 tabsetPanel(
95 tabPanel("Perceptron Model",
96 sidebarLayout(
97 sidebarPanel(
98 fileInput("perc_input", "Choose CSV/XLSX/XSX File", accept = c(".csv, .xlsx, .xsx")),
99 uiOutput("target_perc"), # Dynamically generate UI for selecting target variable
100 uiOutput("predictors_perc"), # Dynamically generate UI for selecting predictor variables
101 sliderInput("dataSplitperc",
102 "Data Split Ratio",
103 min = 0.1,
104 max = 0.9,
105 value = 0.7, # Default value, for instance, 70% for training and 30% for testing
106 step = 0.05,
107 ticks = FALSE,
108 animate = TRUE),
109 actionButton("train_perceptron", "Train Perceptron Model"),
110 HTML("<div>
111 <h2>Perceptron Modeli</h2>
112 <p>Perceptron modeli, doğrusal olarak ayrılabilir veri kümeleri için basit bir denetimli öğrenme algoritmasıdır. Bu model, girdi ve çıktılar arasındaki ilişkiyi öğrenmek için kullanılır ve sınıflandırma problemlerinde yaygın olarak tercih edilir.</p>
113
114 <h3>Kullanım Adımları:</h3>
115 <ol>
116 <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> aracı ile CSV, XLSX veya XSX formatlarında veri dosyanızı yükleyin.</li>
117 <li><strong>Hedef ve Öngörücülerin Seçimi:</strong> Dinamik olarak oluşturulan UI üzerinden hedef değişken ve öngörücü değişken(ler)inizi seçin.</li>
118 <li><strong>Veri Bölme Oranı:</strong> <code>sliderInput</code> ile veri bölme oranını ayarlayın (örneğin, %70 eğitim, %30 test).</li>
119 <li><strong>Modeli Eğit:</strong> <code>Train Perceptron Model</code> butonu ile perceptron modelinizi eğitin.</li>
120 </ol>
121
122 <h3>Model Özeti ve Kullanıcı Etkileşimi:</h3>
123 <p>Kullanıcılar modeli eğittikten sonra, model özetini ve eğitim sonuçlarını görebilirler. Modelin performansı, çapraz doğrulama yöntemiyle değerlendirilir.</p>
124
125 <h3>Uygulama Alanları:</h3>
126 <p>Perceptron modeli, metin sınıflandırma, görüntü tanıma ve basit doğrusal ayrım gerektiren diğer makine öğrenmesi görevlerinde kullanılabilir.</p>
127
128 <h3>Sonuçların Yorumlanması:</h3>
129 <p>Eğitilen modelin başarısı, doğruluk oranı ve diğer performans metrikleriyle değerlendirilir. Modelin ayrıntılı özetinde, ağırlıklar, yanlılık ve öğrenme oranı gibi parametreler gösterilir.</p>
130</div>")
131
132 ),
133 mainPanel(
134 tabsetPanel(
135 tabPanel("Model Summary",verbatimTextOutput("model_summary")),
136 )
137 )
138 )
139 ),
140 tabPanel("Multilayer Perceptron",
141
142 sidebarLayout(
143 sidebarPanel(
144 fileInput("mlp_fileInput", "Choose CSV/XLSX/XSX File", accept = c(".csv", ".xlsx", ".xsx")),
145 uiOutput("mlp_preprocessUI"),
146 numericInput("mlp_hiddenLayers", "Number of Hidden Layers", value = 1),
147 numericInput("mlp_neurons", "Neurons in Hidden Layer", value = 5),
148 numericInput("mlp_epochs", "Number of Epochs", value = 100),
149 actionButton("mlp_trainButton", "Train MLP Model"),
150 HTML("<div>
151 <h2>Çok Katmanlı Perseptron Modeli</h2>
152 <p>Çok katmanlı perseptron modeli, derin öğrenme ve yapay sinir ağlarının temel yapı taşlarından biridir. Bu model, karmaşık veri yapılarını öğrenebilme ve tahmin etme yeteneğiyle ön plana çıkar.</p>
153
154 <h3>Kullanım Adımları:</h3>
155 <ol>
156 <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> aracı ile CSV, XLSX veya XSX formatlarında veri dosyanızı yükleyin.</li>
157 <li><strong>Ön İşleme ve Değişken Seçimi:</strong> Dinamik olarak oluşturulan UI üzerinden hedef değişken, öngörücü değişken(ler) ve koşullu değişken seçin.</li>
158 <li><strong>Model Parametreleri:</strong> Gizli katman sayısı, bir gizli katmandaki nöron sayısı ve dönem sayısı gibi model parametrelerini ayarlayın.</li>
159 <li><strong>Modeli Eğit:</strong> <code>Train MLP Model</code> butonu ile çok katmanlı perceptron modelinizi eğitin.</li>
160 </ol>
161
162 <h3>Model Çıktısı ve Değerlendirme:</h3>
163 <p>Model eğitimi tamamlandıktan sonra, eğitim sürecini ve modelin performansını gösteren grafikler ve özet metinler kullanıcıya sunulur. Model, verilen parametrelere göre en iyi yapılandırmayı öğrenmeye çalışır.</p>
164
165 <h3>Uygulama Alanları:</h3>
166 <p>Çok katmanlı perseptron modelleri, görüntü ve ses işleme, metin sınıflandırma ve finansal tahminler gibi geniş bir uygulama alanına sahiptir.</p>
167
168 <h3>Sonuçların Yorumlanması:</h3>
169 <p>Modelin başarımı, hata oranları, adım sayısı ve ağırlık dağılımları üzerinden değerlendirilir. Eğitim sürecinde elde edilen ağırlık değerleri, modelin öğrenme kapasitesini ve veri üzerindeki genelleme yeteneğini gösterir. Ayrıca, modelin gerçek dünya verileri üzerindeki performansını test etmek için ayrı bir test veri seti kullanılması önerilir.</p>
170</div>"),
171 ),
172 mainPanel(
173 tabsetPanel(
174 tabPanel("Multilayer Output", plotOutput("mlp_trainingPlot", width = "100%", height = "700px")),
175 tabPanel("Evaluation", verbatimTextOutput("mlp_evaluation")),
176 tabPanel("GW Plot", plotOutput("mlp_gwplot", width = "100%", height = "700px"))
177 )
178 )
179 )
180 ),
181
182 )
183)
184
185
186
187server <- function(input, output, session) {
188
189 read_data <- function(filepath) {
190 ext <- tools::file_ext(filepath)
191 if (ext == "csv") {
192 read.csv(filepath, stringsAsFactors = FALSE)
193 } else if (ext == "xlsx") {
194 readxl::read_excel(filepath)
195 } else {
196 stop("Invalid file format. Please select a CSV or XLSX file.")
197 }
198 }
199
200 clean_column_names <- function(dataframe) {
201 colnames(dataframe) <- gsub("[^[:alnum:]_]", "", make.names(colnames(dataframe), unique = TRUE))
202 return(dataframe)
203 }
204
205 ##Neural Networks
206 ###Perceptron
207 # Reactive expression to read and preprocess the dataset
208 dataperc <- reactive({
209 req(input$perc_input)
210 inFile <- input$perc_input
211
212 # Read the file based on its type
213 if (grepl("\\.csv$", inFile$name)) {
214 data <- read.csv(inFile$datapath, stringsAsFactors = FALSE)
215 } else if (grepl("\\.(xlsx|xls)$", inFile$name)) {
216 data <- readxl::read_xlsx(inFile$datapath)
217 } else {
218 stop("Unsupported file type")
219 }
220
221 # Clean up column names
222 names(data) <- make.names(names(data), unique = TRUE)
223 return(data)
224 })
225
226
227 # Generate UI for selecting the target variable
228 output$target_perc <- renderUI({
229 req(dataperc()) # Ensure data is loaded
230
231 # Create a list of UI elements to return
232 ui_elements <- tagList(
233 # Dropdown for selecting the target variable
234 selectInput("target_variable", "Select Target Variable", choices = names(dataperc())),
235 # Hint for the user with an emoji
236 tags$p(HTML("Please upload a categorical variable 🏀 💄 🍔 📱")) # Smiling face emoji
237 )
238
239 return(ui_elements)
240 })
241
242
243 # Generate UI for selecting predictor variables
244 output$predictors_perc <- renderUI({
245 req(dataperc())
246 selectInput("predictors", "Select Predictor Variables", multiple = TRUE, choices = names(dataperc()), selected = names(dataperc())[1])
247 })
248
249 # Train the Perceptron model
250 observeEvent(input$train_perceptron, {
251 req(dataperc(), input$target_variable, input$predictors)
252 data <- dataperc()
253 data <- na.omit(data)
254
255 # Ensure the target variable is a factor
256 data[[input$target_variable]] <- as.factor(data[[input$target_variable]])
257
258 #target_variable <- input$target_variable
259 #predictors <- input$predictors
260
261 # Split data into training and testing sets
262 set.seed(123)
263 split_ratio <- input$dataSplitperc
264 trainingIndex <- caret::createDataPartition(data[[input$target_variable]], p = split_ratio, list = FALSE)
265 trainingData <- data[trainingIndex, ]
266 testData <- data[-trainingIndex, ]
267
268 # Define control using a cross-validation approach
269 trainControl <- trainControl(method = "cv", number = 10)
270 # Assuming variable names are now valid R identifiers without special characters
271 formula <- as.formula(paste(input$target_variable, "~", paste(input$predictors, collapse = "+")))
272 perceptronModel <- caret::train(formula, data = trainingData, method = "lvq", preProcess = "scale", trControl = trainControl)
273
274 # Model summary
275 output$model_summary <- renderPrint({
276 perceptronModel
277 })
278
279 })
280
281 ##Multiple Perceptron Model
282 # Reactive expression for data input
283 dataMLP <- reactive({
284 req(input$mlp_fileInput)
285 inFile <- input$mlp_fileInput
286 if (grepl("\\.csv$", inFile$name)) {
287 read.csv(inFile$datapath, stringsAsFactors = FALSE)
288 } else if (grepl("\\.(xlsx|xls)$", inFile$name)) {
289 readxl::read_xlsx(inFile$datapath)
290 } else {
291 stop("Unsupported file type")
292 }
293 })
294
295 output$mlp_preprocessUI <- renderUI({
296 req(dataMLP())
297 varNames <- names(dataMLP())
298 tagList(
299 selectInput("mlp_targetVariable", "Select Target Variable", choices = varNames),
300 selectInput("mlp_variables", "Select Predictor Variables", choices = varNames, multiple = TRUE),
301 selectInput("mlp_covariate", "Select Covariate Variable", choices = varNames),
302 tags$p(HTML("Please select Covariate Variable from Predictor Variables"))
303 )
304 })
305
306 observeEvent(input$mlp_trainButton, {
307 req(dataMLP(), input$mlp_targetVariable, input$mlp_variables)
308 data <- dataMLP()
309 data <- na.omit(data)
310
311 # Define the formula for the neural network
312 formula <- as.formula(paste(input$mlp_targetVariable, "~", paste(input$mlp_variables, collapse = "+")))
313
314 # Train the neural network model
315 nn <- neuralnet(formula, data, hidden = c(input$mlp_neurons), linear.output = FALSE, threshold = 0.01, stepmax = input$mlp_epochs)
316
317 # Plot the neural network
318 output$mlp_trainingPlot <- renderPlot({
319 plot(nn,rep = "best")
320 })
321
322
323 # Print the result matrix of the neural network
324 output$mlp_evaluation <- renderPrint({
325 print(nn$result.matrix)
326 # Neural Network Model Performance Summary
327 cat("\nNeural Network Model Performance Summary:\n")
328
329 # If the error is not within a reasonable range, you could give more context:
330 if (nn$result.matrix["error", ] > 200) {
331 cat("The model error of", nn$result.matrix["error", ], "is above the expected threshold. This may indicate that the model does not fit the data well. Consider collecting more data, feature engineering, or adjusting the model's complexity.\n")
332 } else {
333 cat("The model error of", nn$result.matrix["error", ], "is within the acceptable range, suggesting the model has learned the patterns from the data effectively.\n")
334 }
335
336 # Comment on the number of steps
337 cat("The model took", nn$result.matrix["steps", ], "steps to converge, which indicates ", ifelse(nn$result.matrix["steps", ] < 3000, "an efficient training process.", "that the maximum set steps were reached without sufficient convergence."), "\n")
338
339 # Comment on the weights
340 cat("The model's weights have been optimized through training. Each weight reflects the importance of the corresponding input feature for predicting the output. For instance, the weight for 'Price' to the first hidden neuron is", nn$result.matrix["Price.to.1layhid1", ], ".\n")
341
342 # Mention the threshold
343 cat("The threshold for stopping the training was set to", nn$result.matrix["reached.threshold", ], ", and the model reached an error close to this threshold, which is a good sign of model convergence.\n")
344
345 # Add a note on the usage of the model
346 cat("This trained model can now be used to make predictions on new data. It's important to validate the model's performance on a separate test set to ensure its predictive accuracy.\n")
347 })
348
349 output$mlp_gwplot <- renderPlot({
350 req(input$mlp_covariate) # Make sure input$mlp_variables is available
351 selected_var <- input$mlp_covariate # This should be a vector of selected variable names
352 if (length(selected_var) == 1) { # gwplot may only accept a single variable
353 gwplot(nn, selected.covariate = selected_var, min = -2.5, max = 5)
354 } else {
355 cat("Please select a single predictor variable to view its weight distribution.")
356 }
357 })
358
359 })
360
361}
362
363shinyApp(ui, server)