使用以下前两个代码训练时尚MNIST模型。在第三个中,我尝试为任何外部图像预测相应的标签,但输出始终相同。所有这三个代码都是使用Keras编写的。我是新手,所以即使存在任何非常基本的错误,请帮助我找到它们。
# Fashion Mnist Model file
# Fashion Mnist with Keras
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('fashion_train.csv')
X = dataset.iloc[:,1:].values
y = dataset.iloc[:,0].values
# y is of int type. Change it to categorical
y = y.astype('object')
# Visualization
from matplotlib import pyplot as plt
m = X.shape[0]
n = X.shape[1]
labels = np.unique(y)
labels_count = labels.shape[0]
# Creating and plotting average digits
average_digits = np.empty((0, n+1))
plt.figure(figsize=(8,7))
plt.gray()
for label in labels:
digits = X[y.flatten() == label]
average_digit = digits.mean(0)
average_digits = np.vstack((average_digits, np.append(average_digit,
label)))
image = average_digit.reshape(28, 28)
plt.subplot(3,4,label+1)
plt.imshow(image)
plt.title('Average '+str(label))
plt.show()
average_digits_x = average_digits[:,:-1]
average_digits_y = average_digits[:,-1]
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
# one hot encoding
from keras.utils import np_utils
y = np_utils.to_categorical(y)
# Splitting the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20,
random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Import Keras libraries
import keras
from keras.models import Sequential
from keras.layers import Dense
# ANN
classifier = Sequential() # Initializing
classifier.add(Dense(units = 256, kernel_initializer = 'uniform', activation
= 'relu', input_dim = 784))
classifier.add(Dense(units = 128, kernel_initializer = 'uniform', activation
= 'relu'))
classifier.add(Dense(units = 10, kernel_initializer = 'uniform', activation
= 'softmax'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics
= ['accuracy'])
# Fitting Neural Networks
history=classifier.fit(X_train, y_train, batch_size = 50, epochs = 300) #
Lesser no of epochs - Basic Model
# Save model
classifier.save('fashion.h5') # h5 file will now be in your directory
# "Accuracy"
plt.plot(history.history['acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# "Loss"
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
和
# Load model and make prediction
# Fashion Mnist with Keras
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('fashion_train.csv')
X = dataset.iloc[:,1:].values
y = dataset.iloc[:,0].values
# y is of int type. Change it to categorical
y = y.astype('object')
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
# one hot encoding
from keras.utils import np_utils
y = np_utils.to_categorical(y)
# Splitting the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20,
random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Load model
from keras.models import load_model
classifier = load_model('fashion.h5')
# Prediction
y_pred = classifier.predict(X_test)
maxi = y_pred.max(axis=1)
for i in range(len(y_pred)):
for j in range(10):
if y_pred[i,j] == maxi[i]:
y_pred[i,j] = 1
else:
y_pred[i,j] = 0
# Accuracy
crt_values = (y_pred == y_test).sum()
wrong_values = (y_pred != y_test).sum()
total = crt_values+wrong_values
result = crt_values/total
print(result)
# Prediction for a new test data
test = pd.read_csv("fashion_test.csv")
test1 = test.iloc[:,1:].values
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X = sc.fit_transform(X)
test1 = sc.transform(test1)
# Prediction
y_pred_test = classifier.predict(test1)
# To compare and get accuracy
maxi = y_pred_test.max(axis=1)
for i in range(len(y_pred_test)):
for j in range(10):
if y_pred_test[i,j] == maxi[i]:
y_pred_test[i,j] = 1
else:
y_pred_test[i,j] = 0
y_test_new = test.iloc[:,0].values
from sklearn.preprocessing import LabelEncoder
labelencoder_y = LabelEncoder()
y_test_new = labelencoder_y.fit_transform(y_test_new)
# one hot encoding
from keras.utils import np_utils
y_test_new = np_utils.to_categorical(y_test_new)
# Accuracy
crt_values = (y_pred_test == y_test_new).sum()
wrong_values = (y_pred_test != y_test_new).sum()
total = crt_values+wrong_values
result = crt_values/total
print(result)
在尝试预测输出时,每次都会显示相同的类[8]。使用的代码是:
from keras.preprocessing import image
from keras.models import load_model
import cv2
import numpy as np
model=load_model('fashion.h5')
img = cv2.imread('coat.png',0)
img=cv2.resize(img,(28,28))
img = np.reshape(img, (1,784))
classes = model.predict_classes(img)
print (classes)