[PYTHON] I want to use the activation function Mish

New activation function Mish

GitHub - digantamisra98/Mish: Mish: A Self Regularized Non-Monotonic Neural Activation Function

This seems to be an implementation of Tensorflow-Keras

Mish/mish.py at master · digantamisra98/Mish · GitHub

I don't know what is difficult, but I tried pasting it

A detailed implementation of pytorch and Keras was written here ...

The code I was copying and pasting for the first time is as follows

python::1


from __future__ import print_function
from tensorflow.python import keras
from tensorflow.python.keras.datasets import mnist
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Dropout, Flatten
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras import backend as K
 

"""Tensorflow-Keras Implementation of Mish"""

## Import Necessary Modules
import tensorflow as tf
from tensorflow.keras.layers import Activation
from tensorflow.keras.utils import get_custom_objects

class Mish(Activation):
    '''
    Mish Activation Function.
    .. math::
        mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^{x}))
    Shape:
        - Input: Arbitrary. Use the keyword argument `input_shape`
        (tuple of integers, does not include the samples axis)
        when using this layer as the first layer in a model.
        - Output: Same shape as the input.
    Examples:
        >>> X = Activation('Mish', name="conv1_act")(X_input)
    '''

    def __init__(self, activation, **kwargs):
        super(Mish, self).__init__(activation, **kwargs)
        self.__name__ = 'Mish'


def mish(inputs):
    return inputs * tf.math.tanh(tf.math.softplus(inputs))

get_custom_objects().update({'Mish': Mish(mish)})



batch_size = 128
num_classes = 10
epochs = 12
 
# input image dimensions
img_rows, img_cols = 28, 28
 
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
 
if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)
 
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
 
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
 
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='Mish',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='Mish'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='Mish'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
 
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
 
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Recommended Posts

I want to use the activation function Mish
I want to use the R dataset in python
I want to use the latest gcc without sudo privileges! !!
I want to use only the normalization process of SudachiPy
[Python] I want to use the -h option with argparse
I want to use jar from python
I want to use Linux on mac
I want to use IPython Qt Console
I want to display the progress bar
I want to handle the rhyme part2
I want to handle the rhyme part5
I want to handle the rhyme part4
I want to get the name of the function / method being executed
I want to use the Django Debug Toolbar in my Ajax application
I want to use Temporary Directory with Python2
I want to use ceres solver from python
I don't want to use -inf with np.log
I want to use ip vrf with SONiC
I want to customize the appearance of zabbix
I want to display the progress in Python!
[Python] I want to know the variables in the function when an error occurs!
[Ansible] I want to call my own function from the template module (macro)
I want to use Python in the environment of pyenv + pipenv on Windows 10
I want to get the file name, line number, and function name in Python 3.4
I tried to learn the sin function with chainer
I want to see the file name from DataLoader
I want to use self in Backpropagation (tf.custom_gradient) (tensorflow)
I want to grep the execution result of strace
I want to scroll the Django shift table, but ...
I wanted to use the Python library from MATLAB
I want to inherit to the back with python dataclass
I want to fully understand the basics of Bokeh
I want to write in Python! (3) Utilize the mock
I want to use OpenJDK 11 on Ubuntu Linux 18.04 LTS / 18.10
I want to handle the rhyme part6 (organize once)
I want to automate ssh using the expect command!
I want to publish the product at the lowest cost
The programming language you want to be able to use
I want to handle the rhyme part8 (finished once)
I want to increase the security of ssh connections
Regarding the activation function Gelu
How to use the generator
What is the activation function?
How to use the decorator
I want to use Linux commands at the command prompt! Use Linux commands at the command prompt instead of Git Bash
[TensorFlow] I want to master the indexing for Ragged Tensor
I want to initialize if the value is empty (python)
I want to save the photos sent by LINE to S3
I want to automate ssh using the expect command! part2
maya Python I want to fix the baked animation again.
I want to move selenium for the time being [for mac]
I want to get the operation information of yahoo route
I made a function to check the model of DCGAN
I want to calculate the allowable downtime from the operating rate
I want to judge the authenticity of the elements of numpy array
I want to use a virtual environment with jupyter notebook!
I didn't know how to use the [python] for statement
I tried to implement the mail sending function in Python
I want to know the features of Python and pip
If you want your colleagues to use the same language
I want to make the Dictionary type in the List unique