Python code for PSO to optimise SVM parameters
I'm trying to implement Particle swarm optimization on support vector machine (SVM) to optimizing cost and gamma parameters (Radial basis function) to improve the accuracy.The SVM program is taking data from mysql db and is working fine.Now I need a PSO code to optimize the cost and gamma parameters and use it in svm program.
following are the svm and pso codes. Svm works fine but the PSO code does not work.
the code is written in python.
Please help..
SVM code:
import MySQLdb
import cgi
import cgitb
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing, cross_validation, svm
from sklearn.svm import SVR
import mysql.connector as sql
import pandas as pd
cgitb.enable()
print 'Content-type: text/htmlrnr'
form = cgi.FieldStorage()
e1= form.getvalue('EARNING_PER_SHARE', '')
e2 = form.getvalue('CASH_INVESTMENT', '')
e3 = form.getvalue('CURRENT_LIABILITY', '')
e4 = form.getvalue('TOTAL_REVENUE', '')
e5 = form.getvalue('GROSS_PROFIT', '')
db = MySQLdb.connect(host="127.0.0.1", db="cisco", user="root", passwd="")
cursor = db.cursor()
cursor.execute("""
INSERT INTO table1 (EARNING_PER_SHARE, CASH_INVESTMENT, CURRENT_LIABILITY,
TOTAL_REVENUE,GROSS_PROFIT)
VALUES (%s, %s, %s, %s, %s)
""", (e1, e2, e3, e4,e5))
db.commit()
db.close()
db_connection = sql.connect(host='127.0.0.1', database='cisco', user='root',
password='')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table1')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
np = df.as_matrix()
X = df.drop([4], 1)
np1 = X.as_matrix()
y = df[4]
np2 = y.as_matrix()
x_train, x_test, y_train, y_test = train_test_split(np1, np2, test_size=0.3)
clf = svm.SVR()
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
for k in ['rbf']:
clf = svm.SVR(kernel=k, C=100, gamma=0.0001)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
a = clf.predict(np1)
print ('npredicted values')
print (a)
print ('nreal values')
print (np2)
PSO code:
def fitness_function(a,x,np2,np1,C,gamma,):
C = x[0]
gamma = x[1]
clf = svm.SVR(kernel=k, C=10, gamma=0.0001,swarmsize=50)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
mse = sqrt(mean_squared_error(np2, a))
return mse
lb = [10, 0.0001]
ub = [1000,0.1]
xopt, fopt = pso(fitness_function, lb, ub)
I want to use RMSE as the fitness function but I think fitness function has to include the parameters that is to be optimized. But, in SVR, the objective function is too complicated to write in python.
python svm pso
add a comment |
I'm trying to implement Particle swarm optimization on support vector machine (SVM) to optimizing cost and gamma parameters (Radial basis function) to improve the accuracy.The SVM program is taking data from mysql db and is working fine.Now I need a PSO code to optimize the cost and gamma parameters and use it in svm program.
following are the svm and pso codes. Svm works fine but the PSO code does not work.
the code is written in python.
Please help..
SVM code:
import MySQLdb
import cgi
import cgitb
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing, cross_validation, svm
from sklearn.svm import SVR
import mysql.connector as sql
import pandas as pd
cgitb.enable()
print 'Content-type: text/htmlrnr'
form = cgi.FieldStorage()
e1= form.getvalue('EARNING_PER_SHARE', '')
e2 = form.getvalue('CASH_INVESTMENT', '')
e3 = form.getvalue('CURRENT_LIABILITY', '')
e4 = form.getvalue('TOTAL_REVENUE', '')
e5 = form.getvalue('GROSS_PROFIT', '')
db = MySQLdb.connect(host="127.0.0.1", db="cisco", user="root", passwd="")
cursor = db.cursor()
cursor.execute("""
INSERT INTO table1 (EARNING_PER_SHARE, CASH_INVESTMENT, CURRENT_LIABILITY,
TOTAL_REVENUE,GROSS_PROFIT)
VALUES (%s, %s, %s, %s, %s)
""", (e1, e2, e3, e4,e5))
db.commit()
db.close()
db_connection = sql.connect(host='127.0.0.1', database='cisco', user='root',
password='')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table1')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
np = df.as_matrix()
X = df.drop([4], 1)
np1 = X.as_matrix()
y = df[4]
np2 = y.as_matrix()
x_train, x_test, y_train, y_test = train_test_split(np1, np2, test_size=0.3)
clf = svm.SVR()
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
for k in ['rbf']:
clf = svm.SVR(kernel=k, C=100, gamma=0.0001)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
a = clf.predict(np1)
print ('npredicted values')
print (a)
print ('nreal values')
print (np2)
PSO code:
def fitness_function(a,x,np2,np1,C,gamma,):
C = x[0]
gamma = x[1]
clf = svm.SVR(kernel=k, C=10, gamma=0.0001,swarmsize=50)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
mse = sqrt(mean_squared_error(np2, a))
return mse
lb = [10, 0.0001]
ub = [1000,0.1]
xopt, fopt = pso(fitness_function, lb, ub)
I want to use RMSE as the fitness function but I think fitness function has to include the parameters that is to be optimized. But, in SVR, the objective function is too complicated to write in python.
python svm pso
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38
add a comment |
I'm trying to implement Particle swarm optimization on support vector machine (SVM) to optimizing cost and gamma parameters (Radial basis function) to improve the accuracy.The SVM program is taking data from mysql db and is working fine.Now I need a PSO code to optimize the cost and gamma parameters and use it in svm program.
following are the svm and pso codes. Svm works fine but the PSO code does not work.
the code is written in python.
Please help..
SVM code:
import MySQLdb
import cgi
import cgitb
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing, cross_validation, svm
from sklearn.svm import SVR
import mysql.connector as sql
import pandas as pd
cgitb.enable()
print 'Content-type: text/htmlrnr'
form = cgi.FieldStorage()
e1= form.getvalue('EARNING_PER_SHARE', '')
e2 = form.getvalue('CASH_INVESTMENT', '')
e3 = form.getvalue('CURRENT_LIABILITY', '')
e4 = form.getvalue('TOTAL_REVENUE', '')
e5 = form.getvalue('GROSS_PROFIT', '')
db = MySQLdb.connect(host="127.0.0.1", db="cisco", user="root", passwd="")
cursor = db.cursor()
cursor.execute("""
INSERT INTO table1 (EARNING_PER_SHARE, CASH_INVESTMENT, CURRENT_LIABILITY,
TOTAL_REVENUE,GROSS_PROFIT)
VALUES (%s, %s, %s, %s, %s)
""", (e1, e2, e3, e4,e5))
db.commit()
db.close()
db_connection = sql.connect(host='127.0.0.1', database='cisco', user='root',
password='')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table1')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
np = df.as_matrix()
X = df.drop([4], 1)
np1 = X.as_matrix()
y = df[4]
np2 = y.as_matrix()
x_train, x_test, y_train, y_test = train_test_split(np1, np2, test_size=0.3)
clf = svm.SVR()
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
for k in ['rbf']:
clf = svm.SVR(kernel=k, C=100, gamma=0.0001)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
a = clf.predict(np1)
print ('npredicted values')
print (a)
print ('nreal values')
print (np2)
PSO code:
def fitness_function(a,x,np2,np1,C,gamma,):
C = x[0]
gamma = x[1]
clf = svm.SVR(kernel=k, C=10, gamma=0.0001,swarmsize=50)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
mse = sqrt(mean_squared_error(np2, a))
return mse
lb = [10, 0.0001]
ub = [1000,0.1]
xopt, fopt = pso(fitness_function, lb, ub)
I want to use RMSE as the fitness function but I think fitness function has to include the parameters that is to be optimized. But, in SVR, the objective function is too complicated to write in python.
python svm pso
I'm trying to implement Particle swarm optimization on support vector machine (SVM) to optimizing cost and gamma parameters (Radial basis function) to improve the accuracy.The SVM program is taking data from mysql db and is working fine.Now I need a PSO code to optimize the cost and gamma parameters and use it in svm program.
following are the svm and pso codes. Svm works fine but the PSO code does not work.
the code is written in python.
Please help..
SVM code:
import MySQLdb
import cgi
import cgitb
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing, cross_validation, svm
from sklearn.svm import SVR
import mysql.connector as sql
import pandas as pd
cgitb.enable()
print 'Content-type: text/htmlrnr'
form = cgi.FieldStorage()
e1= form.getvalue('EARNING_PER_SHARE', '')
e2 = form.getvalue('CASH_INVESTMENT', '')
e3 = form.getvalue('CURRENT_LIABILITY', '')
e4 = form.getvalue('TOTAL_REVENUE', '')
e5 = form.getvalue('GROSS_PROFIT', '')
db = MySQLdb.connect(host="127.0.0.1", db="cisco", user="root", passwd="")
cursor = db.cursor()
cursor.execute("""
INSERT INTO table1 (EARNING_PER_SHARE, CASH_INVESTMENT, CURRENT_LIABILITY,
TOTAL_REVENUE,GROSS_PROFIT)
VALUES (%s, %s, %s, %s, %s)
""", (e1, e2, e3, e4,e5))
db.commit()
db.close()
db_connection = sql.connect(host='127.0.0.1', database='cisco', user='root',
password='')
db_cursor = db_connection.cursor()
db_cursor.execute('SELECT * FROM table1')
table_rows = db_cursor.fetchall()
df = pd.DataFrame(table_rows)
np = df.as_matrix()
X = df.drop([4], 1)
np1 = X.as_matrix()
y = df[4]
np2 = y.as_matrix()
x_train, x_test, y_train, y_test = train_test_split(np1, np2, test_size=0.3)
clf = svm.SVR()
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
for k in ['rbf']:
clf = svm.SVR(kernel=k, C=100, gamma=0.0001)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
a = clf.predict(np1)
print ('npredicted values')
print (a)
print ('nreal values')
print (np2)
PSO code:
def fitness_function(a,x,np2,np1,C,gamma,):
C = x[0]
gamma = x[1]
clf = svm.SVR(kernel=k, C=10, gamma=0.0001,swarmsize=50)
clf.fit(np1, np2)
confidence = clf.score(np1, np2)
print(k,confidence)
mse = sqrt(mean_squared_error(np2, a))
return mse
lb = [10, 0.0001]
ub = [1000,0.1]
xopt, fopt = pso(fitness_function, lb, ub)
I want to use RMSE as the fitness function but I think fitness function has to include the parameters that is to be optimized. But, in SVR, the objective function is too complicated to write in python.
python svm pso
python svm pso
edited Apr 13 '17 at 5:33
Manjiri Munghate
asked Apr 12 '17 at 18:29
Manjiri MunghateManjiri Munghate
62
62
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38
add a comment |
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43377055%2fpython-code-for-pso-to-optimise-svm-parameters%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43377055%2fpython-code-for-pso-to-optimise-svm-parameters%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What specifically isn't working?
– rlb.usa
Apr 12 '17 at 18:53
the PSO code is not working.I want to use RMSE as the fitness function and get the optimised value of cost and gamma.5-fold cross-validation can also be used to estimate the RMSE for a given set of parameters.
– Manjiri Munghate
Apr 13 '17 at 5:38