themaninblack
themaninblack

Reputation: 167

Tensorflow How to correctly pass input values for prediction to the neural network

I'm having trouble while trying to pass values for prediction to my neural network. Here is the code snippet:-

model=keras.Sequential([keras.layers.Dense(units=1, input_shape=[14])])
model.compile(optimizer='sgd', loss='mean_squared_error')

Notice my input_shape=[14]

I'm getting errors while trying to make predictions using each of the following ways:-

print(model.predict(40,8,1,2,0,2,6,10,34,40,16,23,67,25))
TypeError: predict() takes from 2 to 9 positional arguments but 15 were given

print(model.predict([40,8,1,2,0,2,6,10,34,40,16,23,67,25]))
ValueError: Error when checking input: expected dense_1_input to have shape (14,) but got array with shape (1,)

print(model.predict([[40,8,1,2,0,2,6,10,34,40,16,23,67,25]]))
ValueError: Error when checking input: expected dense_1_input to have shape (14,) but got array with shape (1,)

print(model.predict[(40,8,1,2,0,2,6,10,34,40,16,23,67,25)])
TypeError: 'method' object is not subscriptable

print(model.predict([40],[8],[1],[2],[0],[2],[6],[10],[34],[40],[16],[23],[67],[25]))
TypeError: predict() takes from 2 to 9 positional arguments but 15 were given

However, it works with the following way:-

X_train,  X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, shuffle=True)
pred=model.predict(X_test)

Here is a screenshot of X_test when printed print(X_test)

enter image description here

And this is a snippet of my dataset:-

enter image description here

And here is the entire code:-

import glob
import os
from keras.models import Sequential, load_model
import numpy as np
import pandas as pd
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
import matplotlib.pyplot as plt
import keras as k
import tensorflow as tf
from tensorflow import keras
from tensorflow import lite

df = pd.read_csv("kidney4.csv")
df = df.dropna(axis=0)

for column in df.columns:
        if df[column].dtype == np.number:
            continue
        df[column] = LabelEncoder().fit_transform(df[column])

X = df.drop(["classification"], axis=1)
y = df["classification"]

x_scaler = MinMaxScaler()
x_scaler.fit(X)
column_names = X.columns
X[column_names] = x_scaler.transform(X)

X_train,  X_test, y_train, y_test = train_test_split(
        X, y, test_size= 0.2, shuffle=True)

model=keras.Sequential([keras.layers.Dense(units=1, input_shape=[14])])
model.compile(optimizer='sgd', loss='mean_squared_error')

model.fit(X_train, y_train, epochs=500)

for model_file in glob.glob("kidney_final_2.model"):
  print("Model file: ", model_file)
  model = load_model(model_file)
  pred=model.predict(X_test)
  pred = [1 if y>=0.5 else 0 for y in pred] #Threshold, transforming probabilities to either 0 or 1 depending if the probability is below or above 0.5
  scores = model.evaluate(X_test, y_test)
  print()
  print("Original  : {0}".format(", ".join([str(x) for x in y_test])))
  print()
  print("Predicted : {0}".format(", ".join([str(x) for x in pred])))
  print() 
  print("Scores    : loss = ", scores[0], " acc = ", scores[1])
  print("---------------------------------------------------------")
  print()

I would appreciate any help on this. Thank you.

Upvotes: 0

Views: 1296

Answers (1)

Timbus Calin
Timbus Calin

Reputation: 14983

Good question.

The problem/trick with the "model.predict()" in Keras and TensorFlow is that you can only predict on batches.

Therefore, in order to predict on one data point(in your case an array of 14 elements), you need to simulate the batch axis. That is, a batch of size 1, since you want to predict on one data point.

You can use numpy to achieve this.

input_array = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14])
input_array_for_prediction = np.expand_dims(input_array,axis=0)
print(model.predict(input_array_for_prediction))

Upvotes: 1

Related Questions