浏览代码

Merge pull request #1495 from Unity-Technologies/release-v0.6

release-v0.6 --> develop
/develop-generalizationTraining-TrainerController
GitHub 6 年前
当前提交
c8cc5a29
共有 151 个文件被更改,包括 3972 次插入4211 次删除
  1. 18
      README.md
  2. 53
      UnitySDK/Assets/Gizmos/HeuristicBrain Icon.png
  3. 52
      UnitySDK/Assets/Gizmos/HeuristicBrain Icon.png.meta
  4. 74
      UnitySDK/Assets/Gizmos/LearningBrain Icon.png
  5. 52
      UnitySDK/Assets/Gizmos/LearningBrain Icon.png.meta
  6. 75
      UnitySDK/Assets/Gizmos/PlayerBrain Icon.png
  7. 52
      UnitySDK/Assets/Gizmos/PlayerBrain Icon.png.meta
  8. 2
      UnitySDK/Assets/ML-Agents/Editor/Tests/EditModeTestInternalBrainTensorApplier.cs
  9. 2
      UnitySDK/Assets/ML-Agents/Editor/Tests/EditModeTestInternalBrainTensorGenerator.cs
  10. 2
      UnitySDK/Assets/ML-Agents/Examples/3DBall/Brains/3DBallHardLearning.asset
  11. 2
      UnitySDK/Assets/ML-Agents/Examples/3DBall/Brains/3DBallLearning.asset
  12. 10
      UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/Brains/BananaLearning.asset
  13. 2
      UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/Prefabs/RLArea.prefab
  14. 2
      UnitySDK/Assets/ML-Agents/Examples/Basic/Brains/BasicLearning.asset
  15. 10
      UnitySDK/Assets/ML-Agents/Examples/Bouncer/Brains/BouncerLearning.asset
  16. 2
      UnitySDK/Assets/ML-Agents/Examples/Crawler/Brains/CrawlerDynamicLearning.asset
  17. 2
      UnitySDK/Assets/ML-Agents/Examples/Crawler/Brains/CrawlerStaticLearning.asset
  18. 2
      UnitySDK/Assets/ML-Agents/Examples/GridWorld/Brains/GridWorldLearning.asset
  19. 2
      UnitySDK/Assets/ML-Agents/Examples/Hallway/Brains/HallwayLearning.asset
  20. 2
      UnitySDK/Assets/ML-Agents/Examples/PushBlock/Brains/PushBlockLearning.asset
  21. 2
      UnitySDK/Assets/ML-Agents/Examples/Pyramids/Brains/PyramidsLearning.asset
  22. 2
      UnitySDK/Assets/ML-Agents/Examples/Reacher/Brains/ReacherLearning.asset
  23. 2
      UnitySDK/Assets/ML-Agents/Examples/Soccer/Brains/GoalieLearning.asset
  24. 2
      UnitySDK/Assets/ML-Agents/Examples/Soccer/Brains/StrikerLearning.asset
  25. 2
      UnitySDK/Assets/ML-Agents/Examples/Tennis/Brains/TennisLearning.asset
  26. 10
      UnitySDK/Assets/ML-Agents/Examples/Walker/Brains/WalkerLearning.asset
  27. 2
      UnitySDK/Assets/ML-Agents/Examples/WallJump/Brains/BigWallJumpLearning.asset
  28. 2
      UnitySDK/Assets/ML-Agents/Examples/WallJump/Brains/SmallWallJumpLearning.asset
  29. 2
      UnitySDK/Assets/ML-Agents/Scripts/Academy.cs
  30. 6
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/ApplierImpl.cs
  31. 5
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/GeneratorImpl.cs
  32. 12
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/ModelParamLoader.cs
  33. 5
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TensorApplier.cs
  34. 6
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TensorGenerator.cs
  35. 36
      UnitySDK/Assets/ML-Agents/Scripts/LearningBrain.cs
  36. 2
      config/offline_bc_config.yaml
  37. 19
      docs/Background-TensorFlow.md
  38. 2
      docs/Background-Unity.md
  39. 101
      docs/Basic-Guide.md
  40. 16
      docs/FAQ.md
  41. 58
      docs/Getting-Started-with-Balance-Ball.md
  42. 2
      docs/Glossary.md
  43. 329
      docs/Learning-Environment-Create-New.md
  44. 10
      docs/Learning-Environment-Design-Learning-Brains.md
  45. 2
      docs/Learning-Environment-Design-Player-Brains.md
  46. 3
      docs/Learning-Environment-Examples.md
  47. 13
      docs/Learning-Environment-Executable.md
  48. 4
      docs/ML-Agents-Overview.md
  49. 15
      docs/Migrating.md
  50. 2
      docs/Readme.md
  51. 6
      docs/Training-Imitation-Learning.md
  52. 2
      docs/Training-ML-Agents.md
  53. 999
      docs/images/mlagents-3DBallHierarchy.png
  54. 277
      docs/images/mlagents-NewProject.png
  55. 360
      docs/images/mlagents-NewTutAcademy.png
  56. 999
      docs/images/mlagents-NewTutAssignBrain.png
  57. 502
      docs/images/mlagents-NewTutBlock.png
  58. 536
      docs/images/mlagents-NewTutFloor.png
  59. 132
      docs/images/mlagents-NewTutHierarchy.png
  60. 507
      docs/images/mlagents-NewTutSphere.png
  61. 819
      docs/images/mlagents-NewTutSplash.png
  62. 999
      docs/images/mlagents-Open3DBall.png
  63. 75
      gym-unity/README.md
  64. 20
      ml-agents/mlagents/envs/environment.py
  65. 16
      ml-agents/mlagents/envs/exception.py
  66. 44
      ml-agents/mlagents/envs/rpc_communicator.py
  67. 9
      ml-agents/mlagents/trainers/bc/offline_trainer.py
  68. 2
      ml-agents/mlagents/trainers/demo_loader.py
  69. 19
      ml-agents/mlagents/trainers/learn.py
  70. 8
      ml-agents/mlagents/trainers/models.py
  71. 2
      ml-agents/mlagents/trainers/policy.py
  72. 2
      ml-agents/setup.py
  73. 4
      ml-agents/tests/envs/test_envs.py
  74. 2
      ml-agents/tests/mock_communicator.py
  75. 4
      ml-agents/tests/trainers/test_demo_loader.py
  76. 4
      ml-agents/tests/trainers/test_trainer_controller.py
  77. 5
      SURVEY.md
  78. 224
      UnitySDK/Assets/ML-Agents/Editor/Tests/MultinomialTest.cs
  79. 122
      UnitySDK/Assets/ML-Agents/Editor/Tests/RandomNormalTest.cs
  80. 7
      UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/3DBallHardLearning.bytes.meta
  81. 7
      UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/3DBallLearning.bytes.meta
  82. 7
      UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/TFModels/BananaLearning.bytes.meta
  83. 7
      UnitySDK/Assets/ML-Agents/Examples/Basic/TFModels/BasicLearning.bytes.meta
  84. 7
      UnitySDK/Assets/ML-Agents/Examples/Bouncer/TFModels/BouncerLearning.bytes.meta
  85. 7
      UnitySDK/Assets/ML-Agents/Examples/Crawler/TFModels/CrawlerDynamicLearning.bytes.meta
  86. 7
      UnitySDK/Assets/ML-Agents/Examples/Crawler/TFModels/CrawlerStaticLearning.bytes.meta
  87. 7
      UnitySDK/Assets/ML-Agents/Examples/GridWorld/TFModels/GridWorldLearning.bytes.meta
  88. 7
      UnitySDK/Assets/ML-Agents/Examples/Hallway/TFModels/HallwayLearning.bytes.meta
  89. 7
      UnitySDK/Assets/ML-Agents/Examples/PushBlock/TFModels/PushBlockLearning.bytes.meta
  90. 7
      UnitySDK/Assets/ML-Agents/Examples/Pyramids/TFModels/PyramidsLearning.bytes.meta
  91. 7
      UnitySDK/Assets/ML-Agents/Examples/Reacher/TFModels/ReacherLearning.bytes.meta
  92. 7
      UnitySDK/Assets/ML-Agents/Examples/Soccer/TFModels/GoalieLearning.bytes.meta
  93. 7
      UnitySDK/Assets/ML-Agents/Examples/Soccer/TFModels/StrikerLearning.bytes.meta
  94. 7
      UnitySDK/Assets/ML-Agents/Examples/Tennis/TFModels/TennisLearning.bytes.meta
  95. 7
      UnitySDK/Assets/ML-Agents/Examples/Walker/TFModels/WalkerLearning.bytes.meta
  96. 7
      UnitySDK/Assets/ML-Agents/Examples/WallJump/TFModels/BigWallJumpLearning.bytes.meta
  97. 7
      UnitySDK/Assets/ML-Agents/Examples/WallJump/TFModels/SmallWallJumpLearning.bytes.meta
  98. 213
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TFSharpInferenceEngine.cs
  99. 12
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TFSharpInferenceEngine.cs.meta
  100. 40
      UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/Tensor.cs

18
README.md


[contribution guidelines](CONTRIBUTING.md) and
[code of conduct](CODE_OF_CONDUCT.md).
You can connect with us and the broader community
through Unity Connect and GitHub:
If you run into any problems using the ML-Agents toolkit,
[submit an issue](https://github.com/Unity-Technologies/ml-agents/issues) and
make sure to include as much detail as possible.
* Join our
[Unity Machine Learning Channel](https://connect.unity.com/messages/c/035fba4f88400000)
to connect with others using the ML-Agents toolkit and Unity developers
enthusiastic about machine learning. We use that channel to surface updates
regarding the ML-Agents toolkit (and, more broadly, machine learning in
games).
* If you run into any problems using the ML-Agents toolkit,
[submit an issue](https://github.com/Unity-Technologies/ml-agents/issues) and
make sure to include as much detail as possible.
Your opinion matters a great deal to us. Only by hearing your thoughts on the Unity ML-Agents Toolkit can we continue to improve and grow. Please take a few minutes to [let us know about it](https://github.com/Unity-Technologies/ml-agents/issues/1454).
team at ml-agents@unity3d.com.
team at ml-agents@unity3d.com.
## Translations

53
UnitySDK/Assets/Gizmos/HeuristicBrain Icon.png

之前 之后
宽度: 64  |  高度: 64  |  大小: 4.9 KiB

52
UnitySDK/Assets/Gizmos/HeuristicBrain Icon.png.meta


fileFormatVersion: 2
guid: b9fe19b47e0744881b9f4afc17dcd926
guid: fbee1fddc738f410ea0b37fe6301d7c0
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

enableMipMap: 0
sRGBTexture: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0

maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 0
aniso: 1
filterMode: -1
aniso: -1
wrapU: 1
wrapV: 1
wrapU: -1
wrapV: -1
nPOTScale: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
alphaIsTransparency: 0
textureType: 2
textureType: 0
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0

maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: iPhone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Android
maxTextureSize: 128
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1

74
UnitySDK/Assets/Gizmos/LearningBrain Icon.png

之前 之后
宽度: 64  |  高度: 64  |  大小: 4.8 KiB

52
UnitySDK/Assets/Gizmos/LearningBrain Icon.png.meta


fileFormatVersion: 2
guid: e7372058b17fb432794fe9b7e395fed5
guid: aff60a06d6c704801a2d09a8e72cbefc
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

enableMipMap: 0
sRGBTexture: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0

maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 0
aniso: 1
filterMode: -1
aniso: -1
wrapU: 1
wrapV: 1
wrapU: -1
wrapV: -1
nPOTScale: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
alphaIsTransparency: 0
textureType: 2
textureType: 0
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0

maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: iPhone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Android
maxTextureSize: 128
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1

75
UnitySDK/Assets/Gizmos/PlayerBrain Icon.png

之前 之后
宽度: 64  |  高度: 64  |  大小: 5.1 KiB

52
UnitySDK/Assets/Gizmos/PlayerBrain Icon.png.meta


fileFormatVersion: 2
guid: 176f3272b939d48de9b37abe13b2b8c3
guid: 224cd0666bb7b4477b0806fd29cf5966
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

enableMipMap: 0
sRGBTexture: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0

maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 0
aniso: 1
filterMode: -1
aniso: -1
wrapU: 1
wrapV: 1
wrapU: -1
wrapV: -1
nPOTScale: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0

spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
alphaIsTransparency: 0
textureType: 2
textureType: 0
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0

maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: iPhone
maxTextureSize: 128
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Android
maxTextureSize: 128
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1

2
UnitySDK/Assets/ML-Agents/Editor/Tests/EditModeTestInternalBrainTensorApplier.cs


using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.MachineLearning.InferenceEngine;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using System.Reflection;
using MLAgents.InferenceBrain;

2
UnitySDK/Assets/ML-Agents/Editor/Tests/EditModeTestInternalBrainTensorGenerator.cs


using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.MachineLearning.InferenceEngine;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using MLAgents.InferenceBrain;
namespace MLAgents.Tests

2
UnitySDK/Assets/ML-Agents/Examples/3DBall/Brains/3DBallHardLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 11400000, guid: c2381a94783b14d5fa1c56dc947a9578, type: 3}
model: {fileID: 4900000, guid: 8a2da2218425f46e9921caefda4b7813, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/3DBall/Brains/3DBallLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 0}
model: {fileID: 4900000, guid: 9f58800fa9d54477aa01ee258842f6b3, type: 3}

10
UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/Brains/BananaLearning.asset


-
-
vectorActionSpaceType: 0
graphModel: {fileID: 0}
graphPlaceholders: []
BatchSizePlaceholderName: batch_size
VectorObservationPlacholderName: vector_observation
RecurrentInPlaceholderName: recurrent_in
RecurrentOutPlaceholderName: recurrent_out
VisualObservationPlaceholderName: []
ActionPlaceholderName: action
PreviousActionPlaceholderName: prev_action
model: {fileID: 4900000, guid: 69bd818d72b944849916d2fda9fe471b, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/Prefabs/RLArea.prefab


m_Script: {fileID: 11500000, guid: 700720465a0104fa586fa4a412b044f8, type: 3}
m_Name:
m_EditorClassIdentifier:
brain: {fileID: 11400000, guid: 9e7865ec29c894c2d8c1617b0fa392f9, type: 2}
brain: {fileID: 11400000, guid: dff7429d656234fed84c4fac2a7a683c, type: 2}
agentParameters:
agentCameras: []
maxStep: 5000

2
UnitySDK/Assets/ML-Agents/Examples/Basic/Brains/BasicLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 503ce1e8257904bd0b5be8f7fb4b5d28, type: 3}

10
UnitySDK/Assets/ML-Agents/Examples/Bouncer/Brains/BouncerLearning.asset


-
-
vectorActionSpaceType: 1
graphModel: {fileID: 4900000, guid: f6197a66bd242464e8b654ef1ac01faf, type: 3}
graphPlaceholders: []
BatchSizePlaceholderName: batch_size
VectorObservationPlacholderName: vector_observation
RecurrentInPlaceholderName: recurrent_in
RecurrentOutPlaceholderName: recurrent_out
VisualObservationPlaceholderName: []
ActionPlaceholderName: action
PreviousActionPlaceholderName: prev_action
model: {fileID: 4900000, guid: 760d2b8347b4b46e3a44d9b989e1304e, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Crawler/Brains/CrawlerDynamicLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 0}
model: {fileID: 4900000, guid: 9482a8782450a4d87b20942c4523176b, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Crawler/Brains/CrawlerStaticLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 0}
model: {fileID: 4900000, guid: e256bd37f98f246e5be72618766d0a93, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/GridWorld/Brains/GridWorldLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 0fd168a0ea1d04ef9a68c80cf452ce3d, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Hallway/Brains/HallwayLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 84588668e6ea948d3ab55bb813cc769b, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/PushBlock/Brains/PushBlockLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: e22850d2072904a0ab06069cda2599e5, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Pyramids/Brains/PyramidsLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 7d1c7f27447234c3a81169de00dcaa8a, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Reacher/Brains/ReacherLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 0}
model: {fileID: 4900000, guid: 5fb4a3624e9ca4e1c81b51b5117cb31e, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Soccer/Brains/GoalieLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 890ab8f03425c4a80a52ba674ddec3f3, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Soccer/Brains/StrikerLearning.asset


vectorActionDescriptions:
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 23410257d39d44616bfefdff59c7fbc9, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/Tennis/Brains/TennisLearning.asset


-
-
vectorActionSpaceType: 1
model: {fileID: 0}
model: {fileID: 4900000, guid: 6d4281b70d41f48cb83d663b84f78c9a, type: 3}

10
UnitySDK/Assets/ML-Agents/Examples/Walker/Brains/WalkerLearning.asset


-
-
vectorActionSpaceType: 1
graphModel: {fileID: 0}
graphPlaceholders: []
BatchSizePlaceholderName: batch_size
VectorObservationPlacholderName: vector_observation
RecurrentInPlaceholderName: recurrent_in
RecurrentOutPlaceholderName: recurrent_out
VisualObservationPlaceholderName: []
ActionPlaceholderName: action
PreviousActionPlaceholderName: prev_action
model: {fileID: 4900000, guid: 48ab33cf9fbee4883948187618027835, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/WallJump/Brains/BigWallJumpLearning.asset


-
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: c118879bb5db84f269e4da23ba8c4f61, type: 3}

2
UnitySDK/Assets/ML-Agents/Examples/WallJump/Brains/SmallWallJumpLearning.asset


-
-
vectorActionSpaceType: 0
model: {fileID: 0}
model: {fileID: 4900000, guid: 92cd96b2c34334db692e93af25b64d2a, type: 3}

2
UnitySDK/Assets/ML-Agents/Scripts/Academy.cs


[SerializeField]
public BroadcastHub broadcastHub = new BroadcastHub();
private const string kApiVersion = "API-5";
private const string kApiVersion = "API-6";
// Fields provided in the Inspector

6
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/ApplierImpl.cs


using UnityEngine.MachineLearning.InferenceEngine;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using System.Collections.Generic;
using MLAgents.InferenceBrain.Utils;
namespace MLAgents.InferenceBrain
{

5
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/GeneratorImpl.cs


using UnityEngine.MachineLearning.InferenceEngine;
using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using MLAgents.InferenceBrain.Utils;
namespace MLAgents.InferenceBrain
{

12
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/ModelParamLoader.cs


using UnityEngine.MachineLearning.InferenceEngine;
using UnityEngine;
#if ENABLE_TENSORFLOW
using System;
using System.Collections.Generic;
using System.Linq;

Continuous
}
private const long ApiVersion = 1;
private InferenceEngine _engine;
private TFSharpInferenceEngine _engine;
private BrainParameters _brainParameters;
private List<string> _failedModelChecks = new List<string>();

/// <param name="brainParameters"> The BrainParamters that are used verify the
/// compatibility with the InferenceEngine</param>
/// <returns></returns>
public static ModelParamLoader GetLoaderAndCheck(InferenceEngine engine,
public static ModelParamLoader GetLoaderAndCheck(TFSharpInferenceEngine engine,
BrainParameters brainParameters)
{
ModelParamLoader modelParamLoader = new ModelParamLoader(engine, brainParameters);

private ModelParamLoader(InferenceEngine engine, BrainParameters brainParameters)
private ModelParamLoader(TFSharpInferenceEngine engine, BrainParameters brainParameters)
{
_engine = engine;
_brainParameters = brainParameters;

{
_engine.ExecuteGraph(new Tensor[0], outputs);
}
catch (Exception e)
catch
{
return -1;
}

}
}
}
#endif

5
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TensorApplier.cs


using UnityEngine.MachineLearning.InferenceEngine;
using System.Collections.Generic;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using System;
using System.Collections.Generic;
namespace MLAgents.InferenceBrain
{

6
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TensorGenerator.cs


using UnityEngine.MachineLearning.InferenceEngine;
using System.Collections.Generic;
using UnityEngine.MachineLearning.InferenceEngine.Util;
using System.Linq;
using System;
using System.Collections.Generic;
namespace MLAgents.InferenceBrain
{

36
UnitySDK/Assets/ML-Agents/Scripts/LearningBrain.cs


using UnityEngine;
using System.Linq;
using MLAgents.InferenceBrain;
using UnityEngine.MachineLearning.InferenceEngine;
using UnityEngine.Profiling;
namespace MLAgents

{
private TensorGenerator _tensorGenerator;
private TensorApplier _tensorApplier;
#if ENABLE_TENSORFLOW
public Model model;
#endif
public TextAsset model;
private InferenceEngine _engine;
#if ENABLE_TENSORFLOW
private TFSharpInferenceEngine _engine;
#endif
private IEnumerable<Tensor> _inferenceInputs;
private IEnumerable<Tensor> _inferenceOutputs;

/// </exception>
public void ReloadModel(int seed = 0)
{
#if ENABLE_TENSORFLOW
var config = new InferenceEngineConfig
{
Device = InferenceEngineConfig.DeviceType.CPU
};
_engine = InferenceAPI.LoadModel(model, config);
_engine = new TFSharpInferenceEngine();
_engine.PrepareModel(model.bytes);
}
else
{

_inferenceOutputs = _modelParamLoader.GetOutputTensors();
_tensorGenerator = new TensorGenerator(brainParameters, seed);
_tensorApplier = new TensorApplier(brainParameters, seed);
#endif
}
/// <summary>

/// Brain Parameters</returns>
public IEnumerable<string> GetModelFailedChecks()
{
#if ENABLE_TENSORFLOW
#else
return new List<string>(){
"You need to install the TensorflowSharp plugin and add the ENABLE_TENSORFLOW " +
"flag in your Player Settings in order to use inference. "};
#endif
}
/// <inheritdoc />

{
return;
}
#if ENABLE_TENSORFLOW
if (_engine == null)
{
Debug.LogError($"No model was present for the Brain {name}.");

// Update the outputs
_tensorApplier.ApplyTensors(_inferenceOutputs, agentInfos);
#else
if (agentInfos.Count > 0)
{
Debug.LogError(string.Format(
"The brain {0} was set to inference mode but the Tensorflow library is not " +
"present in the Unity project.",
name));
}
#endif
agentInfos.Clear();
}
}

2
config/offline_bc_config.yaml


num_layers: 2
sequence_length: 32
memory_size: 256
demo_path: ./UnitySDK/Assets/Demonstrations/<Your_Demon_File>.demo
demo_path: ./UnitySDK/Assets/Demonstrations/<Your_Demo_File>.demo
HallwayLearning:
trainer: offline_bc

19
docs/Background-TensorFlow.md


performing computations using data flow graphs, the underlying representation of
deep learning models. It facilitates training and inference on CPUs and GPUs in
a desktop, server, or mobile device. Within the ML-Agents toolkit, when you
train the behavior of an agent, the output is a TensorFlow model (.tf) file
train the behavior of an agent, the output is a TensorFlow model (.bytes) file
that you can then embed within a Learning Brain. Unless you implement a new
algorithm, the use of TensorFlow is mostly abstracted away and behind the
scenes.

recommend our guide on [using Tensorboard with ML-Agents](Using-Tensorboard.md) or
this [tutorial](https://github.com/dandelionmane/tf-dev-summit-tensorboard-tutorial).
## Tensorflow Model Inference
## TensorflowSharp
We have are using the [Unity Machine Learning Inference SDK](Inference-Engine.md) to
run the models inside of Unity. In order to use it, you will need to have an
appropriate backend downloaded.
This means that the Learning Brain is not natively supported since Unity scripts
are written in C#. Consequently, to enable the Learning Brain, we leverage a
third-party library
[TensorFlowSharp](https://github.com/migueldeicaza/TensorFlowSharp) which
provides .NET bindings to TensorFlow. Thus, when a Unity environment that
contains a Learning Brain is built, inference is performed via TensorFlowSharp.
We provide an additional in-depth overview of how to leverage
[TensorFlowSharp within Unity](Using-TensorFlow-Sharp-in-Unity.md)
which will become more
relevant once you install and start training behaviors within the ML-Agents
toolkit. Given the reliance on TensorFlowSharp, the Learning Brain is currently
marked as experimental.

2
docs/Background-Unity.md


* [Physics](https://docs.unity3d.com/Manual/PhysicsSection.html)
* [Ordering of event functions](https://docs.unity3d.com/Manual/ExecutionOrder.html)
(e.g. FixedUpdate, Update)
* [Prefabs](https://docs.unity3d.com/Manual/Prefabs.html)

101
docs/Basic-Guide.md


# Basic Guide
This guide will show you how to use a pre-trained model in an example Unity
environment, and show you how to train the model yourself.
environment (3D Ball) and show you how to train the model yourself.
If you are not familiar with the [Unity Engine](https://unity3d.com/unity), we
highly recommend the [Roll-a-ball

Equivalent or .NET 4.x Equivalent)**
6. Go to **File** > **Save Project**
## Setting up the Inference Engine
## Setting up TensorFlowSharp
We provide pre-trained models for all the agents in all our demo environments.
To be able to run those models, you'll first need to set-up the Inference
Engine. The Inference Engine is a general API to
run neural network models in Unity that leverages existing inference libraries such
as TensorFlowSharp and Apple's Core ML. Since the ML-Agents Toolkit uses TensorFlow
for training neural network models, the output model format is TensorFlow and
the model files include a `.tf` extension. Consequently, you need to install
the TensorFlowSharp backend to be able to run these models within the Unity
Editor. You can find instructions
on how to install the TensorFlowSharp backend [here](Inference-Engine.md).
Once the backend is installed, you will need to reimport the models : Right click
on the `.tf` model and select `Reimport`.
We provide pre-trained models (`.bytes` files) for all the agents
in all our demo environments. To be able to run those models, you'll
first need to set-up TensorFlowSharp support. Consequently, you need to install
the TensorFlowSharp plugin to be able to run these models within the Unity
Editor.
1. Download the [TensorFlowSharp Plugin](https://s3.amazonaws.com/unity-ml-agents/0.5/TFSharpPlugin.unitypackage)
2. Import it into Unity by double clicking the downloaded file. You can check
if it was successfully imported by checking the
TensorFlow files in the Project window under **Assets** > **ML-Agents** >
**Plugins** > **Computer**.
3. Go to **Edit** > **Project Settings** > **Player** and add `ENABLE_TENSORFLOW`
to the `Scripting Define Symbols` for each type of device you want to use
(**`PC, Mac and Linux Standalone`**, **`iOS`** or **`Android`**).
![Project Settings](images/project-settings.png)
**Note**: If you don't see anything under **Assets**, drag the
`UnitySDK/Assets/ML-Agents` folder under **Assets** within Project window.
![Imported TensorFlowsharp](images/imported-tensorflowsharp.png)
We've included pre-trained models for the 3D Ball example.
1. In the **Project** window, go to `Assets/ML-Agents/Examples/3DBall/Scenes` folder
1. In the **Project** window, go to the `Assets/ML-Agents/Examples/3DBall/Scenes` folder
2. In the **Project** window, go to `Assets/ML-Agents/Examples/3DBall/Prefabs` folder
and select the `Game/Platform` prefab.
3. In the `Ball 3D Agent` Component: Drag the **3DBallLearning** Brain located in
`Assets/ML-Agents/Examples/3DBall/Brains` into the `Brain` property of
the `Ball 3D Agent`.
4. Make sure that all of the Agents in the Scene now have **3DBallLearning** as `Brain`.
__Note__ : You can modify multiple game objects in a scene by selecting them all at
2. In the **Project** window, go to the `Assets/ML-Agents/Examples/3DBall/Prefabs` folder.
Expand `Game` and click on the `Platform` prefab. You should see the `Platform` prefab in the **Inspector** window.
**Note**: The platforms in the `3DBall` scene were created using the `Platform` prefab. Instead of updating all 12 platforms individually, you can update the `Platform` prefab instead.
![Platform Prefab](images/platform_prefab.png)
3. In the **Project** window, drag the **3DBallLearning** Brain located in
`Assets/ML-Agents/Examples/3DBall/Brains` into the `Brain` property under `Ball 3D Agent (Script)` component in the **Inspector** window.
![3dball learning brain](images/3dball_learning_brain.png)
4. You should notice that each `Platform` under each `Game` in the **Hierarchy** windows now contains **3DBallLearning** as `Brain`. __Note__ : You can modify multiple game objects in a scene by selecting them all at
5. In the **Project** window, locate the `Assets/ML-Agents/Examples/3DBall/TFModels`
5. In the **Project** window, click on the **3DBallLearning** Brain located in
`Assets/ML-Agents/Examples/3DBall/Brains`. You should see the properties in the **Inspector** window.
6. In the **Project** window, open the `Assets/ML-Agents/Examples/3DBall/TFModels`
6. Drag the `3DBallLearning` model file from the `Assets/ML-Agents/Examples/3DBall/TFModels`
folder to the **Model** field of the **3DBallLearning** Brain.
7. Click the **Play** button and you will see the platforms balance the balls
7. Drag the `3DBallLearning` model file from the `Assets/ML-Agents/Examples/3DBall/TFModels`
folder to the **Model** field of the **3DBallLearning** Brain in the **Inspector** window. __Note__ : All of the brains should now have `3DBallLearning` as the TensorFlow model in the `Model` property
8. Click the **Play** button and you will see the platforms balance the balls
![Running a pretrained model](images/running-a-pretrained-model.gif)
![Running a pretrained model](images/running-a-pretrained-model.gif)
## Using the Basics Jupyter Notebook

## Training the Brain with Reinforcement Learning
### Adding a Brain to the training session
### Setting up the enviornment for training
1. Assign the **3DBallLearning** Brain to the agents you would like to train.
__Note:__ You can assign the same Brain to multiple agents at once : To do so, you can
use the prefab system. When an agent is created from a prefab, modifying the prefab
will modify the agent as well. If the agent does not synchronize with the prefab, you
can hit the Revert button on top of the Inspector.
Alternatively, you can select multiple agents in the scene and modify their `Brain`
property all at once.
2. Select the **Ball3DAcademy** GameObject and make sure the **3DBallLearning** Brain
is in the Broadcast Hub. In order to train, you need to toggle the
`Control` checkbox.
__Note:__ Assigning a Brain to an agent (dragging a Brain into the `Brain` property of
1. Each platform agent needs an assigned `Learning Brain`. In this example, each platform agent was created using a prefab. To update all of the brains in each platform agent at once, you only need to update the platform agent prefab. In the **Project** window, go to the `Assets/ML-Agents/Examples/3DBall/Prefabs` folder. Expand `Game` and click on the `Platform` prefab. You should see the `Platform` prefab in the **Inspector** window. In the **Project** window, drag the **3DBallLearning** Brain located in `Assets/ML-Agents/Examples/3DBall/Brains` into the `Brain` property under `Ball 3D Agent (Script)` component in the **Inspector** window.
**Note**: The Unity prefab system will modify all instances of the agent properties in your scene. If the agent does not synchronize automatically with the prefab, you can hit the Revert button in the top of the **Inspector** window.
2. In the **Hierarchy** window, select `Ball3DAcademy`.
3. In the **Project** window, go to `Assets/ML-Agents/Examples/3DBall/Brains` folder and drag the **3DBallLearning** Brain to the `Brains` property under `Braodcast Hub` in the `Ball3DAcademy` object in the **Inspector** window. In order to train, make sure the `Control` checkbox is selected.
**Note:** Assigning a Brain to an agent (dragging a Brain into the `Brain` property of
![Set Brain to External](images/mlagents-SetBrainToTrain.png)
![Set Brain to External](images/mlagents-SetBrainToTrain.png)
### Training the environment

Editor"_ is displayed on the screen, you can press the :arrow_forward: button
in Unity to start training in the Editor.
**Note**: Alternatively, you can use an executable rather than the Editor to
**Note**: Alternatively, you can use an executable rather than the Editor to
perform training. Please refer to [this
page](Learning-Environment-Executable.md) for instructions on how to build and
use an executable.

### After training
You can press Ctrl+C to stop the training, and your trained model will be at
`models/<run-identifier>/<brain_name>.tf` where
`models/<run-identifier>/<brain_name>.bytes` where
`<brain_name>` is the name of the Brain corresponding to the model.
(**Note:** There is a known bug on Windows that causes the saving of the model to
fail when you early terminate the training, it's recommended to wait until Step

`UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/`.
2. Open the Unity Editor, and select the **3DBall** scene as described above.
3. Select the **3DBallLearning** Learning Brain from the Scene hierarchy.
5. Drag the `<brain_name>.tf` file from the Project window of
5. Drag the `<brain_name>.bytes` file from the Project window of
the Editor to the **Model** placeholder in the **3DBallLearning**
inspector window.
6. Press the :arrow_forward: button at the top of the Editor.

16
docs/FAQ.md


to [Setting Up The ML-Agents Toolkit Within
Unity](Installation.md#setting-up-ml-agent-within-unity) for solution.
## Cannot drag Model into Learning Brain
## TensorFlowSharp flag not turned on
You might not have the appropriate backend required to import the model. Refer to the
[Inference Engine](Inference-Engine.md) for more information on how to import backends
and reimport the asset.
If you have already imported the TensorFlowSharp plugin, but haven't set
ENABLE_TENSORFLOW flag for your scripting define symbols, you will see the
following error message:
```console
UnityAgentsException: The brain 3DBallLearning was set to inference mode but the Tensorflow library is not present in the Unity project.
```
This error message occurs because the TensorFlowSharp plugin won't be used
without the ENABLE_TENSORFLOW flag, refer to [Setting Up The ML-Agents Toolkit
Within Unity](Installation.md#setting-up-ml-agent-within-unity) for solution.
## Environment Permission Error

_Solution_: Look into the [log
files](https://docs.unity3d.com/Manual/LogFiles.html) generated by the Unity
Environment to figure what error happened.
# _Cause_: You have assigned HTTP_PROXY and HTTPS_PROXY values in your
* _Cause_: You have assigned HTTP_PROXY and HTTPS_PROXY values in your
environment variables. _Solution_: Remove these values and try again.
## Communication port {} still in use

58
docs/Getting-Started-with-Balance-Ball.md


In order to install and set up the ML-Agents toolkit, the Python dependencies
and Unity, see the [installation instructions](Installation.md).
## Understanding a Unity Environment (3D Balance Ball)
## Understanding the Unity Environment (3D Balance Ball)
An agent is an autonomous actor that observes and interacts with an
_environment_. In the context of Unity, an environment is a scene containing an

The Academy object for the scene is placed on the Ball3DAcademy GameObject. When
you look at an Academy component in the inspector, you can see several
properties that control how the environment works.
The **Broadcast Hub** keeps track of which Brains will send data during training,
If a Brain is added to the hub, his data will be sent to the external training
The **Broadcast Hub** keeps track of which Brains will send data during training.
If a Brain is added to the hub, the data from this Brain will be sent to the external training
control the agents linked to the Brain to train them.
The **Training** and **Inference Configuration** properties
control and train the agents linked to the Brain.
The **Training Configuration** and **Inference Configuration** properties
Typically, you set low graphics quality and a high time scale for the **Training
configuration** and a high graphics quality and the timescale to `1.0` for the
Typically, you would set a low graphics quality and timescale to greater `1.0` for the **Training
Configuration** and a high graphics quality and timescale to `1.0` for the
**Inference Configuration** .
**Note:** if you want to observe the environment during training, you can adjust

Another aspect of an environment to look at is the Academy implementation. Since
Another aspect of an environment is the Academy implementation. Since
the base Academy class is abstract, you must always define a subclass. There are
three functions you can implement, though they are all optional:

### Brain
Brains are assets that exist in your project folder. The Ball3DAgents are connected
to a Brain, for example : the **3DBallLearning**.
A Brain doesn't store any information about an Agent, it just
As of v0.6, a Brain is a Unity asset and exists within the `UnitySDK` folder. These brains (ex. **3DBallLearning.asset**) are loaded into each Agent object (ex. **Ball3DAgents**). A Brain doesn't store any information about an Agent, it just
returns the chosen action to the Agent. Thus, all Agents can share the same
Brain, but act independently. The Brain settings tell you quite a bit about how
returns the chosen action to the Agent. All Agents can share the same
Brain, but would act independently. The Brain settings tell you quite a bit about how
You can create Brain objects by selecting `Assets ->
Create -> ML-Agents -> Brain`. There are 3 kinds of Brains :
The **Learning Brain** is a Brain that uses a Neural Network to take decisions.
When the Brain is checked as `Control` in the Academy **Broadcast Hub**, the
external process will be taking decisions for the agents
and generate a neural network when the training is over. You can also use the
You can create new Brain assets by selecting `Assets ->
Create -> ML-Agents -> Brain`. There are 3 types of Brains.
The **Learning Brain** is a Brain that uses a trained neural network to make decisions.
When the `Control` box is checked in the Brains property under the **Broadcast Hub** in the Academy, the external process that is training the neural network will take over decision making for the agents
and ultimately generate a trained neural network. You can also use the
The **Heuristic** Brain allows you to hand-code the Agent's logic by extending
The **Heuristic** Brain allows you to hand-code the Agent logic by extending
can be useful when testing your agents and environment. If none of these types
of Brains do what you need, you can implement your own Brain.
can be useful when testing your agents and environment. You can also implement your own type of Brain.
In this tutorial, you will use a **Learning Brain** for training.
In this tutorial, you will use the **Learning Brain** for training.
#### Vector Observation Space

explaining it.
To train the agents within the Ball Balance environment, we will be using the
Python package. We have provided a convenient script called `mlagents-learn`
Python package. We have provided a convenient command called `mlagents-learn`
which accepts arguments used to configure both training and inference phases.
We can use `run_id` to identify the experiment and create a folder where the

use it with Agents having a **Learning Brain**.
__Note:__ Do not just close the Unity Window once the `Saved Model` message appears.
Either wait for the training process to close the window or press Ctrl+C at the
command-line prompt. If you simply close the window manually, the `.tf` file
command-line prompt. If you close the window manually, the `.bytes` file
### Setting up Inference Support
### Setting up TensorFlowSharp
In order to run neural network models inside of Unity, you will need to setup the
Inference Engine with an appropriate backend. See [here](Inference-Engine.md) for more
information.
Because TensorFlowSharp support is still experimental, it is disabled by
default. Please note that the `Learning` Brain inference can only be used with
TensorFlowSharp.
To set up the TensorFlowSharp Support, follow [Setting up ML-Agents Toolkit
within Unity](Basic-Guide.md#setting-up-ml-agents-within-unity) section. of the
Basic Guide page.
### Embedding the trained model into Unity

2
docs/Glossary.md


* **Agent** - Unity Component which produces observations and takes actions in
the environment. Agents actions are determined by decisions produced by a
linked Brain.
* **Brain** - Unity Component which makes decisions for the agents linked to it.
* **Brain** - Unity Asset which makes decisions for the agents linked to it.
* **Decision** - The specification produced by a Brain for an action to be
carried out given an observation.
* **Editor** - The Unity Editor, which may include any pane (e.g. Hierarchy,

329
docs/Learning-Environment-Create-New.md


steps:
1. Create an environment for your agents to live in. An environment can range
from a simple physical simulation containing a few objects to an entire game
or ecosystem.
from a simple physical simulation containing a few objects to an entire game
or ecosystem.
containing the environment. Your Academy class can implement a few optional
methods to update the scene independently of any agents. For example, you can
add, move, or delete agents and other entities in the environment.
3. Create one or more Brain assets by clicking `Assets -> Create -> ML-Agents
-> Bain`. And name them appropriately.
containing the environment. Your Academy class can implement a few optional
methods to update the scene independently of any agents. For example, you can
add, move, or delete agents and other entities in the environment.
3. Create one or more Brain assets by clicking **Assets** > **Create** >
**ML-Agents** > **Brain**, and naming them appropriately.
uses to observe its environment, to carry out assigned actions, and to
calculate the rewards used for reinforcement training. You can also implement
optional methods to reset the Agent when it has finished or failed its task.
uses to observe its environment, to carry out assigned actions, and to
calculate the rewards used for reinforcement training. You can also implement
optional methods to reset the Agent when it has finished or failed its task.
in the scene that represents the Agent in the simulation. Each Agent object
must be assigned a Brain object.
in the scene that represents the Agent in the simulation. Each Agent object
must be assigned a Brain object.
[run the training process](Training-ML-Agents.md).
[run the training process](Training-ML-Agents.md).
**Note:** If you are unfamiliar with Unity, refer to
[Learning the interface](https://docs.unity3d.com/Manual/LearningtheInterface.html)

importing the ML-Agents assets into it:
1. Launch the Unity Editor and create a new project named "RollerBall".
2. In a file system window, navigate to the folder containing your cloned
ML-Agents repository.
3. Drag the `ML-Agents` folder from `UnitySDK/Assets` to the Unity Editor
Project window.
4. Setup the ML-Agents toolkit by following the instructions [here](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Basic-Guide.md#setting-up-the-ml-agents-toolkit-within-unity).
2. Make sure that the Scripting Runtime Version for the project is set to use
**.NET 4.x Equivalent** (This is an experimental option in Unity 2017,
but is the default as of 2018.3.)
3. In a file system window, navigate to the folder containing your cloned
ML-Agents repository.
4. Drag the `ML-Agents` and `Gizmos` folders from `UnitySDK/Assets` to the Unity
Editor Project window.
Your Unity **Project** window should contain the following assets:

for the Agent to move around on, a Cube to act as the goal or target for the
agent to seek, and a Sphere to represent the Agent itself.
### Create the floor plane
### Create the Floor Plane
3. Select Plane to view its properties in the Inspector window.
4. Set Transform to Position = (0,0,0), Rotation = (0,0,0), Scale = (1,1,1).
3. Select the Floor Plane to view its properties in the Inspector window.
4. Set Transform to Position = (0, 0, 0), Rotation = (0, 0, 0), Scale = (1, 1, 1).
default-material to *floor*.
default-material to *LightGridFloorSquare* (or any suitable material of your choice).
name. This opens the **Object Picker** dialog so that you can choose the a
name. This opens the **Object Picker** dialog so that you can choose a
different material from the list of all materials currently in the project.)
![The Floor in the Inspector window](images/mlagents-NewTutFloor.png)

1. Right click in Hierarchy window, select 3D Object > Cube.
2. Name the GameObject "Target"
3. Select Target to view its properties in the Inspector window.
4. Set Transform to Position = (3,0.5,3), Rotation = (0,0,0), Scale = (1,1,1).
3. Select the Target Cube to view its properties in the Inspector window.
4. Set Transform to Position = (3, 0.5, 3), Rotation = (0, 0, 0), Scale = (1, 1, 1).
default-material to *Block*.
default-material to *Block*.
![The Target Cube in the Inspector window](images/mlagents-NewTutBlock.png)

2. Name the GameObject "RollerAgent"
3. Select Target to view its properties in the Inspector window.
4. Set Transform to Position = (0,0.5,0), Rotation = (0,0,0), Scale = (1,1,1).
3. Select the RollerAgent Sphere to view its properties in the Inspector window.
4. Set Transform to Position = (0, 0.5, 0), Rotation = (0, 0, 0), Scale = (1, 1, 1).
default-material to *checker 1*.
default-material to *CheckerSquare*.
7. Add the Physics/Rigidbody component to the Sphere. (Adding a Rigidbody)
7. Add the Physics/Rigidbody component to the Sphere.
![The Agent GameObject in the Inspector window](images/mlagents-NewTutSphere.png)

Next, edit the new `RollerAcademy` script:
1. In the Unity Project window, double-click the `RollerAcademy` script to open
it in your code editor. (By default new scripts are placed directly in the
**Assets** folder.)
2. In the editor, change the base class from `MonoBehaviour` to `Academy`.
3. Delete the `Start()` and `Update()` methods that were added by default.
it in your code editor. (By default new scripts are placed directly in the
**Assets** folder.)
2. In the code editor, add the statement, `using MLAgents;`.
3. Change the base class from `MonoBehaviour` to `Academy`.
4. Delete the `Start()` and `Update()` methods that were added by default.
In such a basic scene, we don't need the Academy to initialize, reset, or
otherwise control any objects in the environment so we have the simplest

![The Academy properties](images/mlagents-NewTutAcademy.png)
## Add Brains
## Add Brain Assets
(Learning, Heuristic or player) determines how the Brain makes decisions.
(Learning, Heuristic or Player) determines how the Brain makes decisions.
1. Go to `Assets -> Create -> ML-Agents` and select the type of Brain you want to
create. In this tutorial, we will create a **Learning Brain** and
a **Player Brain**.
1. Go to **Assets** > **Create** > **ML-Agents** and select the type of Brain asset
you want to create. For this tutorial, create a **Learning Brain** and
a **Player Brain**.
![Creating a Brain Asset](images/mlagents-NewTutBrain.png)
![The Brain default properties](images/mlagents-NewTutBrain.png)
## Implement an Agent
To create the Agent:

1. In the Unity Project window, double-click the `RollerAgent` script to open it
in your code editor.
2. In the editor, change the base class from `MonoBehaviour` to `Agent`.
2. In the editor, add the `using MLAgents;` statement and then change the base
class from `MonoBehaviour` to `Agent`.
leave it alone for now.
leave it alone for now.
So far, these are the basic steps that you would use to add ML-Agents to any
Unity project. Next, we will add the logic that will let our Agent learn to roll

this reference, add a public field of type `Transform` to the RollerAgent class.
Public fields of a component in Unity get displayed in the Inspector window,
allowing you to choose which GameObject to use as the target in the Unity
Editor. To reset the Agent's velocity (and later to apply force to move the
Editor.
To reset the Agent's velocity (and later to apply force to move the
agent) we need a reference to the Rigidbody component. A
[Rigidbody](https://docs.unity3d.com/ScriptReference/Rigidbody.html) is Unity's
primary element for physics simulation. (See

{
if (this.transform.position.y < 0)
{
// The Agent fell
this.transform.position = new Vector3(0, 0.5f, 0);
// If the Agent fell, zero its momentum
this.transform.position = new Vector3( 0, 0.5f, 0);
else
{
// Move the target to a new spot
Target.position = new Vector3(Random.value * 8 - 4,
0.5f,
Random.value * 8 - 4);
}
// Move the target to a new spot
Target.position = new Vector3(Random.value * 8 - 4,
0.5f,
Random.value * 8 - 4);
Next, let's implement the Agent.CollectObservations() function.
Next, let's implement the `Agent.CollectObservations()` method.
### Observing the Environment

In our case, the information our Agent collects includes:
* Position of the target. In general, it is better to use the relative position
of other objects rather than the absolute position for more generalizable
training. Note that the Agent only collects the x and z coordinates since the
floor is aligned with the x-z plane and the y component of the target's
position never changes.
* Position of the target.
// Calculate position relative to the target
Vector3 relativePosition = Target.position - this.transform.position;
// Position relative to the target
AddVectorObs(relativePosition.x / 5);
AddVectorObs(relativePosition.z / 5);
AddVectorObs(Target.position);
* Position of the Agent itself relative to the size of the floor (which is 10)
* Position of the Agent itself.
// Relative position
AddVectorObs(this.transform.position.x / 5);
AddVectorObs(this.transform.position.z / 5);
AddVectorObs(this.transform.position);
it doesn't overshoot the target and roll off the platform.
it doesn't overshoot the target and roll off the platform.
AddVectorObs(rBody.velocity.x / 5);
AddVectorObs(rBody.velocity.z / 5);
AddVectorObs(rBody.velocity.x);
AddVectorObs(rBody.velocity.z);
All the values are divided to normalize the inputs to the neural network to
the range [-1,1]. (The platform is a square which reaches from positions -5 to +5
thereby having an edge length of 10 units.)
In total, the state observation contains 6 values and we need to use the
In total, the state observation contains 8 values and we need to use the
// Calculate position relative to the target
Vector3 relativePosition = Target.position - this.transform.position;
// Position relative to the target
AddVectorObs(relativePosition.x / 5);
AddVectorObs(relativePosition.z / 5);
// Relative position
AddVectorObs(this.transform.position.x / 10);
AddVectorObs(this.transform.position.x / 10);
// Target and Agent positions
AddVectorObs(Target.position);
AddVectorObs(this.transform.position);
AddVectorObs(rBody.velocity.x/5);
AddVectorObs(rBody.velocity.z/5);
AddVectorObs(rBody.velocity.x);
AddVectorObs(rBody.velocity.z);
The final part of the Agent code is the Agent.AgentAction() function, which
receives the decision from the Brain.
The final part of the Agent code is the `Agent.AgentAction()` method, which
receives the decision from the Brain and assigns the reward.
the `Vector Action Space Type` and `Vector Action Space Size` settings of the
the `Vector Action` `Space Type` and `Space Size` settings of the
`Vector Action Size` to 2. The first element,`action[0]` determines the force
`Space Size` to 2. The first element,`action[0]` determines the force
to set `Vector Action Size` to 3. Each of these values returned by the network
are between `-1` and `1.` Note the Brain really has no idea what the values in
to set `Vector Action Size` to 3.) Note that the Brain really has no idea what the values in
The RollerAgent applies the values from the action[] array to its Rigidbody
The RollerAgent applies the values from the `action[]` array to its Rigidbody
component, `rBody`, using the `Rigidbody.AddForce` function:
```csharp

### Rewards
Reinforcement learning requires rewards. Assign rewards in the `AgentAction()`
function. The learning algorithm uses the rewards assigned to the Agent at each
step in the simulation and learning process to determine whether it is giving
function. The learning algorithm uses the rewards assigned to the Agent during
the simulation and learning process to determine whether it is giving
assigned task (reaching the Target cube, in this case) and punish the Agent if
it irrevocably fails (falls off the platform). You can sometimes speed up
training with sub-rewards that encourage behavior that helps the Agent complete
the task. For example, the RollerAgent reward system provides a small reward if
the Agent moves closer to the target in a step and a small negative reward at
each step which encourages the Agent to complete its task quickly.
assigned task. In this case, the Agent is given a reward of 1.0 for reaching the
Target cube.
When it does, the code increments the Agent.reward variable by 1.0 and marks the
agent as finished by setting the Agent to done.
When it does, the code calls the `Agent.SetReward()` method to assign a
reward of 1.0 and marks the agent as finished by calling the `Done()` method
on the Agent.
```csharp
float distanceToTarget = Vector3.Distance(this.transform.position,

{
AddReward(1.0f);
SetReward(1.0f);
Done();
}
```

`ResetOnDone` mechanism and doesn't set a `Max Steps` limit for the Academy (so
it never resets the environment).
It can also encourage an Agent to finish a task more quickly by assigning a
negative reward at each step:
```csharp
// Time penalty
AddReward(-0.05f);
```
Finally, to punish the Agent for falling off the platform, assign a large
negative reward and, of course, set the Agent to done so that it resets itself
in the next step:
Finally, if the Agent falls off the platform, set the Agent to done so that it can reset itself:
AddReward(-1.0f);
Done();
}
```

```csharp
public float speed = 10;
private float previousDistance = float.MaxValue;
// Actions, size = 2
Vector3 controlSignal = Vector3.zero;
controlSignal.x = vectorAction[0];
controlSignal.z = vectorAction[1];
rBody.AddForce(controlSignal * speed);
// Rewards
float distanceToTarget = Vector3.Distance(this.transform.position,
Target.position);

{
AddReward(1.0f);
SetReward(1.0f);
// Time penalty
AddReward(-0.05f);
AddReward(-1.0f);
// Actions, size = 2
Vector3 controlSignal = Vector3.zero;
controlSignal.x = vectorAction[0];
controlSignal.z = vectorAction[1];
rBody.AddForce(controlSignal * speed);
}
}
Note the `speed` and `previousDistance` class variables defined before the
Note the `speed` class variable defined before the
function. Since `speed` is public, you can set the value from the Inspector
window.

to connect everything together in the Unity Editor. This involves assigning the
Brain asset to the Agent, changing some of the Agent Components properties, and
Brain asset to the Agent, changing some of the Agent Component's properties, and
Brains to the **Broadcast Hub**.
2. Select the RollerAgent GameObject to show its properties in the Inspector
window.
3. Drag the Brain `RollerBallPlayer` from the Project window to the
RollerAgent `Brain` field.
4. Change `Decision Frequency` from `1` to `5`.
Brains to the **Broadcast Hub**.
2. Select the **RollerAgent** GameObject to show its properties in the Inspector
window.
3. Drag the Brain **RollerBallPlayer** from the Project window to the
RollerAgent **Brain** field.
4. Change **Decision Frequency** from `1` to `10`.
5. Drag the Target GameObject from the Hierarchy window to the RollerAgent
Target field.
Also, drag the Target GameObject from the Hierarchy window to the RollerAgent
Target field.
Finally, select the **RollerBallBrain** Asset in the **Project** window so that you can
see its properties in the Inspector window. Set the following properties:
Finally, select the the `RollerBallBrain` and `RollerBallPlayer` Brain assets
so that you can edit their properties in the Inspector window. Set the following
properties on both of them:
* `Vector Observation` `Space Size` = 8
* `Vector Action` `Space Type` = **Continuous**
* `Vector Action` `Space Size` = 2
* `Vector Observation Space Size` = 6
* `Vector Action Space Type` = **Continuous**
* `Vector Action Space Size` = 2
Select the **RollerBallPlayer** Asset in the **Project** window and set the same
property values.
Now you are ready to test the environment before training.

positive values and one to specify negative values for each action, for a total
of four keys.
1. Select the `RollerBallPlayer` Brain to view its properties in the Inspector.
2. Expand the **Continuous Player Actions** dictionary (only visible when using
a **PlayerBrain**).
1. Select the `RollerBallPlayer` Aset to view its properties in the Inspector.
2. Expand the **Key Continuous Player Actions** dictionary (only visible when using
a **PlayerBrain**).
3. Set **Size** to 4.
4. Set the following mappings:

`env_name` to the name of the environment file you specify when building this
environment.
## Training the Environment
Then drag the `RollerBallBrain` into the Academy's `Broadcast Hub` and check
to `Control` checkbox for that brain. From there, the process is
Then, select the Academy GameObject and check the `Control` checkbox for
the RollerBallBrain item in the **Broadcast Hub** list. From there, the process is
The hyperparameters for training are specified in the configuration file that you ls
pass to the `mlagents-learn` program. Using the default settings specified
in the `config/trainer_config.yaml` file (in your ml-agents folder), the
RollerAgent takes about 300,000 steps to train. However, you can change the
following hyperparameters to speed up training considerably (to under 20,000 steps):
batch_size: 10
buffer_size: 100
Since this example creates a very simple training environment with only a few inputs
and outputs, using small batch and buffer sizes speeds up the training considerably.
However, if you add more complexity to the environment or change the reward or
observation functions, you might also find that training performs better with different
hyperparameter values.
**Note:** In addition to setting these hyperparameter values, the Agent
**DecisionFrequency** parameter has a large effect on training time and success.
A larger value reduces the number of decisions the training algorithm has to consider and,
in this simple environment, speeds up training.
To train in the editor, run the following Python command from a Terminal or Console
window before pressing play:
mlagents-learn config/config.yaml --run-id=RollerBall-1 --train
(where `config.yaml` is a copy of `trainer_config.yaml` that you have edited
to change the `batch_size` and `buffer_size` hyperparameters for your brain.)
**Note:** If you get a `command not found` error when running this command, make sure
that you have followed the *Install Python and mlagents Package* section of the
ML-Agents [Installation](Installation.md) instructions.
To monitor the statistics of Agent performance during training, use
[TensorBoard](Using-Tensorboard.md).
![TensorBoard statistics display](images/mlagents-RollerAgentStats.png)
In particular, the *cumulative_reward* and *value_estimate* statistics show how
well the Agent is achieving the task. In this example, the maximum reward an
Agent can earn is 1.0, so these statistics approach that value when the Agent
has successfully *solved* the problem.
**Note:** If you use TensorBoard, always increment or change the `run-id`
you pass to the `mlagents-learn` command for each training run. If you use
the same id value, the statistics for multiple runs are combined and become
difficult to interpret.
## Review: Scene Layout
This section briefly reviews how to organize your scene when using Agents in

to use Unity ML-Agents:
* Academy
* Agents
You also need to have brain assets linked appropriately to Agents and to Academy
to use Unity ML-Agents: an Academy and one or more Agents. You also need to
have brain assets linked appropriately to your Agents and to the Academy.
* You can only train Learning Brains that have been included into the Academy's
Broadcast Hub.
* You can only train Learning Brains that have been added to the Academy's Broadcast Hub list.

10
docs/Learning-Environment-Design-Learning-Brains.md


To use a graph model:
1. Select the **Learning Brain** asset in the **Project** window of the Unity Editor.
**Note:** In order to use the **Learning** Brain, you have appropriate backend for the
Inference Engine. See [here](Inference-Engine.md).
**Note:** In order to use the **Learning** Brain with inference, you need to have
TensorFlowSharp enabled. Refer to [this section](Basic-Guide.md#setting-up-ml-agents-within-unity) for more information.
2. Import the `model_name` file produced by the PPO training
program. (Where `model_name` is the name of the model file, which is
constructed from the name of your Unity environment executable and the run-id

[import assets into Unity](https://docs.unity3d.com/Manual/ImportingAssets.html)
in various ways. The easiest way is to simply drag the file into the
**Project** window and drop it into an appropriate folder.
3. Once the `model_name.tf` file is imported, drag it from the **Project**
3. Once the `model_name.bytes` file is imported, drag it from the **Project**
window to the **Model** field of the Brain component.
If you are using a model produced by the ML-Agents `mlagents-learn` command, use

The default values of the TensorFlow graph parameters work with the model
produced by the PPO and BC training code in the ML-Agents SDK. To use a default
ML-Agents model, the only parameter that you need to set is the `Model`,
which must be set to the `.tf` file containing the trained model itself.
which must be set to the `.bytes` file containing the trained model itself.
* `Model` : This must be the `.tf` file corresponding to the pre-trained
* `Model` : This must be the `.bytes` file corresponding to the pre-trained
TensorFlow graph. (You must first drag this file into your Project window
and then from the Resources folder into the inspector)

2
docs/Learning-Environment-Design-Player-Brains.md


| | **Element 0–N** | The mapping of keys to action values. |
| | **Key** | The key on the keyboard. |
| | **Branch Index** | The element of the Agent's action vector to set when this key is pressed. The index value cannot exceed the size of the Action Space (minus 1, since it is an array index). |
| | **Value** | The value to send to the Agent as its action when the mapped key is pressed. Cannot exceed the max value for the associated branch (minus 1, since it is an array index). |
| | **Value** | The value to send to the Agent as its action when the mapped key is pressed. Cannot exceed the max value for the associated branch (minus 1, since it is an array index). Note that if no key is pressed for that branch, the default action will be 0. |
For more information about the Unity input system, see
[Input](https://docs.unity3d.com/ScriptReference/Input.html).

3
docs/Learning-Environment-Examples.md


rotations for joints.
* Visual Observations: None.
* Reset Parameters: None
* Benchmark Mean Reward: 2000
* Benchmark Mean Reward for `CrawlerStaticTarget`: 2000
* Benchmark Mean Reward for `CrawlerDynamicTarget`: 400
## [Banana Collector](https://youtu.be/heVMs3t9qSk)

13
docs/Learning-Environment-Executable.md


3. Using the file dialog that opens, locate the `UnitySDK` folder within the
ML-Agents project and click **Open**.
4. In the **Project** window, navigate to the folder
`Assets/ML-Agents/Examples/3DBall/`.
`Assets/ML-Agents/Examples/3DBall/Scenes/`.
5. Double-click the `3DBall` file to load the scene containing the Balance Ball
environment.

to be able to control your agents from Python, you will need to put the Brain
controlling the Agents to be a **Learning Brain** and drag it into the
Academy's `Broadcast Hub` with the `Control` checkbox checked.
Academy's `Broadcast Hub` with the `Control` checkbox checked. In the 3DBall
scene, this can be done in the Platform GameObject within the Game prefab in
`Assets/ML-Agents/Examples/3DBall/Prefabs/`, or in each instance of the
Platform in the Scene.
Next, we want the set up scene to play correctly when the training process
launches our environment executable. This means:

* (optional) Select “Development Build” to [log debug
messages](https://docs.unity3d.com/Manual/LogFiles.html).
5. If any scenes are shown in the **Scenes in Build** list, make sure that the
3DBall Scene is the only one checked. (If the list is empty, than only the
3DBall Scene is the only one checked. (If the list is empty, then only the
current scene is included in the build).
6. Click **Build**:
* In the File dialog, navigate to your ML-Agents directory.

```
You can press Ctrl+C to stop the training, and your trained model will be at
`models/<run-identifier>/<brain_name>.tf`, which corresponds
`models/<run-identifier>/<brain_name>.bytes`, which corresponds
to your model's latest checkpoint. (**Note:** There is a known bug on Windows
that causes the saving of the model to fail when you early terminate the
training, it's recommended to wait until Step has reached the max_steps

`UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/`.
2. Open the Unity Editor, and select the **3DBall** scene as described above.
3. Select the **Ball3DLearning** object from the Project window.
5. Drag the `<brain_name>.tf` file from the Project window of
5. Drag the `<brain_name>.bytes` file from the Project window of
the Editor to the **Model** placeholder in the **Ball3DLearning**
inspector window.
6. Remove the **Ball3DLearning** from the Academy's `Broadcast Hub`

4
docs/ML-Agents-Overview.md


model. This model is then embedded within the Learning Brain during inference to
generate the optimal actions for all Agents linked to that Brain.
**Note that our Learning Brain is currently experimental as it is limited to TensorFlow
models and leverages the third-party
[TensorFlowSharp](https://github.com/migueldeicaza/TensorFlowSharp) library.**
The
[Getting Started with the 3D Balance Ball Example](Getting-Started-with-Balance-Ball.md)
tutorial covers this training mode with the **3D Balance Ball** sample environment.

15
docs/Migrating.md


using the search bar of the `Hierarchy` window with the word `Agent`.
* We replaced the **Internal** and **External** Brain with **Learning Brain**.
When you need to train a model, you need to drag it into the `Training Hub`
When you need to train a model, you need to drag it into the `Broadcast Hub`
inside the `Academy` and check the `Control` checkbox.
* We removed the `Broadcast` checkbox of the Brain, to use the broadcast
functionality, you need to drag the Brain into the `Broadcast Hub`.

* We have changed the way ML-Agents models perform inference. All previous `.bytes`
files can no longer be used (you will have to retrain them). The models
produced by the training process and the shipped models have now a `.tf`
extension and use TensorflowSharp as a backend for the
[Inference Engine](Inference-Engine.md).
* To use a `.tf` model, drag it inside the `Model` property of the `Learning Brain`
* The **Learning Brain** graph scope, placeholder names, output names and custom
placeholders can no longer be modified.
#### Steps to Migrate

from the `mlagents-learn` Python script, you need to drag the relevant
`LearningBrain` ScriptableObjects used in your scene into entries
into this list.
* You will need to delete the previous TensorFlowSharp package
and install the new one to do inference. To correctly delete the previous
TensorFlowSharp package, Delete all of the files under `ML-Agents/Plugins`
folder except the files under `ML-Agents/Plugins/ProtoBuffer`.
## Migrating from ML-Agents toolkit v0.4 to v0.5

2
docs/Readme.md


* [Using TensorBoard to Observe Training](Using-Tensorboard.md)
## Inference
* [Unity Machine Learning Inference SDK](Inference-Engine.md)
* [TensorFlowSharp in Unity (Experimental)](Using-TensorFlow-Sharp-in-Unity.md)
## Help

6
docs/Training-Imitation-Learning.md


to perform, rather than attempting to have it learn via trial-and-error methods.
Consider our
[running example](ML-Agents-Overview.md#running-example-training-npc-behaviors)
of training a medic NPC : instead of indirectly training a medic with the help
of training a medic NPC. Instead of indirectly training a medic with the help
of a reward function, we can give the medic real world examples of observations
from the game and actions from a game controller to guide the medic's behavior.
Imitation Learning uses pairs of observations and actions from

3. Build the scene, assigning the agent a Learning Brain, and set the Brain to Control in the Broadcast Hub. For more information on Brains, see [here](Learning-Environment-Design-Brains.md).
4. Open the `config/offline_bc_config.yaml` file.
5. Modify the `demo_path` parameter in the file to reference the path to the demonstration file recorded in step 2. In our case this is: `./UnitySDK/Assets/Demonstrations/AgentRecording.demo`
6. Launch `mlagent-learn`, and providing `./config/offline_bc_config.yaml` as the config parameter, and your environment as the `--env` parameter.
6. Launch `mlagent-learn`, providing `./config/offline_bc_config.yaml` as the config parameter, and include the `--run-id` and `--train` as usual. Provide your environment as the `--env` parameter if it has been compiled as standalone, or omit to train in the editor.
7. (Optional) Observe training performance using Tensorboard.
This will use the demonstration file to train a neural network driven agent to directly imitate the actions provided in the demonstration. The environment will launch and be used for evaluating the agent's performance during training.

similarly to the demonstrations.
9. Once the Student Agents are exhibiting the desired behavior, end the training
process with `CTL+C` from the command line.
10. Move the resulting `*.tf` file into the `TFModels` subdirectory of the
10. Move the resulting `*.bytes` file into the `TFModels` subdirectory of the
Assets folder (or a subdirectory within Assets of your choosing) , and use
with `Learning` Brain.

2
docs/Training-ML-Agents.md


When training is finished, you can find the saved model in the `models` folder
under the assigned run-id — in the cats example, the path to the model would be
`models/cob_1/CatsOnBicycles_cob_1.tf`.
`models/cob_1/CatsOnBicycles_cob_1.bytes`.
While this example used the default training hyperparameters, you can edit the
[training_config.yaml file](#training-config-file) with a text editor to set

999
docs/images/mlagents-3DBallHierarchy.png
文件差异内容过多而无法显示
查看文件

277
docs/images/mlagents-NewProject.png

之前 之后
宽度: 499  |  高度: 361  |  大小: 48 KiB

360
docs/images/mlagents-NewTutAcademy.png

之前 之后
宽度: 451  |  高度: 210  |  大小: 36 KiB

999
docs/images/mlagents-NewTutAssignBrain.png
文件差异内容过多而无法显示
查看文件

502
docs/images/mlagents-NewTutBlock.png

之前 之后
宽度: 438  |  高度: 708  |  大小: 101 KiB

536
docs/images/mlagents-NewTutFloor.png

之前 之后
宽度: 438  |  高度: 627  |  大小: 94 KiB

132
docs/images/mlagents-NewTutHierarchy.png

之前 之后
宽度: 307  |  高度: 271  |  大小: 29 KiB

507
docs/images/mlagents-NewTutSphere.png

之前 之后
宽度: 438  |  高度: 624  |  大小: 93 KiB

819
docs/images/mlagents-NewTutSplash.png

之前 之后
宽度: 653  |  高度: 287  |  大小: 88 KiB

999
docs/images/mlagents-Open3DBall.png
文件差异内容过多而无法显示
查看文件

75
gym-unity/README.md


### Example - DQN Baseline
In order to train an agent to play the `GridWorld` environment using the
Baselines DQN algorithm, create a file called `train_unity.py` within the
`baselines/deepq/experiments` subfolder of the baselines repository. This file
will be a modification of the `run_atari.py` file within the same folder. Then
create and `/envs/` directory within the repository, and build the GridWorld
environment to that directory. For more information on building Unity
environments, see [here](../docs/Learning-Environment-Executable.md). Add the
following code to the `train_unity.py` file:
Baselines DQN algorithm, you first need to install the baselines package using
pip:
```
pip install git+git://github.com/openai/baselines
```
Next, create a file called `train_unity.py`. Then create an `/envs/` directory
and build the GridWorld environment to that directory. For more information on
building Unity environments, see
[here](../docs/Learning-Environment-Executable.md). Add the following code to
the `train_unity.py` file:
```python
import gym

def main():
env = UnityEnv("./envs/GridWorld", 0, use_visual=True)
model = deepq.models.cnn_to_mlp(
convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],
hiddens=[256],
dueling=True,
)
q_func=model,
"mlp",
max_timesteps=100000,
total_timesteps=100000,
print_freq=10,
print_freq=10
)
print("Saving model to unity_model.pkl")
act.save("unity_model.pkl")

repository:
```sh
python -m baselines.deepq.experiments.train_unity
python -m train_unity
the example provided above. In most cases, the primary changes needed to use a
Unity environment are to import `UnityEnv`, and to replace the environment
the examples from the baselines package. In most cases, the primary changes needed
to use a Unity environment are to import `UnityEnv`, and to replace the environment
creation code, typically `gym.make()`, with a call to `UnityEnv(env_path)`
passing the environment binary path.

Some algorithms will make use of `make_atari_env()` or `make_mujoco_env()`
functions. These are defined in `baselines/common/cmd_util.py`. In order to use
Unity environments for these algorithms, add the following import statement and
function to `cmd_utils.py`:
Some algorithms will make use of `make_env()` or `make_mujoco_env()`
functions. You can define a similar function for Unity environments. An example of
such a method using the PPO2 baseline:
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.bench import Monitor
from baselines import logger
import baselines.ppo2.ppo2 as ppo2
import os
try:
from mpi4py import MPI
except ImportError:
MPI = None
def make_env(rank): # pylint: disable=C0111
def make_env(rank, use_visual=True): # pylint: disable=C0111
env = UnityEnv(env_directory, rank, use_visual=True)
env = UnityEnv(env_directory, rank, use_visual=use_visual)
env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))
return env
return _thunk

rank = MPI.COMM_WORLD.Get_rank()
env = UnityEnv(env_directory, rank, use_visual=False)
env = Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))
return env
rank = MPI.COMM_WORLD.Get_rank() if MPI else 0
return make_env(rank, use_visual=False)
def main():
env = make_unity_env('./envs/GridWorld', 4, True)
ppo2.learn(
network="mlp",
env=env,
total_timesteps=100000,
lr=1e-3,
)
if __name__ == '__main__':
main()
```

20
ml-agents/mlagents/envs/environment.py


class UnityEnvironment(object):
SCALAR_ACTION_TYPES = (int, np.int32, np.int64, float, np.float32, np.float64)
SINGLE_BRAIN_ACTION_TYPES = SCALAR_ACTION_TYPES + (list, np.ndarray)
SINGLE_BRAIN_TEXT_TYPES = (str, list, np.ndarray)
def __init__(self, file_name=None, worker_id=0,
base_port=5005, seed=0,
docker_training=False, no_graphics=False):

atexit.register(self._close)
self.port = base_port + worker_id
self._buffer_size = 12000
self._version_ = "API-5"
self._version_ = "API-6"
self._loaded = False # If true, this means the environment was successfully loaded
self.proc1 = None # The process that is started. If None, no process was started
self.communicator = self.get_communicator(worker_id, base_port)

# Check that environment is loaded, and episode is currently running.
if self._loaded and not self._global_done and self._global_done is not None:
if isinstance(vector_action, (int, np.int_, float, np.float_, list, np.ndarray)):
if isinstance(vector_action, self.SINGLE_BRAIN_ACTION_TYPES):
if self._num_external_brains == 1:
vector_action = {self._external_brain_names[0]: vector_action}
elif self._num_external_brains > 1:

"There are no external brains in the environment, "
"step cannot take a vector_action input")
if isinstance(memory, (int, np.int_, float, np.float_, list, np.ndarray)):
if isinstance(memory, self.SINGLE_BRAIN_ACTION_TYPES):
if self._num_external_brains == 1:
memory = {self._external_brain_names[0]: memory}
elif self._num_external_brains > 1:

"There are no external brains in the environment, "
"step cannot take a memory input")
if isinstance(text_action, (str, list, np.ndarray)):
if isinstance(text_action, self.SINGLE_BRAIN_TEXT_TYPES):
if self._num_external_brains == 1:
text_action = {self._external_brain_names[0]: text_action}
elif self._num_external_brains > 1:

"There are no external brains in the environment, "
"step cannot take a value input")
if isinstance(value, (int, np.int_, float, np.float_, list, np.ndarray)):
if isinstance(value, self.SINGLE_BRAIN_ACTION_TYPES):
if self._num_external_brains == 1:
value = {self._external_brain_names[0]: value}
elif self._num_external_brains > 1:

if self.proc1 is not None:
self.proc1.kill()
@staticmethod
def _flatten(arr):
@classmethod
def _flatten(cls, arr):
if isinstance(arr, (int, np.int_, float, np.float_)):
if isinstance(arr, cls.SCALAR_ACTION_TYPES):
arr = [float(arr)]
if isinstance(arr, np.ndarray):
arr = arr.tolist()

16
ml-agents/mlagents/envs/exception.py


"You can check the logfile for more information at {}".format(log_file_path))
except:
logger.error("An error might have occured in the environment. "
"No UnitySDK.log file could be found.")
"No UnitySDK.log file could be found.")
class UnityWorkerInUseException(UnityException):
"""
This error occurs when the port for a certain worker ID is already reserved.
"""
MESSAGE_TEMPLATE = (
"Couldn't start socket communication because worker number {} is still in use. "
"You may need to manually close a previously opened environment "
"or use a different worker number.")
def __init__(self, worker_id):
message = self.MESSAGE_TEMPLATE.format(str(worker_id))
super(UnityWorkerInUseException, self).__init__(message)

44
ml-agents/mlagents/envs/rpc_communicator.py


import logging
import grpc
import socket
from multiprocessing import Pipe
from concurrent.futures import ThreadPoolExecutor

from .exception import UnityTimeOutException
from .exception import UnityTimeOutException, UnityWorkerInUseException
logger = logging.getLogger("mlagents.envs")

class RpcCommunicator(Communicator):
def __init__(self, worker_id=0,
base_port=5005):
def __init__(self, worker_id=0, base_port=5005):
"""
Python side of the grpc communication. Python is the server and Unity the client

self.server = None
self.unity_to_external = None
self.is_open = False
self.create_server()
def initialize(self, inputs: UnityInput) -> UnityOutput:
def create_server(self):
"""
Creates the GRPC server.
"""
self.check_port(self.port)
self.server.add_insecure_port('[::]:'+str(self.port))
self.server.add_insecure_port('localhost:' + str(self.port))
except :
raise UnityTimeOutException(
"Couldn't start socket communication because worker number {} is still in use. "
"You may need to manually close a previously opened environment "
"or use a different worker number.".format(str(self.worker_id)))
self.is_open = True
except:
raise UnityWorkerInUseException(self.worker_id)
def check_port(self, port):
"""
Attempts to bind to the requested communicator port, checking if it is already in use.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("localhost", port))
except socket.error:
raise UnityWorkerInUseException(self.worker_id)
finally:
s.close()
def initialize(self, inputs: UnityInput) -> UnityOutput:
if not self.unity_to_external.parent_conn.poll(30):
raise UnityTimeOutException(
"The Unity environment took too long to respond. Make sure that :\n"

aca_param = self.unity_to_external.parent_conn.recv().unity_output
self.is_open = True
message = UnityMessage()
message.header.status = 200
message.unity_input.CopyFrom(inputs)

self.unity_to_external.parent_conn.close()
self.server.stop(False)
self.is_open = False

9
ml-agents/mlagents/trainers/bc/offline_trainer.py


# Contains an implementation of Behavioral Cloning Algorithm
import logging
import copy
from mlagents.trainers.bc.trainer import BCTrainer
from mlagents.trainers.demo_loader import demo_to_buffer

trainer_parameters['demo_path'],
self.policy.sequence_length)
print(brain.__dict__)
print(brain_params.__dict__)
if brain.__dict__ != brain_params.__dict__:
policy_brain = copy.deepcopy(brain.__dict__)
expert_brain = copy.deepcopy(brain_params.__dict__)
policy_brain.pop('brain_name')
expert_brain.pop('brain_name')
if expert_brain != policy_brain:
raise UnityTrainerException("The provided demonstration is not compatible with the "
"brain being used for performance evaluation.")

2
ml-agents/mlagents/trainers/demo_loader.py


current_brain_info = brain_infos[idx]
next_brain_info = brain_infos[idx + 1]
demo_buffer[0].last_brain_info = current_brain_info
demo_buffer[0]['done'].append(next_brain_info.local_done[0])
demo_buffer[0]['rewards'].append(next_brain_info.rewards[0])
for i in range(brain_params.number_visual_observations):
demo_buffer[0]['visual_obs%d' % i] \
.append(current_brain_info.visual_observations[i][0])

19
ml-agents/mlagents/trainers/learn.py


import logging
import os
import multiprocessing
from multiprocessing import Process, Queue
import numpy as np
from docopt import docopt

def run_training(sub_id, run_seed, run_options):
def run_training(sub_id, run_seed, run_options, process_queue):
:param process_queue: Queue used to send signal back to main.
:param sub_id: Unique id for training session.
:param run_seed: Random seed used for training.
:param run_options: Command line arguments for training.

no_graphics = run_options['--no-graphics']
trainer_config_path = run_options['<trainer-config-path>']
# Create controller and begin training.
# Create controller and launch environment.
# Signal that environment has been launched.
process_queue.put(True)
# Begin training
tc.start_learning()

for i in range(num_runs):
if seed == -1:
run_seed = np.random.randint(0, 10000)
p = multiprocessing.Process(target=run_training, args=(i, run_seed, options))
process_queue = Queue()
p = Process(target=run_training, args=(i, run_seed, options, process_queue))
# Wait for signal that environment has successfully launched
while process_queue.get() is not True:
continue

8
ml-agents/mlagents/trainers/models.py


action_idx = [0] + list(np.cumsum(action_size))
branches_logits = [all_logits[:, action_idx[i]:action_idx[i + 1]] for i in range(len(action_size))]
branch_masks = [action_masks[:, action_idx[i]:action_idx[i + 1]] for i in range(len(action_size))]
raw_probs = [tf.multiply(tf.nn.softmax(branches_logits[k]), branch_masks[k]) + 1.0e-10
raw_probs = [tf.multiply(tf.nn.softmax(branches_logits[k]) + 1.0e-10, branch_masks[k])
tf.divide(raw_probs[k], tf.reduce_sum(raw_probs[k] + 1.0e-10, axis=1, keepdims=True))
for k in range(len(action_size))]
tf.divide(raw_probs[k], tf.reduce_sum(raw_probs[k], axis=1, keepdims=True))
for k in range(len(action_size))]
return output, tf.concat([tf.log(normalized_probs[k]) for k in range(len(action_size))], axis=1)
return output, tf.concat([tf.log(normalized_probs[k] + 1.0e-10) for k in range(len(action_size))], axis=1)
def create_observation_streams(self, num_streams, h_size, num_layers):
"""

2
ml-agents/mlagents/trainers/policy.py


input_binary=True,
input_checkpoint=ckpt.model_checkpoint_path,
output_node_names=target_nodes,
output_graph=(self.model_path + '.tf'),
output_graph=(self.model_path + '.bytes'),
clear_devices=True, initializer_nodes='', input_saver='',
restore_op_name='save/restore_all',
filename_tensor_name='save/Const:0')

2
ml-agents/setup.py


setup(
name='mlagents',
version='0.5.0',
version='0.6.0',
description='Unity Machine Learning Agents',
long_description=long_description,
long_description_content_type='text/markdown',

4
ml-agents/tests/envs/test_envs.py


BrainInfo
from tests.mock_communicator import MockCommunicator
def test_handles_bad_filename():
@mock.patch('mlagents.envs.UnityEnvironment.get_communicator')
def test_handles_bad_filename(get_communicator):
with pytest.raises(UnityEnvironmentException):
UnityEnvironment(' ')

2
ml-agents/tests/mock_communicator.py


)
rl_init = UnityRLInitializationOutput(
name="RealFakeAcademy",
version="API-5",
version="API-6",
log_path="",
brain_parameters=[bp]
)

4
ml-agents/tests/trainers/test_demo_loader.py


import unittest.mock as mock
import pytest
import os
brain_parameters, brain_infos, total_expected = load_demonstration('./tests/trainers/test.demo')
path_prefix = os.path.dirname(os.path.abspath(__file__))
brain_parameters, brain_infos, total_expected = load_demonstration(path_prefix+'/test.demo')
assert (brain_parameters.brain_name == "Ball3DBrain")
assert (brain_parameters.vector_observation_space_size == 8)
assert (len(brain_infos) == total_expected)

4
ml-agents/tests/trainers/test_trainer_controller.py


import json
import unittest.mock as mock
import os
import yaml
import pytest

'''
default:
trainer: offline_bc
demo_path: ./tests/trainers/test.demo
demo_path: '''
+ os.path.dirname(os.path.abspath(__file__)) + '''/test.demo
batches_per_epoch: 16
batch_size: 32
beta: 5.0e-3

5
SURVEY.md


# Unity ML-Agents Toolkit Survey
Your opinion matters a great deal to us. Only by hearing your thoughts on the Unity ML-Agents Toolkit can we continue to improve and grow. Please take a few minutes to let us know about it.
[Fill out the survey](https://goo.gl/forms/qFMYSYr5TlINvG6f1)

224
UnitySDK/Assets/ML-Agents/Editor/Tests/MultinomialTest.cs


using System;
using NUnit.Framework;
using UnityEngine;
using MLAgents.InferenceBrain;
using MLAgents.InferenceBrain.Utils;
namespace MLAgents.Tests
{
public class MultinomialTest
{
[Test]
public void TestEvalP()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
Data = new float[1, 3] {{0.1f, 0.2f, 0.7f}},
ValueType = Tensor.TensorType.FloatingPoint
};
Tensor dst = new Tensor
{
Data = new float[1, 3],
ValueType = Tensor.TensorType.FloatingPoint
};
m.Eval(src, dst);
float[] reference = {2, 2, 1};
int i = 0;
foreach (var f in dst.Data)
{
Assert.AreEqual(reference[i], f);
++i;
}
}
[Test]
public void TestEvalLogits()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
Data = new float[1, 3] {{Mathf.Log(0.1f) - 50, Mathf.Log(0.2f) - 50, Mathf.Log(0.7f) - 50}},
ValueType = Tensor.TensorType.FloatingPoint
};
Tensor dst = new Tensor
{
Data = new float[1, 3],
ValueType = Tensor.TensorType.FloatingPoint
};
m.Eval(src, dst);
float[] reference = {2, 2, 2};
int i = 0;
foreach (var f in dst.Data)
{
Assert.AreEqual(reference[i], f);
++i;
}
}
[Test]
public void TestEvalBatching()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
Data = new float[2, 3]
{
{Mathf.Log(0.1f) - 50, Mathf.Log(0.2f) - 50, Mathf.Log(0.7f) - 50},
{Mathf.Log(0.3f) - 25, Mathf.Log(0.4f) - 25, Mathf.Log(0.3f) - 25},
},
ValueType = Tensor.TensorType.FloatingPoint
};
Tensor dst = new Tensor
{
Data = new float[2, 3],
ValueType = Tensor.TensorType.FloatingPoint
};
m.Eval(src, dst);
float[] reference = {2, 2, 2, 0, 1, 0};
int i = 0;
foreach (var f in dst.Data)
{
Assert.AreEqual(reference[i], f);
++i;
}
}
[Test]
public void TestSrcInt()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.Integer
};
Assert.Throws<NotImplementedException>(() => m.Eval(src, null));
}
[Test]
public void TestDstInt()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.Integer
};
Assert.Throws<ArgumentException>(() => m.Eval(src, dst));
}
[Test]
public void TestSrcDataNull()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint
};
Assert.Throws<ArgumentNullException>(() => m.Eval(src, dst));
}
[Test]
public void TestDstDataNull()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1]
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint
};
Assert.Throws<ArgumentNullException>(() => m.Eval(src, dst));
}
[Test]
public void TestSrcWrongShape()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1]
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1]
};
Assert.Throws<ArgumentException>(() => m.Eval(src, dst));
}
[Test]
public void TestDstWrongShape()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1, 1]
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1]
};
Assert.Throws<ArgumentException>(() => m.Eval(src, dst));
}
[Test]
public void TestUnequalBatchSize()
{
Multinomial m = new Multinomial(2018);
Tensor src = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[1, 1]
};
Tensor dst = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = new float[2, 1]
};
Assert.Throws<ArgumentException>(() => m.Eval(src, dst));
}
}
}

122
UnitySDK/Assets/ML-Agents/Editor/Tests/RandomNormalTest.cs


using System;
using NUnit.Framework;
using MLAgents.InferenceBrain;
using MLAgents.InferenceBrain.Utils;
namespace MLAgents.Tests
{
public class RandomNormalTest
{
[Test]
public void RandomNormalTestTwoDouble()
{
RandomNormal rn = new RandomNormal(2018);
Assert.AreEqual(-0.46666, rn.NextDouble(), 0.0001);
Assert.AreEqual(-0.37989, rn.NextDouble(), 0.0001);
}
[Test]
public void RandomNormalTestWithMean()
{
RandomNormal rn = new RandomNormal(2018, 5.0f);
Assert.AreEqual(4.53333, rn.NextDouble(), 0.0001);
Assert.AreEqual(4.6201, rn.NextDouble(), 0.0001);
}
[Test]
public void RandomNormalTestWithStddev()
{
RandomNormal rn = new RandomNormal(2018, 1.0f, 4.2f);
Assert.AreEqual(-0.9599, rn.NextDouble(), 0.0001);
Assert.AreEqual(-0.5955, rn.NextDouble(), 0.0001);
}
[Test]
public void RandomNormalTestWithMeanStddev()
{
RandomNormal rn = new RandomNormal(2018, -3.2f, 2.2f);
Assert.AreEqual(-4.2266, rn.NextDouble(), 0.0001);
Assert.AreEqual(-4.0357, rn.NextDouble(), 0.0001);
}
[Test]
public void RandomNormalTestTensorInt()
{
RandomNormal rn = new RandomNormal(1982);
Tensor t = new Tensor
{
ValueType = Tensor.TensorType.Integer
};
Assert.Throws<NotImplementedException>(() => rn.FillTensor(t));
}
[Test]
public void RandomNormalTestDataNull()
{
RandomNormal rn = new RandomNormal(1982);
Tensor t = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint
};
Assert.Throws<ArgumentNullException>(() => rn.FillTensor(t));
}
[Test]
public void RandomNormalTestTensor()
{
RandomNormal rn = new RandomNormal(1982);
Tensor t = new Tensor
{
ValueType = Tensor.TensorType.FloatingPoint,
Data = Array.CreateInstance(typeof(float), new long[3] {3, 4, 2})
};
rn.FillTensor(t);
float[] reference = new float[]
{
-0.2139822f,
0.5051259f,
-0.5640336f,
-0.3357787f,
-0.2055894f,
-0.09432302f,
-0.01419199f,
0.53621f,
-0.5507085f,
-0.2651141f,
0.09315512f,
-0.04918706f,
-0.179625f,
0.2280539f,
0.1883962f,
0.4047216f,
0.1704049f,
0.5050544f,
-0.3365685f,
0.3542781f,
0.5951571f,
0.03460682f,
-0.5537263f,
-0.4378373f,
};
int i = 0;
foreach (float f in t.Data)
{
Assert.AreEqual(f, reference[i], 0.0001);
++i;
}
}
}
}

7
UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/3DBallHardLearning.bytes.meta


fileFormatVersion: 2
guid: 8a2da2218425f46e9921caefda4b7813
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/3DBall/TFModels/3DBallLearning.bytes.meta


fileFormatVersion: 2
guid: 9f58800fa9d54477aa01ee258842f6b3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/BananaCollectors/TFModels/BananaLearning.bytes.meta


fileFormatVersion: 2
guid: 69bd818d72b944849916d2fda9fe471b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Basic/TFModels/BasicLearning.bytes.meta


fileFormatVersion: 2
guid: 503ce1e8257904bd0b5be8f7fb4b5d28
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Bouncer/TFModels/BouncerLearning.bytes.meta


fileFormatVersion: 2
guid: 760d2b8347b4b46e3a44d9b989e1304e
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Crawler/TFModels/CrawlerDynamicLearning.bytes.meta


fileFormatVersion: 2
guid: 9482a8782450a4d87b20942c4523176b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Crawler/TFModels/CrawlerStaticLearning.bytes.meta


fileFormatVersion: 2
guid: e256bd37f98f246e5be72618766d0a93
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/GridWorld/TFModels/GridWorldLearning.bytes.meta


fileFormatVersion: 2
guid: 0fd168a0ea1d04ef9a68c80cf452ce3d
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Hallway/TFModels/HallwayLearning.bytes.meta


fileFormatVersion: 2
guid: 84588668e6ea948d3ab55bb813cc769b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/PushBlock/TFModels/PushBlockLearning.bytes.meta


fileFormatVersion: 2
guid: e22850d2072904a0ab06069cda2599e5
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Pyramids/TFModels/PyramidsLearning.bytes.meta


fileFormatVersion: 2
guid: 7d1c7f27447234c3a81169de00dcaa8a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Reacher/TFModels/ReacherLearning.bytes.meta


fileFormatVersion: 2
guid: 5fb4a3624e9ca4e1c81b51b5117cb31e
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Soccer/TFModels/GoalieLearning.bytes.meta


fileFormatVersion: 2
guid: 890ab8f03425c4a80a52ba674ddec3f3
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Soccer/TFModels/StrikerLearning.bytes.meta


fileFormatVersion: 2
guid: 23410257d39d44616bfefdff59c7fbc9
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Tennis/TFModels/TennisLearning.bytes.meta


fileFormatVersion: 2
guid: 6d4281b70d41f48cb83d663b84f78c9a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/Walker/TFModels/WalkerLearning.bytes.meta


fileFormatVersion: 2
guid: 48ab33cf9fbee4883948187618027835
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/WallJump/TFModels/BigWallJumpLearning.bytes.meta


fileFormatVersion: 2
guid: c118879bb5db84f269e4da23ba8c4f61
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

7
UnitySDK/Assets/ML-Agents/Examples/WallJump/TFModels/SmallWallJumpLearning.bytes.meta


fileFormatVersion: 2
guid: 92cd96b2c34334db692e93af25b64d2a
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

213
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TFSharpInferenceEngine.cs


#if ENABLE_TENSORFLOW
using System.Collections.Generic;
using TensorFlow;
using System.Linq;
using System;
using UnityEngine.Profiling;
using System.Runtime.InteropServices;
using UnityEngine;
namespace MLAgents.InferenceBrain
{
/// <summary>
/// TFSharpInferenceEngine - Inference engine utilizing the TensorFlow Sharp package to run inference
/// on frozen TensorFlow models
/// </summary>
public class TFSharpInferenceEngine
{
private TFGraph m_graph;
private TFSession m_session;
public void PrepareModel(byte[] model)
{
Profiler.BeginSample("TFSharpInferenceComponent.PrepareModel");
#if UNITY_ANDROID && !UNITY_EDITOR
// This needs to ba called only once and will raise an exception if called multiple times
try{
TensorFlowSharp.Android.NativeBinding.Init();
}
catch{
}
#endif
m_graph = new TFGraph();
m_graph.Import(model);
m_session = new TFSession(m_graph);
Profiler.EndSample();
}
public int ExecuteGraph(IEnumerable<Tensor> inputs_it, IEnumerable<Tensor> outputs_it)
{
Profiler.BeginSample("TFSharpInferenceComponent.ExecuteGraph");
Tensor[] inputs = inputs_it.ToArray();
Tensor[] outputs = outputs_it.ToArray();
// TODO: Can/should we pre-allocate that?
TFSession.Runner runner = m_session.GetRunner();
inputs.ToList().ForEach((Tensor input) =>
{
if (input.Shape.Length == 0)
{
var data = input.Data.GetValue(0);
if (input.DataType == typeof(int))
{
runner.AddInput(m_graph[input.Name][0], (int)data);
}
else
{
runner.AddInput(m_graph[input.Name][0], (float)data);
}
}
else
{
runner.AddInput(m_graph[input.Name][0], input.Data);
}
});
// TODO: better way to pre-allocate this?
outputs.ToList().ForEach(s => runner.Fetch(s.Name));
TFStatus status = new TFStatus();
Profiler.BeginSample("TFSharpInferenceComponent.ExecuteGraph.RunnerRun");
var out_tensors = runner.Run(status);
Profiler.EndSample();
if (!status.Ok)
{
Debug.LogError(status.StatusMessage);
return -1;
}
Debug.Assert(outputs.Length == out_tensors.Length);
for (var i = 0; i < outputs.Length; ++i)
{
if (outputs[i].Shape.Length == 0)
{
// Handle scalars
outputs[i].Data = Array.CreateInstance(outputs[i].DataType, new long[1] {1});
outputs[i].Data.SetValue(out_tensors[i].GetValue(), 0);
}
else
{
outputs[i].Data = out_tensors[i].GetValue() as Array;
}
}
Profiler.EndSample();
// TODO: create error codes
return 0;
}
[DllImport("libtensorflow")]
private static extern unsafe void TF_OperationGetAttrType(IntPtr oper, string attr_name,
TFDataType* value, IntPtr status);
[DllImport("libtensorflow")]
private static extern unsafe void TF_OperationGetAttrShape(IntPtr oper, string attr_name, long[] value,
int num_dims, IntPtr status);
private Tensor GetOpMetadata(TFOperation op)
{
TFStatus status = new TFStatus();
// Query the shape
long[] shape = null;
var shape_attr = op.GetAttributeMetadata("shape", status);
if (!status.Ok || shape_attr.TotalSize <= 0)
{
Debug.LogWarning("Operation " + op.Name + " does not contain shape attribute or it" +
" doesn't contain valid shape data!");
}
else
{
if (shape_attr.IsList)
{
throw new NotImplementedException("Querying lists is not implemented yet!");
}
else
{
TFStatus s = new TFStatus();
long[] dims = new long[shape_attr.TotalSize];
TF_OperationGetAttrShape(op.Handle, "shape", dims, (int)shape_attr.TotalSize,
s.Handle);
if (!status.Ok)
{
throw new FormatException("Could not query model for op shape (" + op.Name + ")");
}
else
{
shape = new long[dims.Length];
for (int i = 0; i < shape_attr.TotalSize; ++i)
{
if (dims[i] == -1)
{
// we have to use batchsize 1
shape[i] = 1;
}
else
{
shape[i] = dims[i];
}
}
}
}
}
// Query the data type
TFDataType type_value = new TFDataType();
unsafe
{
TFStatus s = new TFStatus();
TF_OperationGetAttrType(op.Handle, "dtype", &type_value, s.Handle);
if (!s.Ok)
{
Debug.LogWarning("Operation " + op.Name +
": error retrieving dtype, assuming float!");
type_value = TFDataType.Float;
}
}
Tensor.TensorType placeholder_type = Tensor.TensorType.FloatingPoint;
switch (type_value)
{
case TFDataType.Float:
placeholder_type = Tensor.TensorType.FloatingPoint;
break;
case TFDataType.Int32:
placeholder_type = Tensor.TensorType.Integer;
break;
default:
Debug.LogWarning("Operation " + op.Name +
" is not a float/integer. Proceed at your own risk!");
break;
}
Tensor t = new Tensor
{
Data = null,
Name = op.Name,
Shape = shape,
ValueType = placeholder_type
};
return t;
}
public IEnumerable<Tensor> InputFeatures()
{
List<Tensor> inputs = new List<Tensor>();
foreach (var op in m_graph.GetEnumerator())
{
if (op.OpType == "Placeholder")
{
inputs.Add(GetOpMetadata(op));
}
}
return inputs;
}
}
}
#endif

12
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/TFSharpInferenceEngine.cs.meta


fileFormatVersion: 2
guid: 120cbe3fa702f4e428f57ae1d893a0a7
timeCreated: 1535148728
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

40
UnitySDK/Assets/ML-Agents/Scripts/InferenceBrain/Tensor.cs


using System;
using System.Collections.Generic;
namespace MLAgents.InferenceBrain
{
/// <summary>
/// Tensor - A class to encapsulate a Tensor used for inference.
///
/// This class contains the Array that holds the data array, the shapes, type and the placeholder in the
/// execution graph. All the fields are editable in the inspector, allowing the user to specify everything
/// but the data in a graphical way.
/// </summary>
[System.Serializable]
public class Tensor
{
public enum TensorType
{
Integer,
FloatingPoint
};
private static Dictionary<TensorType, Type> m_typeMap = new Dictionary<TensorType, Type>()
{
{ TensorType.FloatingPoint, typeof(float)},
{TensorType.Integer, typeof(int)}
};
public string Name;
public TensorType ValueType;
// Since Type is not serializable, we use the DisplayType for the Inspector
public Type DataType
{
get { return m_typeMap[ValueType]; }
}
public long[] Shape;
public Array Data;
}
}

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存