如何在Keras中制作一个自定义激活函数?

226 阅读3分钟

写一篇文章

注册

登录

寻找开发者和导师社区帖子博客注册登录

[

](www.codementor.io/projects?re…)

亚历克斯-多面体

关注

让我解决一些问题

如何在Keras中制作一个自定义的激活函数?

发表于2021年8月25日

How to make a custom activation function  in Keras?

大家好,我的名字是Alex Polymath。

这是另一篇关于入侵神经网络的文章--创建自定义激活函数。

你可以运行google colab或者使用你的电脑。

概述

在本教程中,我们将使用kaggle的mnist数据集。

  1. 首先,我们将为训练准备数据
  2. 第二,在python中设置激活函数(RELU,但由我们的函数提供)。
  3. 编译神经网络
  4. 训练神经网络
  5. 测试它是否还能给出好的结果

1.从kaggle下载数据。

会有2个文件

  • train.csv.zip
  • test.csv.zip

我不知道为什么,但是测试文件没有任何意义,
,因为那里没有标签。
www.kaggle.com/oddrational…

如果你使用google colab

把train.csv.zip文件拖到文件中。

!unzip archive.zip

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import keras
import matplotlib.pyplot as plt

from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split

首先,我们要准备训练用的数据

train_df = pd.read_csv('/content/train.csv') #might be in other place
train_labels = train_df['label'] #We need Y values - labels
train_labels = train_labels.to_numpy() # nothing smart just convert to numpy array
del train_df['label'] # remove label from original dataframe to use it as X
train_data = train_df.to_numpy()


# we can't use values 1,2,3,4,4,5 for Y
# instead we should use smth like [1,0,0,0,0,0], [0,1,0,0,0,0], ...
y = LabelBinarizer().fit_transform(train_labels) 


#Split train and test data
X_train, X_test, y_train, y_test = train_test_split(train_data, y, test_size=0.1)

创建自定义激活函数


from keras import backend as K
from keras.layers.core import Activation
from keras.utils.generic_utils import get_custom_objects

### Note! You cannot use random python functions, activation function gets as an input tensorflow tensors and should return tensors. There are a lot of helper functions in keras backend.
def custom_activation(x):
  
    return (1/(1 + K.exp(-x)))
     
get_custom_objects().update({'custom_activation': Activation(custom_activation)})

编译神经网络

# Define sequential model

model = keras.Sequential()

# Define the first layer
model.add(keras.layers.Dense(128, activation="custom_activation", input_shape=(784,)))
model.add(keras.layers.Dense(128, activation="custom_activation", input_shape=(128,)))
model.add(keras.layers.Dense(128, activation="custom_activation", input_shape=(128,)))
model.add(keras.layers.Dense(128, activation="custom_activation", input_shape=(128,)))

# Add activation function to classifier
model.add(keras.layers.Dense(10, activation='softmax'))

# Finish the modecl compilation
model.compile('adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Complete the model fit operation

训练神经网络

model.fit(train_data, y, epochs=10, validation_data=(X_test, y_test), callbacks=[], verbose=0)
``





KerasTensorflowPython深度学习机器学习

报告

喜欢这个帖子吗?如果对你有帮助,请给Alex Polymath一个赞。

分享

亚历克斯-波利玛特

让我解决一些问题

大家好,我叫Alex!我是一个全栈开发者。最近我创建了基于GPT2微调神经网络的服务textporn.ioaudio-data.cc的创造者 - 语音 - 到 - 文本服务clip.photos的创造者 - ...

关注

发现并阅读Alex Polymath的更多文章

开始

喜欢这个帖子吗?

请为亚历克斯留下喜欢和评论

成为第一个分享您意见的人

支持GitHub口味的markdown

提交

显示更多回复