AI_ML / app.py
Kolpitor's picture
Update app.py
7fb8137
import streamlit as st
from PIL import Image
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from tensorflow.keras.utils import img_to_array, load_img
from keras import backend as K
from subprocess import check_output
from sklearn import preprocessing
"""
# AI_ML
"""
uploaded_file = st.file_uploader("Choose a picture", type=["png","jpg","jpeg"])
if uploaded_file is not None:
st.image(Image.open(uploaded_file),width=250)
train = pd.read_csv("sign_mnist_train.csv").values
test = pd.read_csv("sign_mnist_test.csv").values
trainX = train[:, 1:].reshape(train.shape[0], 1, 28, 28).astype('float32')
X_train = trainX / 255.0
y_train = train[:, 0]
testX = test[:, 1:].reshape(test.shape[0], 1, 28, 28).astype('float32')
X_test = testX / 255.0
y_test = test[:, 0]
lb = preprocessing.LabelBinarizer()
y_train = lb.fit_transform(y_train)
y_test = lb.fit_transform(y_test)
model = Sequential()
try:
if K.backend() == 'theano':
K.set_image_data_format('channels_first')
else:
K.set_image_data_format('channels_last')
except AttributeError:
if K._BACKEND == 'theano':
K.set_image_dim_ordering('th')
else:
K.set_image_dim_ordering('tf')
model.add(Convolution2D(30, 5, 5, padding='same', input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(1, 1)))
model.add(Convolution2D(15, 3, 3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), padding='same'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(24, activation='relu'))
#model.add(Dense(50, activation='relu'))
model.add(Dense(24, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=20, batch_size=128)
score = model.evaluate(X_test, y_test, batch_size=128)
model.summary()
if uploaded_file is not None:
img = load_img(uploaded_file, grayscale=True, target_size=(28, 28))
img = img_to_array(img)
img = img.reshape(1, 1, 28, 28)
img = img.astype('float32')
img = img / 255.0
predict_x = model.predict(img)
classes_x = np.argmax(predict_x,axis=1)
sign = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']
st.write("Prediction : " + sign[classes_x[0]])