This repository was archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 137
Move Dense and Dropout layers to separate files #541
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
/// A densely-connected neural network layer. | ||
/// | ||
/// `Dense` implements the operation `activation(matmul(input, weight) + bias)`, where `weight` is | ||
/// a weight matrix, `bias` is a bias vector, and `activation` is an element-wise activation | ||
/// function. | ||
/// | ||
/// This layer also supports 3-D weight tensors with 2-D bias matrices. In this case the first | ||
/// dimension of both is treated as the batch size that is aligned with the first dimension of | ||
/// `input` and the batch variant of the `matmul(_:_:)` operation is used, thus using a different | ||
/// weight and bias for each element in input batch. | ||
@frozen | ||
public struct Dense<Scalar: TensorFlowFloatingPoint>: Layer { | ||
/// The weight matrix. | ||
public var weight: Tensor<Scalar> | ||
/// The bias vector. | ||
public var bias: Tensor<Scalar> | ||
/// The element-wise activation function. | ||
@noDerivative public let activation: Activation | ||
/// Indicates whether this is a batched dense layer. | ||
@noDerivative internal let batched: Bool | ||
|
||
/// The element-wise activation function type. | ||
public typealias Activation = @differentiable (Tensor<Scalar>) -> Tensor<Scalar> | ||
|
||
public init( | ||
weight: Tensor<Scalar>, | ||
bias: Tensor<Scalar>, | ||
activation: @escaping Activation | ||
) { | ||
precondition(weight.rank <= 3, "The rank of the 'weight' tensor must be less than 4.") | ||
precondition(bias.rank <= 2, "The rank of the 'bias' tensor must be less than 3.") | ||
self.weight = weight | ||
self.bias = bias | ||
self.activation = activation | ||
self.batched = weight.rank == 3 | ||
} | ||
|
||
/// Returns the output obtained from applying the layer to the given input. | ||
/// | ||
/// - Parameter input: The input to the layer. | ||
/// - Returns: The output. | ||
@differentiable | ||
public func callAsFunction(_ input: Tensor<Scalar>) -> Tensor<Scalar> { | ||
if batched { | ||
let hidden = matmul(input.expandingShape(at: 1), weight) | ||
return activation(hidden.squeezingShape(at: 1) + bias) | ||
} | ||
return activation(matmul(input, weight) + bias) | ||
} | ||
} | ||
|
||
public extension Dense { | ||
/// Creates a `Dense` layer with the specified input size, output size, and element-wise | ||
/// activation function. The weight matrix is created with shape `[inputSize, outputSize]` and | ||
/// the bias vector is created with shape `[outputSize]`. | ||
/// | ||
/// - Parameters: | ||
/// - inputSize: The dimensionality of the input space. | ||
/// - outputSize: The dimensionality of the output space. | ||
/// - activation: The activation function to use. The default value is `identity(_:)`. | ||
/// - weightInitializer: Initializer to use for `weight`. | ||
/// - biasInitializer: Initializer to use for `bias`. | ||
init( | ||
inputSize: Int, | ||
outputSize: Int, | ||
activation: @escaping Activation = identity, | ||
weightInitializer: ParameterInitializer<Scalar> = glorotUniform(), | ||
biasInitializer: ParameterInitializer<Scalar> = zeros() | ||
) { | ||
self.init( | ||
weight: weightInitializer([inputSize, outputSize]), | ||
bias: biasInitializer([outputSize]), | ||
activation: activation) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
fileprivate extension Tensor where Scalar: TensorFlowFloatingPoint { | ||
/// Computes dropout given a probability. | ||
// TODO: Remove the underscore once `droppingOut(probability:)` has been removed. | ||
@differentiable(wrt: self where Scalar: Differentiable) | ||
func _droppingOut(probability: Double) -> Tensor { | ||
let noise = Tensor(randomUniform: shape) | ||
let keepMask = noise .>= Scalar(probability) | ||
let keepProbability = Scalar(1.0 - probability) | ||
return self * Tensor(keepMask) / Tensor(keepProbability) | ||
} | ||
} | ||
|
||
public extension Tensor where Scalar: TensorFlowFloatingPoint { | ||
/// Computes dropout given a probability. | ||
@available(*, deprecated, message: """ | ||
This API will be removed after Swift for TensorFlow 0.6. | ||
For dropout, use the `Dropout` layer. | ||
""") | ||
@differentiable(wrt: self where Scalar: Differentiable) | ||
func droppingOut(probability: Double) -> Tensor { | ||
_droppingOut(probability: probability) | ||
} | ||
} | ||
|
||
/// A dropout layer. | ||
/// | ||
/// Dropout consists in randomly setting a fraction of input units to `0` at each update during | ||
/// training time, which helps prevent overfitting. | ||
@frozen | ||
public struct Dropout<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { | ||
@noDerivative public let probability: Double | ||
|
||
/// Creates a dropout layer. | ||
/// | ||
/// - Parameter probability: The drop probability. | ||
/// - Precondition: probability must be a value between 0 and 1 (inclusive). | ||
public init(probability: Double) { | ||
precondition(0...1 ~= probability, | ||
"Probability must be a value between 0 and 1 (inclusive) but is \(probability)") | ||
self.probability = probability | ||
} | ||
|
||
@differentiable | ||
private func applyingTraining(to input: Tensor<Scalar>) -> Tensor<Scalar> { | ||
return input._droppingOut(probability: probability) | ||
} | ||
|
||
@differentiable | ||
private func applyingInference(to input: Tensor<Scalar>) -> Tensor<Scalar> { | ||
return input | ||
} | ||
|
||
/// Returns the output obtained from applying the layer to the given input. | ||
/// | ||
/// - Parameter input: The input to the layer. | ||
/// - Returns: The output. | ||
@differentiable | ||
public func callAsFunction(_ input: Tensor<Scalar>) -> Tensor<Scalar> { | ||
switch Context.local.learningPhase { | ||
case .training: | ||
return applyingTraining(to: input) | ||
case .inference: | ||
return applyingInference(to: input) | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FWIW, although it's generally better to have one logical change per PR, given that this is just one statement, I think it's probably okay to leave in.
Note: this change would break users who relied upon probability outside the range acting as if it's clamped to the range. I think this is okay, however, as this likely indicates a bug. That said, if we wanted to, we could provide a convenience initializer that would do the clamping to 0...1 and then delegate to this initializer. (This could be done in a follow-on PR.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are absolutely right. I forgot to exclude it in the commit--will look more closely in the future.
The convenience initializer ia a great idea. I think it should show some kind of message though indicating the input value will be clamped. Should this be a permanent or temporary initializer (with deprecation warning)?