这是一个基本的Tensorflow网络示例(基于MNIST),完整代码,提供大约0.92的准确度:
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run() # or
tf.initialize_all_variables().run()
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, …Run Code Online (Sandbox Code Playgroud) import numpy as np
def relu(z):
return np.maximum(0,z)
def d_relu(z):
z[z>0]=1
z[z<=0]=0
return z
x=np.array([5,1,-4,0])
y=relu(x)
z=d_relu(y)
print("y = {}".format(y))
print("z = {}".format(z))
Run Code Online (Sandbox Code Playgroud)
上面的代码输出:
y = [1 1 0 0]
z = [1 1 0 0]
Run Code Online (Sandbox Code Playgroud)
代替
y = [5 1 0 0]
z = [1 1 0 0]
Run Code Online (Sandbox Code Playgroud)
据我了解,我使用过的函数调用只应该按值传递,传递变量的副本。
为什么我的d_relu函数会影响y变量?
我正在尝试在Keras中创建一个激活函数,该函数可以采用如下所示的参数beta:
from keras import backend as K
from keras.utils.generic_utils import get_custom_objects
from keras.layers import Activation
class Swish(Activation):
def __init__(self, activation, beta, **kwargs):
super(Swish, self).__init__(activation, **kwargs)
self.__name__ = 'swish'
self.beta = beta
def swish(x):
return (K.sigmoid(beta*x) * x)
get_custom_objects().update({'swish': Swish(swish, beta=1.)})
Run Code Online (Sandbox Code Playgroud)
它在没有beta参数的情况下可以正常运行,但是如何在激活定义中包含参数?我也model.to_json()喜欢在激活ELU 时保存该值。
更新:我根据@today的答案编写了以下代码:
from keras.layers import Layer
from keras import backend as K
class Swish(Layer):
def __init__(self, beta, **kwargs):
super(Swish, self).__init__(**kwargs)
self.beta = K.cast_to_floatx(beta)
self.__name__ = 'swish'
def call(self, inputs):
return K.sigmoid(self.beta * …Run Code Online (Sandbox Code Playgroud) python machine-learning keras activation-function keras-layer
我正在创建自定义的激活功能,尤其是RBF激活功能:
from keras import backend as K
from keras.layers import Lambda
l2_norm = lambda a,b: K.sqrt(K.sum(K.pow((a-b),2), axis=0, keepdims=True))
def rbf2(x):
X = #here i need inputs that I receive from previous layer
Y = # here I need weights that I should apply for this layer
l2 = l2_norm(X,Y)
res = K.exp(-1 * gamma * K.pow(l2,2))
return res
Run Code Online (Sandbox Code Playgroud)
该函数rbf2接收上一层作为输入:
#some keras layers
model.add(Dense(84, activation='tanh')) #layer1
model.add(Dense(10, activation = rbf2)) #layer2
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能获得输入layer1和权重layer2以创建定制的激活功能?
我实际上想做的是为LeNet5神经网络实现输出层。LeNet-5的输出层有点特殊,而不是计算输入和权重向量的点积,每个神经元输出其输入向量与其权重向量之间的欧几里得距离的平方。
例如,layer1 …
python machine-learning conv-neural-network keras activation-function
我目前正在尝试使用名称为自定义激活的多个层cust_sig。但是当我尝试编译模型时,我收到一个 ValueError 错误,因为多个层具有相同的名称cust_sig。我知道我可以手动更改每个图层的名称,但想知道是否可以_1, _2, ...像内置图层一样自动添加到名称中。模型定义如下。
# Creating a model
from tensorflow.python.keras import keras
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Dense
# Custom activation function
from tensorflow.python.keras.layers import Activation
from tensorflow.python.keras import backend as K
from keras.utils.generic_utils import get_custom_objects
def custom_activation(x):
return (K.sigmoid(x) * 5) - 1
get_custom_objects().update({'custom_activation': Activation(custom_activation)})
data_format = 'channels_first'
spec_input = keras.layers.Input(shape=(1, 3, 256), name='spec')
x = keras.layers.Flatten(data_format)(spec_input)
for layer in range(3):
x = Dense(512)(x)
x = Activation('custom_activation', name='cust_sig')(x)
out = …Run Code Online (Sandbox Code Playgroud) 我目前正在首次使用深度 q 学习来训练多个循环卷积神经网络。
输入是一个 11x11x1 矩阵,每个网络由 4 个卷积层组成,尺寸分别为 3x3x16、3x3x32、3x3x64、3x3x64。我使用 stride=1 和 padding=1。每个 convLayer 后面都有 ReLU 激活。输出被馈送到具有 128 个单元的前馈全连接密集层,然后馈入同样包含 128 个单元的 LSTM 层。接下来的两个致密层产生单独的优势和价值流。
因此,训练现在已经运行了几天,现在我已经意识到(在阅读了一些相关论文之后),我没有在第一个密集层之后添加激活函数(就像大多数论文中那样)。我想知道添加一个是否会显着改善我的网络?由于我正在为大学培训网络,因此由于我的工作截止日期,我没有无限的培训时间。但是,我在训练神经网络方面没有足够的经验来决定要做什么......你有什么建议?我很感谢每一个答案!
neural-network deep-learning activation-function pytorch densenet
我一直在尝试用 CNN 构建图像分类器。我的数据集中有 2300 张图像,分为两个类别:男性和女性。这是我使用的模型:
early_stopping = EarlyStopping(min_delta = 0.001, patience = 30, restore_best_weights = True)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(256, (3, 3), input_shape=X.shape[1:], activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.Conv2D(256, (3, 3), input_shape=X.shape[1:], activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(tf.keras.layers.Dense(64))
model.add(tf.keras.layers.Dense(1, activation='softmax'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
h= model.fit(xtrain, ytrain, validation_data=(xval, yval), batch_size=32, epochs=30, callbacks = [early_stopping], verbose = 0)
Run Code Online (Sandbox Code Playgroud)
该模型的准确度为 0.501897,损失为 7.595693(该模型在每个时期都停留在这些数字上),但如果我用 Sigmoid 替换 Softmax 激活,准确度约为 0.98,损失为 0.06。为什么 Softmax …
python conv-neural-network softmax activation-function sigmoid
def newactivation(x):
if x>0:
return K.relu(x, alpha=0, max_value=None)
else :
return x * K.sigmoid(0.7* x)
get_custom_objects().update({'newactivation': Activation(newactivation)})
Run Code Online (Sandbox Code Playgroud)
我正在尝试在 keras 中为我的模型使用此激活函数,但是我很难找到要替换的内容
if x>0:
Run Code Online (Sandbox Code Playgroud)
我得到的错误:
文件“/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py”,第 614 行,在bool raise TypeError(“不允许将 a
tf.Tensor作为 Pythonbool使用。”类型错误:不允许将 a
tf.Tensor用作 Pythonbool。使用if >t is not None:而不是if t:测试是否定义了张量,并且 > 使用 TensorFlow 操作(例如 tf.cond)执行以 > 张量值为条件的子图。
有人可以帮我说清楚吗?
我已将 ReLu 导数实现为:
def relu_derivative(x):
return (x>0)*np.ones(x.shape)
Run Code Online (Sandbox Code Playgroud)
我也试过:
def relu_derivative(x):
x[x>=0]=1
x[x<0]=0
return x
Run Code Online (Sandbox Code Playgroud)
X 的大小=(3072,10000)。但是计算需要很多时间。有没有其他优化的解决方案?
python numpy machine-learning deep-learning activation-function
我读到 ResNet 通过使用跳过函数解决了梯度消失问题。但是它们不是已经使用 RELU 解决了吗?关于 ResNet 是否还有其他一些重要的事情我遗漏了,或者即使在使用 RELU 之后也会出现梯度消失问题?
optimization backpropagation neural-network deep-learning activation-function
python ×8
keras ×4
tensorflow ×3
numpy ×2
arrays ×1
densenet ×1
keras-layer ×1
optimization ×1
pytorch ×1
relu ×1
sigmoid ×1
softmax ×1