Keras

内容来自百度百科和CS230作业

Keras是一个由Python编写的开源人工神经网络库,可以作为Tensorflow、Microsoft-CNTK和Theano的高阶应用程序接口,进行深度学习模型的设计、调试、评估、应用和可视化 。

Keras在代码结构上由面向对象方法编写,完全模块化并具有可扩展性,其运行机制和说明文档有将用户体验和使用难度纳入考虑,并试图简化复杂算法的实现难度。Keras支持现代人工智能领域的主流算法,包括前馈结构和递归结构的神经网络,也可以通过封装参与构建统计学习模型。在硬件和开发环境方面,Keras支持多操作系统下的多GPU并行计算,可以根据后台设置转化为Tensorflow、Microsoft-CNTK等系统下的组件。

Keras tutorial - the Happy House

For your next vacation, you decided to spend a week with five of your friends from school. It is a very convenient house with many things to do nearby. But the most important benefit is that everybody has commited to be happy when they are in the house. So anyone wanting to enter the house must prove their current state of happiness.

As a deep learning expert, to make sure the "Happy" rule is strictly applied, you are going to build an algorithm which that uses pictures from the front door camera to check if the person is happy or not. The door should open only if the person is happy.

You have gathered pictures of your friends and yourself, taken by the front-door camera. The dataset is labbeled.

Building a model in Keras

Keras is very good for rapid prototyping. In just a short time you will be able to build a model that achieves outstanding results.

Exercise: Implement a HappyModel(). This assignment is more open-ended than most. We suggest that you start by implementing a model using the architecture we suggest, and run through the rest of this assignment using that as your initial model. But after that, come back and take initiative to try out other model architectures. For example, you might take inspiration from the model above, but then vary the network architecture and hyperparameters however you wish. You can also use other functions such as AveragePooling2D()GlobalMaxPooling2D()Dropout().

# GRADED FUNCTION: HappyModel

def HappyModel(input_shape):
    """
    Implementation of the HappyModel.
    
    Arguments:
    input_shape -- shape of the images of the dataset

    Returns:
    model -- a Model() instance in Keras
    """
    
    ### START CODE HERE ###
    # Feel free to use the suggested outline in the text above to get started, and run through the whole
    # exercise (including the later portions of this notebook) once. The come back also try out other
    # network architectures as well. 
    
    X_input = Input(input_shape)
    X = ZeroPadding2D((1, 1))(X_input)
    # 66*66*3
    print(X.shape)
    X = Conv2D(8, (5, 5), strides = (1, 1))(X)
    X = BatchNormalization(axis = 3)(X)
    # 62*62*8
    print(X.shape)
    X = Activation('relu')(X)
    X = MaxPooling2D((2, 2), strides=(2, 2))(X)
    # 31*31*8
    print(X.shape)
    
    
    X = ZeroPadding2D((1, 1))(X)
    # 32*32*8
    print(X.shape)
    X = Conv2D(16, (3, 3), strides = (1, 1))(X)
    X = BatchNormalization(axis = 3)(X)
    # 30*30*16
    print(X.shape)
    X = Activation('relu')(X)
    X = MaxPooling2D((2, 2), strides=(2, 2))(X)
    # 15*15*16
    print(X.shape)
    
    X = ZeroPadding2D((1, 1))(X)
    # 16*16*16
    print(X.shape)
    X = Conv2D(32, (3, 3), strides = (1, 1))(X)
    X = BatchNormalization(axis = 3)(X)
    # 14*14*32
    print(X.shape)
    X = Activation('relu')(X)
    X = MaxPooling2D((2, 2), strides=(2, 2))(X)
    # 7*7*32
    print(X.shape)
    
    
    # FLATTEN X (means convert it to a vector) + FULLYCONNECTED
    X = Flatten()(X)
    Y = Dense(1, activation='sigmoid', name='fc')(X)

    # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
    model = Model(inputs = X_input, outputs = Y, name='HappyModel')
    
    
    ### END CODE HERE ###
    
    return model

create the model

happyModel = HappyModel((64,64,3))

compile the model to configure the learning process

adam = keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999)
happyModel.compile(optimizer="adam", loss=keras.losses.mean_squared_error, metrics = ["accuracy"])

 train the model. Choose the number of epochs and the batch size.

happyModel.fit(x=X_train, y=Y_train, epochs=20)

  

test/evaluate the model.


preds = happyModel.evaluate(x=X_test, y=Y_test)

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

 怀疑过拟合,减少迭代数

happyModel.fit(x=X_train, y=Y_train, epochs=10)

测试自己的图片

img_path = 'images/my_image.jpg'
img = image.load_img(img_path, target_size=(64, 64))
imshow(img)

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

print(happyModel.predict(x))

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MobileNet 是一种轻量级的深度学习模型,专为移动设备和嵌入式系统设计,以减少计算资源和内存占用,同时保持较高的性能。它是 Google 在 2017 年 ICLR 大会上提出的,由 Inception 模型发展而来,但采用了深度可分离卷积(Depthwise Separable Convolution)来大幅度减少参数数量。 在 Keras 中,你可以使用 `tf.keras.applications.MobileNet` 或 `keras.applications.mobilenet_v2.MobileNetV2` 来导入预训练的 MobileNet 模型。这个模型通常包括以下几个部分: 1. **输入层**:接受图像数据作为输入。 2. **卷积层**:包括深度可分离卷积层,它们分别对空间维度和通道维度进行操作,大大减少了参数数量。 3. **瓶颈层**:使用扩张路径(Expanded Path),包含一个深度可分离卷积后接一个1x1卷积来增加通道数。 4. **全局平均池化**(Global Average Pooling):代替全连接层,减少过拟合并使网络更易于部署。 5. **分类层**:如 `tf.keras.layers.Dense`,用于输出分类结果。 如果你想要在 Keras 中使用 MobileNet,可以直接加载预训练权重,然后可以选择冻结部分层进行微调,或者从头开始训练。以下是使用 Keras 导入 MobileNet 的基本步骤: ```python from tensorflow.keras.applications import MobileNet from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, GlobalAveragePooling2D # 加载预训练模型 base_model = MobileNet(weights='imagenet', include_top=False, input_shape=(img_height, img_width, 3)) # 添加全局平均池化和全连接层进行分类任务 x = base_model.output x = GlobalAveragePooling2D()(x) predictions = Dense(num_classes, activation='softmax')(x) # 创建新的模型 model = Model(inputs=base_model.input, outputs=predictions) # 选择是否训练或冻结预训练层 if fine_tuning: # 冻结所有层 for layer in base_model.layers: layer.trainable = False # 再定义几个顶部的层进行微调 num_frozen_layers = len(base_model.layers) - num_top_layers_to_freeze for layer in model.layers[:num_frozen_layers]: layer.trainable = False else: # 训练整个模型 model.trainable = True ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值