keras实现happyhouse程序

ng第四课第二周的作业,用keros实现happyhouse,即使用keras框架识别笑脸和非笑脸,代码如下。这个代码对训练集和测试集的准确率都挺高,但是对我自己输入的图片的识别效果确并不好,ng在作业中有指明原因:

The training/test sets were quite similar; for example, all the pictures were taken against the same background (since a front door camera is always mounted in the same position). This makes the problem easier, but a model trained on this data may or may not work on your own data. But feel free to give it a try!

想要训练出更好的模型的话,就需要我们自己调试框架中的方法,调整参数,或者重新选择训练集。

import keras.backend as K
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from keras.utils import plot_model
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

K.set_image_data_format('channels_last')


def mean_pred(y_true,y_pred):
    return K.mean(y_pred)


def load_dataset():
    train_dataset = h5py.File('datasets/train_happy.h5', "r")
    train_set_x_orig = np.array(train_dataset["train_set_x"][:])  # train set features
    train_set_y_orig = np.array(train_dataset["train_set_y"][:])  # train set labels

    test_dataset = h5py.File('datasets/test_happy.h5', "r")
    test_set_x_orig = np.array(test_dataset["test_set_x"][:])  # test set features
    test_set_y_orig = np.array(test_dataset["test_set_y"][:])  # test set labels

    classes = np.array(test_dataset["list_classes"][:])  # the list of classes

    train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
    test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))

    return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes


X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()

# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.

# Reshape
Y_train = Y_train_orig.T
Y_test = Y_test_orig.T


#  graded function : happymodel
def HappyModel(input_shape):
    # input_shape -- shape of the images of the dataset
    # return model -- a Model() instance in keras

    X_input = Input(input_shape)
    X = ZeroPadding2D((3, 3))(X_input)
    X = BatchNormalization(axis=3, name='bn0')(X)
    X = Activation('relu')(X)
    X = MaxPooling2D((2, 2), name='max_pool')(X)
    X = Flatten()(X)
    X = Dense(1, activation='sigmoid', name='fc')(X)
    model = Model(inputs=X_input, outputs=X, name='HappyModel')

    return model


# train and test model above
# 1 Create the model by calling the function above
happyModel = HappyModel(X_train.shape[1:])

# 2 Compile the model by calling model.compile(optimizer = "...", loss = "...", metrics = ["accuracy"])
happyModel.compile(optimizer="adam", loss='binary_crossentropy', metrics=['accuracy'])

# 3 Train the model on train data by calling model.fit(x = ..., y = ..., epochs = ..., batch_size = ...)
happyModel.fit(x=X_train, y=Y_train, epochs=40, batch_size=16)

# 4 Test the model on test data by calling model.evaluate(x = ..., y = ...)
preds = happyModel.evaluate(x=X_test, y=Y_test)

print()
print("Loss = " + str(preds[0]))
print("Test Accuracy = " + str(preds[1]))


# test
img_path = 'images/cry.jpg'
img = image.load_img(img_path, target_size=(64, 64))
imshow(img)
plt.show()

x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

print(happyModel.predict(x))

happyModel.summary()

plot_model(happyModel, to_file='HappyModel.png')
SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))

好的,下面是使用Keras实现MNIST分类程序的代码: ```python # 导入相关库 import numpy as np import keras.datasets.mnist as mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout # 加载数据集 (X_train, y_train), (X_test, y_test) = mnist.load_data() # 将数据集转换为指定类型 X_train = X_train.reshape(X_train.shape[0], -1).astype('float32') / 255. X_test = X_test.reshape(X_test.shape[0], -1).astype('float32') / 255. y_train = np_utils.to_categorical(y_train, num_classes=10) y_test = np_utils.to_categorical(y_test, num_classes=10) # 建立模型 model = Sequential() model.add(Dense(units=512, input_dim=784, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(units=512, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(units=10, 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, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) ``` 这个程序使用了keras库来实现MNIST分类。首先,我们使用mnist.load_data()函数来加载MNIST数据集。然后将数据集转换为指定的类型,并对标签进行one-hot编码。接下来,我们建立了一个包含3个全连接层的神经网络。其中前2个层包含了512个神经元和relu激活函数,并添加了0.2的dropout层用于防止过拟合。第3个层包含10个神经元和softmax激活函数,用于输出分类结果。最后,我们编译模型并训练它,最后评估模型的准确性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值