//波士顿房价
import tensorflow.keras as keras
from tensorflow.keras.datasets import mnist
(x_train_image,y_train_label),(x_test_image,y_test_label)=mnist.load_data()
# x_train y_train 为训练集
print("x_train:",x_train_image.shape)
print("y_train:",y_train_label.shape)
import matplotlib.pyplot as plt
def plot_image(image):
fig = plt.gcf()
fig.set_size_inches(2,2)
plt.imshow(image,camp="binary")
plt.show()
plot_image(x_train_image[0])
# 图像的处理
x_train = x_train_image.reshape(60000,784).astype("float32")
x_test = x_test_image.reshape(10000,784).reshape("float32")
x_train = x_train /255
x_test=x_test /255
#标签的处理
print(y_train_label[:3])
from tensorflow.python.keras.utils import np_utils
y_train = np_utils.to_categorical(y_train_label)
y_test = np_utils.to_categorical(y_test_label)
print("one-hot:")
print(y_train[:3])
# x_train = x_train[:5000]
# y_train = y_train[:5000]
# 构建模型
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(units=512,#256
input_dim=784,
kernel_initializer="normal",
# keras_regularizer = keras.regularizer.l2(0.0002),
activation="relu"))
from tensorflow.keras.layers import Dropout
model.add(Dropout(0.3))
model.add(Dense(units=10,
keras_initializer="normal",
# keras_regularizer=keras.regularizer.l2(0.0002),
activation="softmax"))
print(model.summary())
# compile
model.compile(loss="ccategorical_crossentropy",
optimizer='adam',
metrics=['accuracy'])
train_history=model.fit(x=x_train,
y=y_train,
validation_split=0.2,
batch_size=256,
epochs=25,#10
verbose=2)
def show_train_history(train_history, train, validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train history')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train', 'validation'], loc='best')
plt.show()
show_train_history(train_history, 'acc', 'val_acc')
print(show_train_history.__dict__)
scores = model.evaluate(x_test, y_test)
print()
print('accuracy=',scores[1])
prediction = model.predict_classes(x_test)
print(prediction)
def plot_images_labels_prediction(images,labels,prediction,idx,num=10):
fig = plt.gcf()
fig.set_size_inches(12,5)
if num >25:num=25
for i in range(num):
ax=plt.subplot(5,5,i+1)
ax.imshow(images[idx],cmap="binary")
title="label"+str(labels[idx])
if len (prediction)>0:
title += "predict =" + str(prediction[idx])
ax.set_title(title, fontsize=10)
ax.set_xticks([])
ax.set_yticks([])
idx+=1
plt.show()
plot_images_labels_prediction(x_test_image,y_test_label,prediction,idx=340)
//from PIL import Image
//import numpy as np
//img = Image.open('white_0.jpg').convert('L') #white_5.jpg
//print('img size:', img.size)
//img = np.array(img).reshape(1, 784).astype('float32')
//img = img / 255
//pred_label = model.predict_classes(img)
//print('predict my img',pred_label)