Skip to content

Commit

Permalink
added some interactive graphs
Browse files Browse the repository at this point in the history
  • Loading branch information
Danushka2 committed Oct 10, 2020
1 parent 51b8cc0 commit d5e3dff
Show file tree
Hide file tree
Showing 10 changed files with 467 additions and 121 deletions.
Binary file added ClusteringPredict.pkl
Binary file not shown.
169 changes: 154 additions & 15 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
from dataset.cleanDs import cleanDs


import plotly
import plotly.graph_objs as go
import json
import pandas as pd

app = Flask(__name__)
model = pickle.load(open('testModel.pkl', 'rb'))

Expand All @@ -15,13 +20,55 @@

@app.route('/')
def home():
return render_template('index.html', url ='/static/images/line_plot.jpg')
# return render_template('index.html', url ='/static/images/line_plot.jpg')

labels = df['Genre']
values = df['Global_Sales']

graphs = [
dict(
data=[
dict(
x = df['Genre'],
y = df['Global_Sales'],
type='bar'
),
],
layout=dict(
title='Bar Chart'
)
),

dict(
data = [go.Pie(
labels=labels, values=values, hole=.3
)
],
layout=dict(
title='Pie Chart'
)
)
]

# Add "ids" to each of the graphs to pass up to the client
# for templating
ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)]

# Convert the figures to JSON
# PlotlyJSONEncoder appropriately converts pandas, datetime, etc
# objects to their JSON equivalents
graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

return render_template('index.html',
ids=ids,
graphJSON=graphJSON)


############################# Sales and User Score prediction ######################################
@app.route('/predict-sales')
def pSales():
return render_template('sale-prediction.html')


@app.route('/p-sales-new', methods=['POST'])
def predicSalesNew():

Expand Down Expand Up @@ -58,6 +105,33 @@ def predicSalesNew():

return render_template('sale-prediction.html', rVal = output)

@app.route('/user-score-p', methods=['POST'])
def usPrediction():

cScore = float(request.form['cScore'])
gSales = float(request.form['gSales'])
cCount = float(request.form['cCount'])


model = pickle.load(open('MultipleLinearRegression.pkl','rb'))
# predict using a value

new_row = {'Critic_Score': cScore, 'Global_Sales': gSales, 'Critic_Count':cCount}
df_Apnd = df.append(new_row, ignore_index=True)

################## Get features and labels ######################
newDF2 = df_Apnd[['Critic_Score','Global_Sales','Critic_Count']]
M = newDF2
N = df_Apnd.iloc[:,5].values

l = M.iloc[-1].values

pred = model.predict(l.reshape(1,-1))[0]
pred = round(pred, 2)

return render_template('sale-prediction.html', rVal = gSales, score = pred)

############################# Genre prediction ######################################

@app.route('/genre-classify')
def cGenre():
Expand Down Expand Up @@ -99,36 +173,101 @@ def genreClassify():
return render_template('genre-classify.html', genre = pred)


@app.route('/uscore-predict')
def usPredict():
return render_template('uscore-prediction.html')
############################# User Score Clustering ######################################

@app.route('/uscore-clustering')
def uscoreCluster():
return render_template('uscore-cluster.html')

@app.route('/user-score-p', methods=['POST'])
def usPrediction():
@app.route('/us-cluster', methods=['POST'])
def usCluster():

cScore = float(request.form['cScore'])
gSales = float(request.form['gSales'])
cCount = float(request.form['cCount'])


model = pickle.load(open('MultipleLinearRegression.pkl','rb'))
model = pickle.load(open('ClusteringPredict.pkl','rb'))
# predict using a value

new_row = {'Critic_Score': cScore, 'Global_Sales': gSales, 'Critic_Count':cCount}
new_row = {'User_Score': cScore, 'Global_Sales': gSales, 'Critic_Score': cCount}
df_Apnd = df.append(new_row, ignore_index=True)

################## Get features and labels ######################
newDF2 = df_Apnd[['Critic_Score','Global_Sales','Critic_Count']]
# Get features and labels
newDF2 = df_Apnd[['User_Score','Global_Sales','Critic_Score']]
M = newDF2
N = df_Apnd.iloc[:,5].values
N = df_Apnd.iloc[:,3].values

# Encoding
objList2 = M.select_dtypes(include = "object").columns
le = LabelEncoder()

for feat2 in objList2:
M[feat2] = le.fit_transform(M[feat2].astype(str))


l = M.iloc[-1].values

pred = model.predict(l.reshape(1,-1))[0]
pred = round(pred, 2)
clstr = model.predict(l.reshape(1,-1))
if clstr == 0:
pred = "Cluster A"
elif clstr == 1:
pred = "Cluster B"
elif clstr == 2:
pred = "Cluster C"
else:
pred = "Cluster D"


return render_template('sale-prediction.html', rVal = gSales, score = pred)
return render_template('uscore-cluster.html', score = pred)









@app.route('/test')
def indexT():
# rng = pd.date_range('1/1/2011', periods=7500, freq='H')
# ts = pd.Series(np.random.randn(len(rng)), index=rng)

graphs = [
dict(
# Create a trace
data = [go.Scatter3d(
x = df['Global_Sales'],
y = df['User_Score'],
z = df['Critic_Score'],
mode = 'markers',marker = dict(
size = 12,
colorscale = 'Viridis'
)
)]
)
]

# Add "ids" to each of the graphs to pass up to the client
# for templating
ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)]

# Convert the figures to JSON
# PlotlyJSONEncoder appropriately converts pandas, datetime, etc
# objects to their JSON equivalents
graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)

return render_template('test.html',
ids=ids,
graphJSON=graphJSON)










Expand Down
24 changes: 0 additions & 24 deletions models/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,4 @@
cleanedDS = cleanDataset.clean_db()


# Declaring the points for first line plot
X1 = cleanedDS['Genre']
Y1 = cleanedDS['Global_Sales']

# Setting the figure size
fig = plt.figure(figsize=(10,5))

# plotting the first plot
plt.bar(X1, Y1, align='center', alpha=0.5)

# Labeling the X-axis
plt.xlabel('Genre')

# Labeling the Y-axis
plt.ylabel('Global_Sales')

# Give a title to the graph
plt.title('Total sales of the Genres')

# Show a legend on the plot
plt.legend()

#Saving the plot as an image
fig.savefig('../static/images/line_plot.jpg', bbox_inches='tight', dpi=150)

5 changes: 2 additions & 3 deletions static/assets/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@
border-color: #343a40; }

.social-box {
min-height: 160px;
min-height: 100px;
margin-bottom:24px;
margin-bottom: 1.5rem;
text-align: center;
Expand Down Expand Up @@ -1781,7 +1781,7 @@ header .form-inline {
padding-right: 10px; }

.social-box i {
line-height: 110px; }
line-height: 80px; }

.social-box ul {
display: inline-block;
Expand Down Expand Up @@ -2537,7 +2537,6 @@ h1,h2,h3,h4,h5,h6 {
}

p {
font-family: Montserrat-Regular;
font-size: 14px;
line-height: 1.7;
color: #666666;
Expand Down
Binary file modified static/images/line_plot.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion templates/genre-classify.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ <h3 class="menu-title">UI elements</h3><!-- /.menu-title -->
<a href="/genre-classify"> <i class="menu-icon fa fa-area-chart"></i>Classify Genre</a>
</li>
<li>
<a href="/uscore-predict"> <i class="menu-icon fa fa-table"></i>User Score</a>
<a href="/uscore-clustering"> <i class="menu-icon fa fa-table"></i>Cluster User Score</a>
</li>


Expand Down
Loading

0 comments on commit d5e3dff

Please sign in to comment.