fixed voting

master
Angelos Chatzimparmpas 4 years ago
parent d95eae62ee
commit 8390cf0c63
  1. BIN
      __pycache__/run.cpython-37.pyc
  2. 0
      frontend/src/components/ActiveScatter.vue
  3. 42
      frontend/src/components/Ensemble.vue
  4. 2
      frontend/src/components/History.vue
  5. 29
      frontend/src/components/HyperParameterSpace.vue
  6. 42
      frontend/src/components/Main.vue
  7. 54
      frontend/src/components/VotingResults.vue
  8. 4
      frontend/src/main.js
  9. 372
      run.py

Binary file not shown.

@ -7,12 +7,19 @@
<option value="umapCM">UMAP</option> <option value="umapCM">UMAP</option>
</select> </select>
&nbsp;&nbsp; &nbsp;&nbsp;
Action: <button Actions: <button
id="Remove" id="Remove"
v-on:click="Remove"> v-on:click="Remove">
<font-awesome-icon icon="eraser" /> <font-awesome-icon icon="eraser" />
{{ CrossoverMutateText }} {{ CrossoverMutateText }}
</button> </button>
&nbsp;&nbsp;
<button
id="updateActiveScatter"
v-on:click="sendUpdateActiveScatter">
<font-awesome-icon icon="calculator" />
{{ valueActive }}
</button>
</div> </div>
<div id="OverviewPlotlyCM" class="OverviewPlotlyCM"></div> <div id="OverviewPlotlyCM" class="OverviewPlotlyCM"></div>
</div> </div>
@ -31,11 +38,12 @@ export default {
name: 'Ensemble', name: 'Ensemble',
data () { data () {
return { return {
CrossoverMutateText: 'Remove unselected points from ensemble', CrossoverMutateText: 'Remove unselected models from ensemble',
WH: [], WH: [],
ScatterPlotResults: '', ScatterPlotResults: '',
representationDef: 'mdsCM', representationDef: 'mdsCM',
storeEnsembleLoc: [], storeEnsembleLoc: [],
valueActive: 'Compute performance for active ensemble'
} }
}, },
methods: { methods: {
@ -104,8 +112,8 @@ export default {
var DataGeneral, maxX, minX, maxY, minY, layout var DataGeneral, maxX, minX, maxY, minY, layout
var width = this.WH[0]*8 // interactive visualization var width = this.WH[0]*6.5 // interactive visualization
var height = this.WH[1]*4 // interactive visualization var height = this.WH[1]*0.9 // interactive visualization
if (this.representationDef == 'mdsCM') { if (this.representationDef == 'mdsCM') {
maxX = Math.max(MDSData[0]) maxX = Math.max(MDSData[0])
@ -153,10 +161,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -215,10 +223,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -268,10 +276,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -311,6 +319,9 @@ export default {
} }
}) })
}, },
sendUpdateActiveScatter () {
EventBus.$emit('sendToServerSelectedScatter')
}
}, },
mounted() { mounted() {
EventBus.$on('SendStoredEnsemble', data => { this.storeEnsembleLoc = data }) EventBus.$on('SendStoredEnsemble', data => { this.storeEnsembleLoc = data })
@ -322,6 +333,11 @@ export default {
EventBus.$on('RepresentationSelectionCM', data => {this.representationDef = data}) EventBus.$on('RepresentationSelectionCM', data => {this.representationDef = data})
EventBus.$on('RepresentationSelectionCM', this.ScatterPlotView) EventBus.$on('RepresentationSelectionCM', this.ScatterPlotView)
EventBus.$on('Responsive', data => {
this.WH = data})
EventBus.$on('ResponsiveandChange', data => {
this.WH = data})
// reset view // reset view
EventBus.$on('resetViews', this.reset) EventBus.$on('resetViews', this.reset)
} }

@ -1,5 +1,5 @@
<template> <template>
<div id="SankeyInter" style="min-height: 363px;"></div> <div id="SankeyInter" style="min-height: 357px;"></div>
</template> </template>
<script> <script>

@ -31,7 +31,7 @@ export default {
name: 'HyperParameterSpace', name: 'HyperParameterSpace',
data () { data () {
return { return {
CrossoverMutateText: 'Crossover and mutate unselected points', CrossoverMutateText: 'Crossover and mutate unselected models',
WH: [], WH: [],
ScatterPlotResults: '', ScatterPlotResults: '',
representationDef: 'mds', representationDef: 'mds',
@ -88,8 +88,8 @@ export default {
var DataGeneral, maxX, minX, maxY, minY, layout var DataGeneral, maxX, minX, maxY, minY, layout
var width = this.WH[0]*8 // interactive visualization var width = this.WH[0]*6.5 // interactive visualization
var height = this.WH[1]*4 // interactive visualization var height = this.WH[1]*0.9 // interactive visualization
if (this.representationDef == 'mds') { if (this.representationDef == 'mds') {
maxX = Math.max(MDSData[0]) maxX = Math.max(MDSData[0])
@ -137,10 +137,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -199,10 +199,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -252,10 +252,10 @@ export default {
hoverlabel: { bgcolor: "#FFF" }, hoverlabel: { bgcolor: "#FFF" },
legend: {orientation: 'h', y: -0.3}, legend: {orientation: 'h', y: -0.3},
margin: { margin: {
l: 50, l: 0,
r: 0, r: 0,
b: 30, b: 0,
t: 40, t: 30,
pad: 0 pad: 0
}, },
} }
@ -307,6 +307,11 @@ export default {
EventBus.$on('RepresentationSelection', data => {this.representationDef = data}) EventBus.$on('RepresentationSelection', data => {this.representationDef = data})
EventBus.$on('RepresentationSelection', this.ScatterPlotView) EventBus.$on('RepresentationSelection', this.ScatterPlotView)
EventBus.$on('Responsive', data => {
this.WH = data})
EventBus.$on('ResponsiveandChange', data => {
this.WH = data})
// reset view // reset view
EventBus.$on('resetViews', this.reset) EventBus.$on('resetViews', this.reset)
} }

@ -18,9 +18,9 @@
</b-col> </b-col>
<b-col cols="6"> <b-col cols="6">
<mdb-card> <mdb-card>
<mdb-card-header color="primary-color" tag="h5" class="text-center">History and Algorithms/Models Selector</mdb-card-header> <mdb-card-header color="primary-color" tag="h5" class="text-center">History and Algorithms/Models Selector<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">1&2</span></span></mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-left" style="font-size: 18.5px; min-height: 359px"> <mdb-card-text class="text-left" style="font-size: 18.5px; min-height: 357px">
<History/> <History/>
</mdb-card-text> </mdb-card-text>
</mdb-card-body> </mdb-card-body>
@ -28,10 +28,10 @@
</b-col> </b-col>
<b-col cols="3"> <b-col cols="3">
<mdb-card > <mdb-card >
<mdb-card-header color="primary-color" tag="h5" class="text-center">Results of Majority-Voting Ensemble </mdb-card-header> <mdb-card-header color="primary-color" tag="h5" class="text-center">Overall Performance for Each Algorithm/Model<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">1&2</span></span></mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-left" style="font-size: 18.5px; min-height: 359px"> <mdb-card-text class="text-left" style="font-size: 18.5px; min-height: 357px">
<VotingResults/>
</mdb-card-text> </mdb-card-text>
</mdb-card-body> </mdb-card-body>
</mdb-card> </mdb-card>
@ -125,7 +125,7 @@
[Sel: {{OverSelLength}} / All: {{OverAllLength}}]<small class="float-right"><active-scatter/></small><span class="badge badge-info badge-pill float-right">Projection<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">1</span></span> [Sel: {{OverSelLength}} / All: {{OverAllLength}}]<small class="float-right"><active-scatter/></small><span class="badge badge-info badge-pill float-right">Projection<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">1</span></span>
</mdb-card-header> </mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-center" style="min-height: 600px"> <mdb-card-text class="text-center" style="min-height: 434px">
<HyperParameterSpace/> <HyperParameterSpace/>
</mdb-card-text> </mdb-card-text>
</mdb-card-body> </mdb-card-body>
@ -137,7 +137,7 @@
[Sel: {{OverSelLengthCM}} / All: {{OverAllLengthCM}}]<small class="float-right"><active-scatter/></small><span class="badge badge-info badge-pill float-right">Projection<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">2</span></span> [Sel: {{OverSelLengthCM}} / All: {{OverAllLengthCM}}]<small class="float-right"><active-scatter/></small><span class="badge badge-info badge-pill float-right">Projection<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">2</span></span>
</mdb-card-header> </mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-center" style="min-height: 600px"> <mdb-card-text class="text-center" style="min-height: 434px">
<Ensemble/> <Ensemble/>
</mdb-card-text> </mdb-card-text>
</mdb-card-body> </mdb-card-body>
@ -147,7 +147,7 @@
<b-row class="md-3"> <b-row class="md-3">
<b-col cols="3"> <b-col cols="3">
<mdb-card style="margin-top: 15px;"> <mdb-card style="margin-top: 15px;">
<mdb-card-header color="primary-color" tag="h5" class="text-center">Overall Performance for Each Algorithm/Model<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">1&2</span></span> <mdb-card-header color="primary-color" tag="h5" class="text-center">Performance for Each Validation Metric<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">{{projectionID_B}}</span></span>
</mdb-card-header> </mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-center" style="min-height: 270px"> <mdb-card-text class="text-center" style="min-height: 270px">
@ -169,11 +169,11 @@
</b-col> </b-col>
<b-col cols="3"> <b-col cols="3">
<mdb-card style="margin-top: 15px;"> <mdb-card style="margin-top: 15px;">
<mdb-card-header color="primary-color" tag="h5" class="text-center">Performance for Each Validation Metric<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">{{projectionID_B}}</span></span> <mdb-card-header color="primary-color" tag="h5" class="text-center">Predictive Results for Majority-Voting Ensemble<span class="badge badge-primary badge-pill float-right">Active<span class="badge badge-light" style="margin-left:4px; margin-bottom:1px">2</span></span>
</mdb-card-header> </mdb-card-header>
<mdb-card-body> <mdb-card-body>
<mdb-card-text class="text-center" style="min-height: 270px"> <mdb-card-text class="text-center" style="min-height: 270px">
<VotingResults/>
</mdb-card-text> </mdb-card-text>
</mdb-card-body> </mdb-card-body>
</mdb-card> </mdb-card>
@ -354,7 +354,8 @@ export default Vue.extend({
EventBus.$emit('SendSelectedPointsToServerEvent', this.PredictSelEnsem) EventBus.$emit('SendSelectedPointsToServerEvent', this.PredictSelEnsem)
this.storeBothEnsCM[1] = this.OverviewResults this.storeBothEnsCM[1] = this.OverviewResults
//EventBus.$emit('emittedEventCallingGridSelection', this.OverviewResults) //EventBus.$emit('emittedEventCallingGridSelection', this.OverviewResults)
//this.getFinalResults() EventBus.$emit('emittedEventCallingInfo', this.OverviewResults)
this.getFinalResults()
} }
}) })
.catch(error => { .catch(error => {
@ -506,15 +507,14 @@ export default Vue.extend({
this.SendSelectedIDsEnsemble() this.SendSelectedIDsEnsemble()
}, },
SendSelectedPointsToServer () { SendSelectedPointsToServer () {
if (this.ClassifierIDsList === ''){ if (this.ClassifierIDsListCM === ''){
this.OverSelLength = 0 this.OverSelLengthCM = 0
EventBus.$emit('resetViews') EventBus.$emit('resetViews')
} else { } else {
this.OverSelLength = this.ClassifierIDsList.length this.OverSelLengthCM = this.ClassifierIDsListCM.length
const path = `http://127.0.0.1:5000/data/ServerRequestSelPoin` const path = `http://127.0.0.1:5000/data/ServerRequestSelPoin`
const postData = { const postData = {
ClassifiersList: this.ClassifierIDsList, ClassifiersList: this.ClassifierIDsListCM,
keyNow: this.keyNow,
} }
const axiosConfig = { const axiosConfig = {
headers: { headers: {
@ -527,10 +527,10 @@ export default Vue.extend({
axios.post(path, postData, axiosConfig) axios.post(path, postData, axiosConfig)
.then(response => { .then(response => {
console.log('Sent the selected points to the server (scatterplot)!') console.log('Sent the selected points to the server (scatterplot)!')
if (this.keyNow == 0) { // if (this.keyNow == 0) {
this.OverAllLength = this.ClassifierIDsList.length // this.OverAllLength = this.ClassifierIDsList.length
EventBus.$emit('GrayOutPoints', this.ClassifierIDsList) // EventBus.$emit('GrayOutPoints', this.ClassifierIDsList)
} // }
//this.getSelectedModelsMetrics() //this.getSelectedModelsMetrics()
this.getFinalResults() this.getFinalResults()
}) })
@ -677,7 +677,7 @@ export default Vue.extend({
axios.get(path, axiosConfig) axios.get(path, axiosConfig)
.then(response => { .then(response => {
this.FinalResults = response.data.FinalResults this.FinalResults = response.data.FinalResults
EventBus.$emit('emittedEventCallingLinePlot', this.FinalResults) EventBus.$emit('emittedEventCallingResultsPlot', this.FinalResults)
}) })
.catch(error => { .catch(error => {
console.log(error) console.log(error)

@ -1,5 +1,5 @@
<template> <template>
<div id="doubleBarChart" style="min-height: 363px;"></div> <div id="doubleBarChart" style="min-height: 270px;"></div>
</template> </template>
<script> <script>
@ -9,7 +9,8 @@ export default {
name: 'VotingResults', name: 'VotingResults',
data () { data () {
return { return {
FinalResultsforLinePlot: 0, FinalResultsforPlot: [],
Info: [],
NumberofExecutions: 0, NumberofExecutions: 0,
scoresMean: [], scoresMean: [],
scoresSTD: [], scoresSTD: [],
@ -55,22 +56,45 @@ export default {
}, },
VotingResultsFun () { VotingResultsFun () {
var svg = d3.select("#doubleBarChart");
svg.selectAll("*").remove();
var info = JSON.parse(this.Info[13])
var dataLoc = []
dataLoc[0] = Math.floor(JSON.parse(this.FinalResultsforPlot[0])*100)
dataLoc[1] = Math.floor(JSON.parse(this.FinalResultsforPlot[1])*100)
dataLoc[2] = Math.floor(JSON.parse(this.FinalResultsforPlot[2])*100)
dataLoc[3] = Math.floor(JSON.parse(this.FinalResultsforPlot[3])*100)
dataLoc[4] = Math.floor(JSON.parse(this.FinalResultsforPlot[4])*100)
dataLoc[5] = Math.floor(JSON.parse(this.FinalResultsforPlot[5])*100)
dataLoc[6] = Math.floor(JSON.parse(this.FinalResultsforPlot[6])*100)
dataLoc[7] = Math.floor(JSON.parse(this.FinalResultsforPlot[7])*100)
dataLoc[8] = Math.floor(JSON.parse(this.FinalResultsforPlot[8])*100)
dataLoc[9] = Math.floor(JSON.parse(this.FinalResultsforPlot[9])*100)
dataLoc[10] = Math.floor(JSON.parse(this.FinalResultsforPlot[10])*100)
dataLoc[11] = Math.floor(JSON.parse(this.FinalResultsforPlot[11])*100)
dataLoc[12] = Math.floor(JSON.parse(this.FinalResultsforPlot[12])*100)
dataLoc[13] = Math.floor(JSON.parse(this.FinalResultsforPlot[13])*100)
dataLoc[14] = Math.floor(JSON.parse(this.FinalResultsforPlot[14])*100)
dataLoc[15] = Math.floor(JSON.parse(this.FinalResultsforPlot[15])*100)
var data = [ var data = [
{'countries': 'Active Accuracy', 'infant.mortality': 60, 'gdp': 100, 'group': 1, 'color': 'LIGHTSKYBLUE'}, {'countries': 'Active Accuracy', 'infant.mortality': dataLoc[0], 'gdp': dataLoc[1], 'group': 1, 'color': 'LIGHTSKYBLUE'},
{'countries': 'Best Accuracy', 'infant.mortality': 60, 'gdp': 100, 'group': 1, 'color': 'LIGHTCORAL'}, {'countries': 'Best Accuracy', 'infant.mortality': dataLoc[2], 'gdp': dataLoc[3], 'group': 1, 'color': 'LIGHTCORAL'},
{'countries': 'Active Precision', 'infant.mortality': 0, 'gdp': 33, 'group': 2, 'color': 'LIGHTSKYBLUE'}, {'countries': 'Active Precision', 'infant.mortality': dataLoc[4], 'gdp': dataLoc[5], 'group': 2, 'color': 'LIGHTSKYBLUE'},
{'countries': 'Best Precision', 'infant.mortality': 60, 'gdp': 100, 'group': 2, 'color': 'LIGHTCORAL'}, {'countries': 'Best Precision', 'infant.mortality': dataLoc[6], 'gdp': dataLoc[7], 'group': 2, 'color': 'LIGHTCORAL'},
{'countries': 'Active Recall', 'infant.mortality': 34, 'gdp': 53, 'group': 3, 'color': 'LIGHTSKYBLUE'}, {'countries': 'Active Recall', 'infant.mortality': dataLoc[8], 'gdp': dataLoc[9], 'group': 3, 'color': 'LIGHTSKYBLUE'},
{'countries': 'Best Recall', 'infant.mortality': 60, 'gdp': 100, 'group': 3, 'color': 'LIGHTCORAL'}, {'countries': 'Best Recall', 'infant.mortality': dataLoc[10], 'gdp': dataLoc[11], 'group': 3, 'color': 'LIGHTCORAL'},
{'countries': 'Active F1-score', 'infant.mortality': 50, 'gdp': 43, 'group': 4, 'color': 'LIGHTSKYBLUE'}, {'countries': 'Active F1-score', 'infant.mortality': dataLoc[12], 'gdp': dataLoc[13], 'group': 4, 'color': 'LIGHTSKYBLUE'},
{'countries': 'Best F1-score', 'infant.mortality': 60, 'gdp': 100, 'group': 4, 'color': 'LIGHTCORAL'} {'countries': 'Best F1-score', 'infant.mortality': dataLoc[14], 'gdp': dataLoc[15], 'group': 4, 'color': 'LIGHTCORAL'}
] ]
var labelArea = 160; var labelArea = 160;
var chart, var chart,
width = 214, width = 214,
bar_height = 15, bar_height = 15,
height = bar_height * 22; height = bar_height * 18;
var rightOffset = width + labelArea; var rightOffset = width + labelArea;
var lCol = "infant.mortality"; var lCol = "infant.mortality";
@ -169,13 +193,15 @@ export default {
.attr('class', 'score') .attr('class', 'score')
.text(function(d){return d[rCol];}); .text(function(d){return d[rCol];});
chart.append("text").attr("x",width/3).attr("y", 15).attr("class","title").text("Healthy"); chart.append("text").attr("x",width/3).attr("y", 15).attr("class","title").text(info[0]);
chart.append("text").attr("x",width/3+rightOffset).attr("y", 15).attr("class","title").text("Diseased"); chart.append("text").attr("x",width/3+rightOffset).attr("y", 15).attr("class","title").text(info[1]);
chart.append("text").attr("x",width+labelArea/3).attr("y", 15).attr("class","title").text("Metrics"); chart.append("text").attr("x",width+labelArea/3).attr("y", 15).attr("class","title").text("Metrics");
} }
}, },
mounted() { mounted() {
this.VotingResultsFun() EventBus.$on('emittedEventCallingInfo', data => { this.Info = data })
EventBus.$on('emittedEventCallingResultsPlot', data => { this.FinalResultsforPlot = data })
EventBus.$on('emittedEventCallingResultsPlot', this.VotingResultsFun)
EventBus.$on('Responsive', data => { EventBus.$on('Responsive', data => {
this.WH = data}) this.WH = data})

@ -6,10 +6,10 @@ import 'bootstrap-vue/dist/bootstrap-vue.css'
import router from './router' import router from './router'
import { library } from '@fortawesome/fontawesome-svg-core' import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faDna, faEraser, faSearch, faTrash} from '@fortawesome/free-solid-svg-icons' import { faDna, faEraser, faSearch, faTrash, faCalculator} from '@fortawesome/free-solid-svg-icons'
import bFormSlider from 'vue-bootstrap-slider' import bFormSlider from 'vue-bootstrap-slider'
library.add(faDna, faEraser, faSearch, faTrash) library.add(faDna, faEraser, faSearch, faTrash, faCalculator)
Vue.component('font-awesome-icon', FontAwesomeIcon) Vue.component('font-awesome-icon', FontAwesomeIcon)

372
run.py

@ -29,11 +29,13 @@ from mlxtend.feature_selection import ColumnSelector
from sklearn.metrics import matthews_corrcoef from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import log_loss from sklearn.metrics import log_loss
from imblearn.metrics import geometric_mean_score from imblearn.metrics import geometric_mean_score
from sklearn.metrics import classification_report, accuracy_score, make_scorer, confusion_matrix
from sklearn.manifold import MDS from sklearn.manifold import MDS
from sklearn.manifold import TSNE from sklearn.manifold import TSNE
import umap import umap
# this block of code is for the connection between the server, the database, and the client (plus routing) # this block of code is for the connection between the server, the database, and the client (plus routing)
# access MongoDB # access MongoDB
@ -48,6 +50,11 @@ cors = CORS(app, resources={r"/data/*": {"origins": "*"}})
@app.route('/data/Reset', methods=["GET", "POST"]) @app.route('/data/Reset', methods=["GET", "POST"])
def reset(): def reset():
global PerClassResultsClass0
PerClassResultsClass0 = []
global PerClassResultsClass1
PerClassResultsClass1 = []
global Results global Results
Results = [] Results = []
global ResultsCM global ResultsCM
@ -61,15 +68,9 @@ def reset():
global filterActionFinal global filterActionFinal
filterActionFinal = '' filterActionFinal = ''
global keySpecInternal
keySpecInternal = 1
global dataSpacePointsIDs global dataSpacePointsIDs
dataSpacePointsIDs = [] dataSpacePointsIDs = []
global previousStateActive
previousStateActive = []
global RANDOM_SEED global RANDOM_SEED
RANDOM_SEED = 42 RANDOM_SEED = 42
@ -177,6 +178,10 @@ def reset():
global target_namesLoc global target_namesLoc
target_namesLoc = [] target_namesLoc = []
global names_labels
names_labels = []
return 'The reset was done!' return 'The reset was done!'
# retrieve data from client and select the correct data set # retrieve data from client and select the correct data set
@ -191,9 +196,6 @@ def retrieveFileName():
fileName = request.get_data().decode('utf8').replace("'", '"') fileName = request.get_data().decode('utf8').replace("'", '"')
data = json.loads(fileName) data = json.loads(fileName)
global keySpecInternal
keySpecInternal = 1
global filterActionFinal global filterActionFinal
filterActionFinal = '' filterActionFinal = ''
@ -233,9 +235,6 @@ def retrieveFileName():
global previousState global previousState
previousState = [] previousState = []
global previousStateActive
previousStateActive = []
global yData global yData
yData = [] yData = []
@ -331,11 +330,16 @@ def retrieveFileName():
target_namesLoc = [] target_namesLoc = []
global names_labels
names_labels = []
DataRawLength = -1 DataRawLength = -1
DataRawLengthTest = -1 DataRawLengthTest = -1
if data['fileName'] == 'HeartC': if data['fileName'] == 'HeartC':
CollectionDB = mongo.db.HeartC.find() CollectionDB = mongo.db.HeartC.find()
names_labels.append('Healthy')
names_labels.append('Diseased')
elif data['fileName'] == 'StanceC': elif data['fileName'] == 'StanceC':
StanceTest = True StanceTest = True
CollectionDB = mongo.db.StanceC.find() CollectionDB = mongo.db.StanceC.find()
@ -1027,9 +1031,6 @@ def EnsembleModel (Models, keyRetrieved):
global XDataTest, yDataTest global XDataTest, yDataTest
global scores global scores
global previousState global previousState
global previousStateActive
global keySpec
global keySpecInternal
global crossValidation global crossValidation
global keyData global keyData
scores = [] scores = []
@ -1049,169 +1050,193 @@ def EnsembleModel (Models, keyRetrieved):
global numberIDRFGlob global numberIDRFGlob
global numberIDGradBGlob global numberIDGradBGlob
all_classifiers = []
columnsInit = []
columnsInit = [XData.columns.get_loc(c) for c in XData.columns if c in XData]
temp = allParametersPerformancePerModel[1]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamKNN = pd.DataFrame.from_dict(tempDic)
dfParamKNNFilt = dfParamKNN.iloc[:,0]
for eachelem in numberIDKNNGlob:
arg = dfParamKNNFilt[eachelem]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), KNeighborsClassifier().set_params(**arg)))
temp = allParametersPerformancePerModel[5]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamLR = pd.DataFrame.from_dict(tempDic)
dfParamLRFilt = dfParamLR.iloc[:,0]
for eachelem in numberIDLRGlob:
arg = dfParamLRFilt[eachelem-LRModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), LogisticRegression(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[9]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamMLP = pd.DataFrame.from_dict(tempDic)
dfParamMLPFilt = dfParamMLP.iloc[:,0]
for eachelem in numberIDMLPGlob:
arg = dfParamMLPFilt[eachelem-MLPModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), MLPClassifier(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[13]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamRF = pd.DataFrame.from_dict(tempDic)
dfParamRFFilt = dfParamRF.iloc[:,0]
for eachelem in numberIDRFGlob:
arg = dfParamRFFilt[eachelem-RFModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), RandomForestClassifier(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[17]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamGradB = pd.DataFrame.from_dict(tempDic)
dfParamGradBFilt = dfParamGradB.iloc[:,0]
for eachelem in numberIDGradBGlob:
arg = dfParamGradBFilt[eachelem-GradBModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), GradientBoostingClassifier(random_state=RANDOM_SEED).set_params(**arg)))
global sclf
sclf = 0
sclf = EnsembleVoteClassifier(clfs=all_classifiers,
voting='soft')
global PerClassResultsClass0
PerClassResultsClass0 = []
global PerClassResultsClass1
PerClassResultsClass1 = []
nested_score = model_selection.cross_val_score(sclf, X=XData, y=yData, cv=crossValidation, scoring=make_scorer(classification_report_with_accuracy_score))
PerClassResultsClass0Con = pd.concat(PerClassResultsClass0, axis=1, sort=False)
PerClassResultsClass1Con = pd.concat(PerClassResultsClass1, axis=1, sort=False)
averageClass0 = PerClassResultsClass0Con.mean(axis=1)
averageClass1 = PerClassResultsClass1Con.mean(axis=1)
y_pred = cross_val_predict(sclf, XData, yData, cv=crossValidation)
conf_mat = confusion_matrix(yData, y_pred)
cm = conf_mat.astype('float') / conf_mat.sum(axis=1)[:, np.newaxis]
cm.diagonal()
if (keyRetrieved == 0): if (keyRetrieved == 0):
all_classifiers = [] scores.append(cm[0][0])
columnsInit = [] scores.append(cm[1][1])
columnsInit = [XData.columns.get_loc(c) for c in XData.columns if c in XData] scores.append(cm[0][0])
scores.append(cm[1][1])
temp = allParametersPerformancePerModel[1] scores.append(averageClass0.precision)
scores.append(averageClass1.precision)
temp = temp['params'] scores.append(averageClass0.precision)
temp = {int(k):v for k,v in temp.items()} scores.append(averageClass1.precision)
tempDic = { scores.append(averageClass0.recall)
'params': temp scores.append(averageClass1.recall)
} scores.append(averageClass0.recall)
dfParamKNN = pd.DataFrame.from_dict(tempDic) scores.append(averageClass1.recall)
dfParamKNNFilt = dfParamKNN.iloc[:,0] scores.append(averageClass0['f1-score'])
for eachelem in numberIDKNNGlob: scores.append(averageClass1['f1-score'])
arg = dfParamKNNFilt[eachelem] scores.append(averageClass0['f1-score'])
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), KNeighborsClassifier().set_params(**arg))) scores.append(averageClass1['f1-score'])
temp = allParametersPerformancePerModel[5] previousState.append(scores[0])
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamLR = pd.DataFrame.from_dict(tempDic)
dfParamLRFilt = dfParamLR.iloc[:,0]
for eachelem in numberIDLRGlob:
arg = dfParamLRFilt[eachelem-LRModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), LogisticRegression(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[9]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamMLP = pd.DataFrame.from_dict(tempDic)
dfParamMLPFilt = dfParamMLP.iloc[:,0]
for eachelem in numberIDMLPGlob:
arg = dfParamMLPFilt[eachelem-MLPModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), MLPClassifier(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[13]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamRF = pd.DataFrame.from_dict(tempDic)
dfParamRFFilt = dfParamRF.iloc[:,0]
for eachelem in numberIDRFGlob:
arg = dfParamRFFilt[eachelem-RFModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), RandomForestClassifier(random_state=RANDOM_SEED).set_params(**arg)))
temp = allParametersPerformancePerModel[17]
temp = temp['params']
temp = {int(k):v for k,v in temp.items()}
tempDic = {
'params': temp
}
dfParamGradB = pd.DataFrame.from_dict(tempDic)
dfParamGradBFilt = dfParamGradB.iloc[:,0]
for eachelem in numberIDGradBGlob:
arg = dfParamGradBFilt[eachelem-GradBModelsCount]
all_classifiers.append(make_pipeline(ColumnSelector(cols=columnsInit), GradientBoostingClassifier(random_state=RANDOM_SEED).set_params(**arg)))
global sclf
sclf = 0
sclf = EnsembleVoteClassifier(clfs=all_classifiers,
voting='soft')
keySpec = 0
if (keySpec == 0 or keySpec == 1):
num_cores = multiprocessing.cpu_count()
inputsSc = ['accuracy','precision','recall','f1']
flat_results = Parallel(n_jobs=num_cores)(delayed(solve)(sclf,keyData,keySpec,keySpecInternal,previousState,previousStateActive,XData,yData,crossValidation,item,index) for index, item in enumerate(inputsSc))
scores = [item for sublist in flat_results for item in sublist]
if (keySpec == 0):
previousState = []
previousState.append(scores[1]) previousState.append(scores[1])
previousState.append(scores[3]) previousState.append(scores[4])
previousState.append(scores[5]) previousState.append(scores[5])
previousState.append(scores[7]) previousState.append(scores[8])
previousStateActive = [] previousState.append(scores[9])
previousStateActive.append(scores[0]) previousState.append(scores[12])
previousStateActive.append(scores[2]) previousState.append(scores[13])
previousStateActive.append(scores[4])
previousStateActive.append(scores[6])
elif (keySpec == 1):
if (keySpecInternal == 1):
previousStateActive = []
previousStateActive.append(scores[0])
previousStateActive.append(scores[2])
previousStateActive.append(scores[4])
previousStateActive.append(scores[6])
else:
previousStateActive = []
previousStateActive.append(scores[0])
previousStateActive.append(scores[2])
previousStateActive.append(scores[4])
previousStateActive.append(scores[6])
previousState = []
previousState.append(scores[1])
previousState.append(scores[3])
previousState.append(scores[5])
previousState.append(scores[7])
else: else:
scores = [] scores.append(cm[0][0])
previousState = [] scores.append(cm[1][1])
scores.append(previousStateActive[0]) if (cm[0][0] > previousState[0]):
scores.append(previousStateActive[0]) scores.append(cm[0][0])
previousState.append(previousStateActive[0]) previousState[0] = cm[0][0]
scores.append(previousStateActive[2]) else:
scores.append(previousStateActive[2]) scores.append(previousState[0])
previousState.append(previousStateActive[2]) if (cm[1][1] > previousState[1]):
scores.append(previousStateActive[4]) scores.append(cm[1][1])
scores.append(previousStateActive[4]) previousState[1] = cm[1][1]
previousState.append(previousStateActive[4]) else:
scores.append(previousStateActive[6]) scores.append(previousState[1])
scores.append(previousStateActive[6]) scores.append(averageClass0.precision)
previousState.append(previousStateActive[6]) scores.append(averageClass1.precision)
print(scores) if (averageClass0.precision > previousState[2]):
scores.append(averageClass0.precision)
previousState[2] = averageClass0.precision
else:
scores.append(previousState[2])
if (averageClass1.precision > previousState[3]):
scores.append(averageClass1.precision)
previousState[3] = averageClass1.precision
else:
scores.append(previousState[3])
scores.append(averageClass0.recall)
scores.append(averageClass1.recall)
if (averageClass0.recall > previousState[4]):
scores.append(averageClass0.recall)
previousState[4] = averageClass0.recall
else:
scores.append(previousState[4])
if (averageClass1.recall > previousState[5]):
scores.append(averageClass1.recall)
previousState[5] = averageClass1.recall
else:
scores.append(previousState[5])
scores.append(averageClass0['f1-score'])
scores.append(averageClass1['f1-score'])
if (averageClass0['f1-score'] > previousState[6]):
scores.append(averageClass0['f1-score'])
previousState[6] = averageClass0['f1-score']
else:
scores.append(previousState[6])
if (averageClass1['f1-score'] > previousState[7]):
scores.append(averageClass1['f1-score'])
previousState[7] = averageClass1['f1-score']
else:
scores.append(previousState[7])
return 'Okay' return 'Okay'
def solve(sclf,keyData,keySpec,keySpecInternal,previousStateLoc,previousStateActiveLoc,XData,yData,crossValidation,scoringIn,loop): # Sending the final results to be visualized as a line plot
scoresLoc = [] @app.route('/data/SendFinalResultsBacktoVisualize', methods=["GET", "POST"])
if (keySpec == 0): def SendToPlotFinalResults():
temp = model_selection.cross_val_score(sclf, XData, yData, cv=crossValidation, scoring=scoringIn, n_jobs=-1) global scores
scoresLoc.append(temp.mean()) response = {
if (keyData == 1): 'FinalResults': scores
if (loop == 0): }
scoresLoc.append(previousStateLoc[0]) return jsonify(response)
elif (loop == 1):
scoresLoc.append(previousStateLoc[1]) def classification_report_with_accuracy_score(y_true, y_pred):
elif (loop == 2): global PerClassResultsClass0
scoresLoc.append(previousStateLoc[2]) global PerClassResultsClass1
else: PerClassResultsLocal = pd.DataFrame.from_dict(classification_report(y_true, y_pred, output_dict=True))
scoresLoc.append(previousStateLoc[3]) Filter_PerClassResultsLocal0 = PerClassResultsLocal['0']
else: Filter_PerClassResultsLocal0 = Filter_PerClassResultsLocal0[:-1]
scoresLoc.append(temp.mean()) Filter_PerClassResultsLocal1 = PerClassResultsLocal['1']
else: Filter_PerClassResultsLocal1 = Filter_PerClassResultsLocal1[:-1]
if (keySpecInternal == 1): PerClassResultsClass0.append(Filter_PerClassResultsLocal0)
temp = model_selection.cross_val_score(sclf, XData, yData, cv=crossValidation, scoring=scoringIn, n_jobs=-1) PerClassResultsClass1.append(Filter_PerClassResultsLocal1)
scoresLoc.append(temp.mean()) return accuracy_score(y_true, y_pred) # return accuracy score
if (loop == 0):
scoresLoc.append(previousStateLoc[0])
elif (loop == 1):
scoresLoc.append(previousStateLoc[1])
elif (loop == 2):
scoresLoc.append(previousStateLoc[2])
else:
scoresLoc.append(previousStateLoc[3])
else:
temp = model_selection.cross_val_score(sclf, XData, yData, cv=crossValidation, scoring=scoringIn, n_jobs=-1)
scoresLoc.append(temp.mean())
scoresLoc.append(temp.mean())
return scoresLoc
def returnResults(ModelSpaceMDS,ModelSpaceTSNE,ModelSpaceUMAP,PredictionProbSel): def returnResults(ModelSpaceMDS,ModelSpaceTSNE,ModelSpaceUMAP,PredictionProbSel):
global Results global Results
global AllTargets global AllTargets
global names_labels
Results = [] Results = []
parametersGen = PreprocessingParam() parametersGen = PreprocessingParam()
@ -1237,6 +1262,7 @@ def returnResults(ModelSpaceMDS,ModelSpaceTSNE,ModelSpaceUMAP,PredictionProbSel)
Results.append(json.dumps(ModelSpaceTSNE)) Results.append(json.dumps(ModelSpaceTSNE))
Results.append(json.dumps(ModelSpaceUMAP)) Results.append(json.dumps(ModelSpaceUMAP))
Results.append(json.dumps(PredictionProbSel)) Results.append(json.dumps(PredictionProbSel))
Results.append(json.dumps(names_labels))
return Results return Results
@ -2212,6 +2238,7 @@ def CrossMutateResults(ModelSpaceMDSCM,ModelSpaceTSNECM,ModelSpaceUMAPCM,Predict
ResultsCM.append(json.dumps(ModelSpaceTSNECM)) ResultsCM.append(json.dumps(ModelSpaceTSNECM))
ResultsCM.append(json.dumps(ModelSpaceUMAPCM)) ResultsCM.append(json.dumps(ModelSpaceUMAPCM))
ResultsCM.append(json.dumps(PredictionProbSel)) ResultsCM.append(json.dumps(PredictionProbSel))
ResultsCM.append(json.dumps(names_labels))
return ResultsCM return ResultsCM
@ -2427,4 +2454,15 @@ def SendPredictSelEnsem():
response = { response = {
'PredictSelEnsem': ResultsSelPredEnsem 'PredictSelEnsem': ResultsSelPredEnsem
} }
return jsonify(response) return jsonify(response)
@cross_origin(origin='localhost',headers=['Content-Type','Authorization'])
@app.route('/data/ServerRequestSelPoin', methods=["GET", "POST"])
def RetrieveSelClassifiersID():
ClassifierIDsList = request.get_data().decode('utf8').replace("'", '"')
#ComputeMetricsForSel(ClassifierIDsList)
ClassifierIDCleaned = json.loads(ClassifierIDsList)
EnsembleModel(ClassifierIDsList, 1)
return 'Everything Okay'
Loading…
Cancel
Save