I created a model using Keras using the following code:
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split , cross_validate
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense , Dropout , Activation , Flatten
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import StandardScaler
import tensorflowjs as tfjs
# %%
df=pd.read_csv('Crop_recommendation.csv')
# %%
features = df.T[:7].T
features
# %%
scaler = StandardScaler()
features = scaler.fit_transform(features)
features
# %%
data_classes = list(df['label'].unique())
# %%
data_classes
# %%
targets = df['label'].apply(data_classes.index)
targets
# %%
targets = to_categorical(targets)
targets
# %%
x_train , x_test , y_train , y_test = train_test_split(features,targets,test_size = 0.1 , random_state = 42)
# %%
x_train.shape , y_train.shape
# %%
model = Sequential()
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dense(22,activation='softmax'))
# %%
model.compile(optimizer='adam',loss = 'categorical_crossentropy',metrics = ['accuracy'])
# %%
history = model.fit(x_train,y_train,epochs=50)
I export my code using tesnsorflowjs converter:
tfjs.converters.save_keras_model(model, 'models')
When I try to import the model in javascript using tf.loadLayersModel The promise returns an error Error: Input 0 is incompatible with layer flatten_1: expected min_ndim=3, found ndim=2.
const loadModel = async () => {
model = undefined;
model = await tf.loadLayersModel(
"https://raw.githubusercontent.com/mostafa-gouda/crop_recommendation/main/model.json"
);
return model;
};
I can't seem to find where the problem is