C:\Users\ravik\Anaconda3\lib\site-packages\ipykernel\parentpoller.py:116: UserWarning: Parent poll failed. If the frontend dies,
the kernel may be left running. Please let us know
about your system (bitness, Python, etc.) at
ipython-dev@scipy.org
ipython-dev@scipy.org""")
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.0s remaining: 0.0s
building tree 1 of 25
building tree 2 of 25
building tree 3 of 25
building tree 4 of 25
building tree 5 of 25
building tree 6 of 25
building tree 7 of 25
building tree 8 of 25
building tree 9 of 25
building tree 10 of 25
building tree 11 of 25
building tree 12 of 25
building tree 13 of 25
building tree 14 of 25
building tree 15 of 25
building tree 16 of 25
building tree 17 of 25
building tree 18 of 25
building tree 19 of 25
building tree 20 of 25
building tree 21 of 25
building tree 22 of 25
building tree 23 of 25
building tree 24 of 25
building tree 25 of 25
[Parallel(n_jobs=1)]: Done 25 out of 25 | elapsed: 0.8s finished
[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.
[Parallel(n_jobs=1)]: Done 1 out of 1 | elapsed: 0.0s remaining: 0.0s
[Parallel(n_jobs=1)]: Done 25 out of 25 | elapsed: 0.0s finished
<matplotlib.axes._subplots.AxesSubplot at 0x208a080e978>
In [6]:
bestfea=set(l.list)
type(bestfea)
bestfea=list(bestfea)
bestfea=max(bestfea[:-1])#in top best #1 feature
featurename=l[l.list==bestfea].iloc[:,1:]
featurename=str(featurename)
len(featurename[:-7])
featurename=featurename[16:]
featurename[:]
feat=model.feature_importances_
feat.max()
feat=model.feature_importances_
feat
l=list(feat)
l=pd.DataFrame(l,columns=['list'])
l['name']=list(X)
bestfea=set(l.list)
featurename=l[l.list==feat.max()]
featurename
Out[6]:
| list | name
-- | -- | --
0.12567 | alcohol
import matplotlib.pyplot as plt # To plot a graph from matplotlib import rcParams import numpy as np import pandas as pd import seaborn as sns import scipy as sc
sns.displot(df.TV)
from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import scale from sklearn.model_selection import cross_val_score from collections import Counter from sklearn.preprocessing import MinMaxScaler,LabelEncoder
from sklearn.neural_network import MLPRegressor from sklearn.ensemble import RandomForestRegressor
import pickle import flask
#data=pd.read_csv("Advertising.csv")
file=r"C:\Users\ravik\Data Files\1. ST Academy - Crash course and Regression files\House_Price.csv" data=pd.read_csv(file)
'''
For rendering results on HTML GUI
'''
int_features = [float(x) for x in request.form.values()]
final_features = [np.array(int_features)]
inp_data = input_scaler.transform([int_features])
feat=model.feature_importances_
feat
l=list(feat)
l=pd.DataFrame(l,columns=['list'])
bestfea=set(l.list)
featurename=l[l.list==feat.max()].iloc[:,1:]
prediction = model.predict(inp_data) # 2-d array is reuqired as an input
output = str(round(prediction[0],2)) + ", Best feature index number :"+str(featurename) +'th'+'is :' + str(feat.max())
Python 3
import pickle
import flask
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
import seaborn as sns
from io import StringIO
from IPython.display import Image
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeClassifier,DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import export_graphviz
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score,accuracy_score,confusion_matrix,plot_roc_curve,\
classification_report,roc_auc_score,roc_curve,precision_score
from sklearn.datasets import load_iris
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
from sklearn.model_selection import cross_val_score
from collections import Counter
from sklearn.preprocessing import MinMaxScaler,LabelEncoder
file=r"winequalityN.csv"
df=pd.read_csv(file)
df.fillna(df.mean(),inplace=True)
enc=LabelEncoder()
df["type"]=enc.fit_transform(df['type'])
df
X=df.iloc[:,:-1]
y=df.quality
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=10)
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import RandomForestRegressor
minmax_scaler=MinMaxScaler()
minmax_scaler.fit(X_train)
X_train=minmax_scaler.transform(X_train)
X_test=minmax_scaler.transform(X_test)
#model=DecisionTreeClassifier(criterion='gini',max_depth=4)
model=RandomForestClassifier(n_estimators=25, verbose=2, random_state = 10)
#model=LinearRegression()
model.fit(X_train,y_train)
ypred=model.predict(X_train)
pickle.dump(model,open("wineQualitypredict.pkl",'wb'))
pickle.dump(minmax_scaler,open("wineQuality_input.pkl",'wb'))
Adv_model=pickle.load(open("wineQualitypredict.pkl",'rb'))
input_scaler=pickle.load(open("wineQuality_input.pkl",'rb'))
pd.crosstab(y_train,ypred)
accuracy_score(y_train,ypred)
print(classification_report(y_train,ypred))
feat=model.feature_importances_
feat
l=list(feat)
l=pd.DataFrame(l,columns=['list'])
name=X.columns
plt.figure(figsize=(15,5))
plt.grid()
l['name']=list(X)
#l.plot(kind='barh')
sns.swarmplot(x=l.name,y=l.list,data=l,)
sns.scatterplot(x=l.name,y=l.list,data=l,hue=l.name)#df.type
#l=[]
#for i in range(X.shape[1]):
# fe=input(X.columns[i])
# l.append(fe)
#winequality=model.predict([l])
#if(winequality>=7):
# print(winequality[0],'is','Quality is good')
#else:
# print(winequality[0],'is','bad quality')
bestfea=set(l.list)
type(bestfea)
bestfea=list(bestfea)
bestfea=max(bestfea[:-1])#in top best #1 feature
featurename=l[l.list==bestfea].iloc[:,1:]
featurename=str(featurename)
len(featurename[:-7])
featurename=featurename[16:]
featurename[:]
feat=model.feature_importances_
feat.max()
feat=model.feature_importances_
feat
l=list(feat)
l=pd.DataFrame(l,columns=['list'])
l['name']=list(X)
bestfea=set(l.list)
featurename=l[l.list==feat.max()]
featurename
import matplotlib.pyplot as plt # To plot a graph from matplotlib import rcParams import numpy as np import pandas as pd import seaborn as sns import scipy as sc
sns.displot(df.TV)
from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import scale from sklearn.model_selection import cross_val_score from collections import Counter from sklearn.preprocessing import MinMaxScaler,LabelEncoder
from sklearn.neural_network import MLPRegressor from sklearn.ensemble import RandomForestRegressor
import pickle import flask
#data=pd.read_csv("Advertising.csv")
file=r"C:\Users\ravik\Data Files\1. ST Academy - Crash course and Regression files\House_Price.csv" data=pd.read_csv(file)
Split the data
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.20)#random_state=0
scale the data
minmax_scaler=MinMaxScaler() minmax_scaler.fit(X_train) X_train=minmax_scaler.transform(X_train)
X_test=minmax_scaler.transform(X_test)
model_LR=LinearRegression()
#model_LR=MLPRegressor(hidden_layer_sizes=(60,50,20))
#model_LR=RandomForestRegressor(n_estimators=100,random_state=10)
model_LR.fit(X_train,y_train)
predict=model_LR.predict(X_train)
dump the model
pickle.dump(model_LR,open("Adverting_model_pickle.pkl",'wb'))
pickle.dump(minmax_scaler,open("Adverting_input_scaler.pkl",'wb'))
load the model
Adv_model=pickle.load(open("Adverting_model_pickle.pkl",'rb'))
input_scaler=pickle.load(open("Adverting_input_scaler.pkl",'rb'))
Directory structure Projectory Name / templates/ index.html/ app.py/ module.py
Working file . Model should be dumped using pickle commnad not joblib
import numpy as np import pandas as pd
from flask import Flask, request, jsonify, render_template
import pickle
App = Flask(name)
model=pickle.load(open('wineQualitypredict.pkl','rb'))
input_scaler=pickle.load(open('wineQuality_input.pkl','rb'))
@App.route('/') def home(): return render_template('index.html') # Home page
@App.route('/predict', methods=['POST']) # Prediction def predict():
+ ", Radio - " + str(int_features[1])+", Newspaper - " + str(int_features[2])
if name == "main": App.run(debug=True)