Commit aef42614 authored by Shalitha Deshan Jayasekara's avatar Shalitha Deshan Jayasekara 🏘

Merge branch 'IT18523256_GunarathnaK.A.G.I.P.T' into 'master'

Adding new Python modules and SVm

See merge request !20
parents 3a84bd31 b15f897a
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CsvFileAttributes">
<option name="attributeMap">
<map>
<entry key="\diet_plan\weight_data.csv">
<value>
<Attribute>
<option name="separator" value="," />
</Attribute>
</value>
</entry>
</map>
</option>
</component>
</project>
\ No newline at end of file
import numpy
from flask import Flask
from flask import request
from flask_cors import CORS
from sklearn import preprocessing
import pandas as pd
le = preprocessing.LabelEncoder()
dataDf = pd.read_csv("weight_data_with_headers.csv")
le.fit(dataDf['breed'])
dataDf['breed'] = le.transform(dataDf['breed'])
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
X = dataDf[['breed', 'height', 'weight']]
y = dataDf['outcome']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
from sklearn.svm import SVC
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)
app = Flask(__name__)
cors = CORS(app)
@app.route("/predict", methods =['POST'])
def predict():
data = numpy.array(request.get_json())
print(data)
prediction = clf.predict(data)
print(prediction)
return {"pred": str(prediction[0])}
if __name__ == '__main__':
app.run(debug=True, port=5003, host="0.0.0.0")
import numpy
from flask import Flask
from flask import request
from flask_cors import CORS
from sklearn import preprocessing
import pandas as pd
le = preprocessing.LabelEncoder()
dataDf = pd.read_csv("weight_data_with_headers_puppy.csv")
le.fit(dataDf['breed'])
dataDf['breed'] = le.transform(dataDf['breed'])
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
X = dataDf[['breed', 'month', 'weight']]
y = dataDf['outcome']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
from sklearn.svm import SVC
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)
app = Flask(__name__)
cors = CORS(app)
@app.route("/predict", methods =['POST'])
def predict():
data = numpy.array(request.get_json())
print(data)
prediction = clf.predict(data)
print(prediction)
return {"pred": str(prediction[0])}
if __name__ == '__main__':
app.run(debug=True, port=5004, host="0.0.0.0")
[[159 15 1]
[ 35 137 26]
[ 0 14 155]]
\ No newline at end of file
[[124 46 5]
[ 66 79 53]
[ 24 47 98]]
\ No newline at end of file
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
sns.set_style("whitegrid")
plt.style.use("fivethirtyeight")
dataDf = pd.read_csv("weight_data_with_headers.csv")
le.fit(dataDf['breed'])
print(le.classes_)
dataDf['breed'] = le.transform(dataDf['breed'])
print(dataDf.head())
sns.pairplot(dataDf)
plt.show()
sns.heatmap(dataDf.corr(), annot=True)
plt.show()
corr = dataDf.corr(method='pearson')
print(corr)
from sklearn.model_selection import train_test_split
X = dataDf[['breed', 'height', 'weight']]
y = dataDf['outcome']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
from sklearn.linear_model import LogisticRegression
# LOGISTIC REGRESSION
clf = LogisticRegression(random_state=0, max_iter=2000, solver='lbfgs').fit(X_train, y_train)
predictions = clf.predict(X_test)
score = clf.score(X_test, y_test)
print("Logistic regression score: ", score)
from sklearn import metrics
cm = metrics.confusion_matrix(y_test, predictions)
print(cm)
plt.figure(figsize=(9,9))
sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r');
plt.ylabel('Actual label');
plt.xlabel('Predicted label');
all_sample_title = 'Accuracy Score: {0}'.format(score)
plt.title(all_sample_title, size = 15)
plt.show()
# SVM
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X, y)
score = clf.score(X, y, sample_weight=None)
print("SVM score: ", score)
predictions = clf.predict(X_test)
cm = metrics.confusion_matrix(y_test, predictions)
print(cm)
plt.figure(figsize=(9,9))
sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r');
plt.ylabel('Actual label');
plt.xlabel('Predicted label');
all_sample_title = 'Accuracy Score: {0}'.format(score)
plt.title(all_sample_title, size = 15)
plt.show()
#import pandas #import pandas
import pandas as pd import pandas as pd
#creating columns for dataset preview
col_names = ['breed', 'age', 'weight', 'label'] col_names = ['breed', 'age', 'weight', 'label']
dog_breeds = ["german_sheppard", "labrador", "pomeranian", "husky", "golden_retriever", "poodle", "bulldog", "shiba", "rottweiler","boxer","Dobermen"] dog_breeds = ["german_sheppard", "labrador", "pomeranian", "husky", "golden_retriever", "poodle", "bulldog", "shiba", "rottweiler"]
# load dataset
# reading data set
pima = pd.read_csv("weight_data.csv", header=None, names=col_names) pima = pd.read_csv("weight_data.csv", header=None, names=col_names)
print("===================") print("===================")
print("Dataset head") print("Dataset head")
print("===================") print("===================")
#previewing the head of data set
print(pima.head()) print(pima.head())
#split dataset in to features and target variable
#split dataset in features and target variable
feature_cols = ['breed', 'age', 'weight'] feature_cols = ['breed', 'age', 'weight']
X = pima[feature_cols] # Features X = pima[feature_cols] # Features
y = pima.label # Target variable y = pima.label # Target variable
#Use sklearn to train dataset
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0) X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)
# import the class # import the class
#use logistic Regression
from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LogisticRegression
# instantiate the model (using the default parameters) # instantiate the model (using the default parameters)
...@@ -32,6 +27,7 @@ logreg = LogisticRegression() ...@@ -32,6 +27,7 @@ logreg = LogisticRegression()
# fit the model with data # fit the model with data
logreg.fit(X_train,y_train) logreg.fit(X_train,y_train)
#
y_pred=logreg.predict(X_test) y_pred=logreg.predict(X_test)
# import the metrics class # import the metrics class
...@@ -40,18 +36,16 @@ cnf_matrix = metrics.confusion_matrix(y_test, y_pred) ...@@ -40,18 +36,16 @@ cnf_matrix = metrics.confusion_matrix(y_test, y_pred)
print("===================") print("===================")
print("Confusion matrix") print("Confusion matrix")
print("===================") print("===================")
#printing a confusion matrix
print(cnf_matrix) print(cnf_matrix)
print("===================") print("===================")
print("Accuracy") print("Accuracy")
print("===================") print("===================")
#printing the accuracy of model
print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
# print("Precision:",metrics.precision_score(y_test, y_pred)) # print("Precision:",metrics.precision_score(y_test, y_pred))
# print("Recall:",metrics.recall_score(y_test, y_pred)) # print("Recall:",metrics.recall_score(y_test, y_pred))
# Prediction test # Prediction test
y_prediction_test = logreg.predict([[5,4,22]]) y_prediction_test = logreg.predict([[1,1,3]])
y_labels = ["Overweight", "Normal", "Underweight"] y_labels = ["Overweight", "Normal", "Underweight"]
print(y_labels[y_prediction_test[0]]) print(y_labels[y_prediction_test[0]])
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment