예제 #1
0
    public Brain(SequentialModel model = null)
    {
        if (!TrainManager.Instance) // when not training, just load the passed model
        {
            if (model == null)
            {
                throw new NullReferenceException(
                          "When not training, there should always a model be passed! But model is null!");
            }

            Debug.Log("Running passed model.");

            _model   = model;
            _weights = _model.GetWeights();
        }
        else // when training, load default model
        {
            _model = TrainManager.Instance.DefaultModel;

            if (model != null) // if model not null, try to get the weights from pretrained model
            {
                _weights = model.GetWeights();
                var defaultWeights = _model.GetWeights();
                if (defaultWeights.Length != _weights.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(ArgumentOutOfRangeException),
                                                          $"The length of the default model {defaultWeights.Length} and the length of " +
                                                          $"the pretrained model {_weights.Length} should be identical.");
                }

                //Debug.Log("Training with pretrained models.");
            }
            else // if model null, get weights from default model and train from scratch
            {
                _weights = _model.GetWeights();
                for (var i = 0; i < _weights.Length; i++)
                {
                    _weights[i] = Random.value * 2 - 1f;
                }

                //Debug.Log("Training from scratch models.");
            }
        }
        _layers = _model.GetLayers();
        _model.SetWeights(_layers, _weights);
    }