Commit ff1483e2 authored by inusha maduranga's avatar inusha maduranga

Machine learnning flask project

parent abc10597
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
flask = "*"
flask-sqlalchemy = "*"
flask-marshmallow = "*"
marshmallow-sqlalchemy = "*"
[requires]
python_version = "3.7"
This diff is collapsed.
from flask import Flask, request, jsonify , render_template, redirect
import os
from flask_mysqldb import MySQL
import yaml
import model
import numpy as np
# init app
app = Flask(__name__)
# Configure db
db = yaml.load(open('db.yaml')) # Load data from db.yaml file
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
@app.route('/progress/<uniqueId>', methods = ['get'])
def calculate_progress(uniqueId):
gradient_list = []
#Create connection to MYSql
cur = mysql.connection.cursor()
#get paper numbers of the student
cur.execute("SELECT PAPER_NO FROM paper_result_student_final WHERE UNIQUE_ID="+uniqueId)
paper_no_list = [item[0] for item in cur.fetchall()] # Fetched data add to the list
for i in range(0, len(paper_no_list)): # get paper number one by one
#Initialize list
weight_list = []
time_list = []
time_list_new = []
#get WEIGHT using id and paper number
cur.execute("SELECT WEIGHT FROM paper_result_student WHERE UNIQUE_ID= " + uniqueId + " AND PAPER_NO= " + str(paper_no_list[i]))
weight_list = [item[0] for item in cur.fetchall()]
for w in range(0, len(weight_list)):
weight_list[i] = int(weight_list[w]) #convert string to int
#get TIME using id and paper number
cur.execute("SELECT TIME FROM paper_result_student WHERE UNIQUE_ID= " + uniqueId + " AND PAPER_NO= " + str(paper_no_list[i]))
time_list = [item[0] for item in cur.fetchall()] #Tuple convert toList
for t in range(0, len(time_list)):
(h, m, s) = time_list[t].split(':') #Time split to decimal number
time_in_decimal = int(h) * 3600 + int(m) * 60 + int(s)
time_list_new.append(time_in_decimal)
#pass weight_list and time_list_new to the Machine learning MODEL and get gradient
gradient = model.calculateGradientLinerRegressionAndSVR(weight_list , time_list_new)
gradient_list.append(float(gradient)) #Gradient convert to float and add to the list
#Close the db connections
cur.close()
#gradient_list Convert to numpy array
arr = np.array(gradient_list)
print(arr.tolist())
return({'learningProgresList': arr.tolist()})
# return render_template('index2.html', students=data )
# Run Server
if __name__ == '__main__':
app.run(debug=True)
mysql_host: 'localhost'
mysql_user: 'root'
# Enter your password in field below
mysql_password: '123'
mysql_db: 'elearning_db'
\ No newline at end of file
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.svm import SVR
def calculateGradientLinerRegressionAndSVR(x_list,y_list):
# -------- Preprocessing Input data -------------------------------------------------------
# Importing the dataset
X = np.array(x_list)
Y = np.array(y_list)
# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
# Reshape (Gives a new shape to an array without changing its data. | 1D Array to 2D Array)
X_train= X_train.reshape(-1, 1)
y_train= y_train.reshape(-1, 1)
X_test= X_test.reshape(-1, 1)
y_test= y_test.reshape(-1, 1)
# -------- Build the Model ***Linear Regression(LR)*****---------------------------------
# Fitting Simple Linear Regression to the Training set
regressor_LR = LinearRegression()
regressor_LR.fit(X_train,y_train) #training the algorithm
# Predicting the Test set result
y_pred = regressor_LR.predict(X_test)
# Get Gradient
gradient_LR = regressor_LR.coef_
# Calulate r-Squared
r_squared_linear_regression = r2_score(y_test, y_pred)
# Visualising the Training set result
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor_LR.predict(X_train), color = 'blue')
plt.title("Linear Regression")
plt.xlabel('Allocated weight for question' )
plt.ylabel('Spend time per question')
# plt.show()
# -------- Build the Model ***Support Vector Regression(SVR)*****-------------------------------------
# Fitting Support Vector Regression to the Training set
regressor_SVR = SVR(kernel = 'linear')
regressor_SVR.fit(X_train,y_train) #training the algorithm
# Predicting the Test set result
y_pred = regressor_SVR.predict(X_test)
# Get Gradient
gradient_SVR = regressor_SVR.coef_
# Calulate r-Squared
r_squared_support_vector_regression = r2_score(y_test, y_pred)
# Visualising the Training set result
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor_SVR.predict(X_train), color = 'blue')
plt.title("Support Vector Regression")
plt.xlabel('Allocated weight for question' )
plt.ylabel('Spend time per question')
# plt.show()
# Compare and add best gradient to the list
if r_squared_linear_regression >= r_squared_support_vector_regression:
print("linear_regression_Gardient = ",gradient_LR)
print("linear_regression_Gardient = ",gradient_SVR)
print("r_squared_linear_regression = ",r_squared_linear_regression)
print("r_squared_support_vector_regression = ",r_squared_support_vector_regression)
return gradient_LR
else:
print("support_vector_regression_Gardient = ",gradient_LR)
print("support_vector_regression_Gardient = ",gradient_SVR)
print("r_squared_linear_regression = ",r_squared_linear_regression)
print("r_squared_support_vector_regression = ",r_squared_support_vector_regression)
return gradient_SVR
\ No newline at end of file
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