项目作者: getnamo

项目描述 :
Machine Learning plugin for the Unreal Engine, encapsulating calls to remote python servers running e.g. Tensorflow/Pytorch.
高级语言: C++
项目地址: git://github.com/getnamo/machine-learning-remote-ue4.git
创建时间: 2019-04-24T05:12:36Z
项目社区:https://github.com/getnamo/machine-learning-remote-ue4

开源协议:MIT License

下载


MachineLearningRemote Unreal Plugin

A Machine Learning (ML) plugin for the Unreal Engine, encapsulating calls to remote python servers running python ML libraries like Tensorflow or Pytorch. Depends on server complement repository: https://github.com/getnamo/ml-remote-server.

GitHub release
Github All Releases

Should have the same api as tensorflow-ue4, but with freedom to run a host server on platform of choice (e.g. remote win/linux/mac instances) and without a hard bind to the tensorflow library.

Unreal Machine Learning Plugin Variants

Want to run tensorflow or pytorch on a remote (or local) python server?

Want to use tensorflow python api with a python instance embedded in your unreal engine project?

Want native tensorflow inference? (WIP)

Quick Install & Setup

  1. Install and setup https://github.com/getnamo/ml-remote-server on your target backend (can be a local folder), or setup the one embedded in plugin.
  2. Download Latest Release
  3. Create new or choose project.
  4. Browse to your project folder (typically found at Documents/Unreal Project/{Your Project Root})
  5. Copy Plugins folder into your Project root.
  6. Plugin should be now ready to use. Remember to startup your server when using this plugin.

How to use

Blueprint API

Add a MachineLearningRemote component to an actor of choice

Change server endpoint and DefaultScript to fit your use case. DefaultScript is the file name of your ML script which is placed in your [server](https://github.com/getnamo/ml-remote-server)/scripts folder. See https://github.com/getnamo/MachineLearningRemote-Unreal#python-api for example scripts.

In your script the on_setup and if self.should_train_on_start is true on_begin_training gets called. When your script has trained or it is otherwise ready, you can send inputs to it using SendSIOJsonInput or other variants (string/raw).

Your inputs will be processed on your script side and any value you return from there will be sent back and returned in ResultData as USIOJsonValue in your latent callback.

Other input variants

See https://github.com/getnamo/MachineLearningRemote-Unreal/blob/master/Source/MachineLearningRemote/Public/MachineLearningRemoteComponent.h for all variants

Custom Function

Change the FunctionName parameter in the SendSIOJsonInput to call a different function name in your script. This name will be used verbatim.

Python API

These scripts should be placed in your [server](https://github.com/getnamo/ml-remote-server)/scripts folder. If a matching script is defined in your MachineLearningRemote->DefaultScript property it should load on connect.

Keep in mind that tensorflow is optional and used as an illustrative example of ML, you can use any other valid python library e.g. pytorch instead without issue.

See https://github.com/getnamo/ml-remote-server/tree/master/scripts for additional examples.
See https://github.com/getnamo/TensorFlow-Unreal#python-api for more detailed api examples.

empty_example

Bare bones API example.

  1. import tensorflow as tf
  2. from mlpluginapi import MLPluginAPI
  3. class ExampleAPI(MLPluginAPI):
  4. #optional api: setup your model for training
  5. def on_setup(self):
  6. pass
  7. #optional api: parse input object and return a result object, which will be converted to json for UE4
  8. def on_json_input(self, input):
  9. result = {}
  10. return result
  11. #optional api: start training your network
  12. def on_begin_training(self):
  13. pass
  14. #NOTE: this is a module function, not a class function. Change your CLASSNAME to reflect your class
  15. #required function to get our api
  16. def get_api():
  17. #return CLASSNAME.getInstance()
  18. return ExampleAPI.get_instance()

add_example

Super basic example showing how to add using the tensorflow library.

  1. import tensorflow as tf
  2. import unreal_engine as ue #for remote logging only, this is a proxy import to enable same functionality as local variants
  3. from mlpluginapi import MLPluginAPI
  4. class ExampleAPI(MLPluginAPI):
  5. #expected optional api: setup your model for training
  6. def on_setup(self):
  7. self.sess = tf.InteractiveSession()
  8. #self.graph = tf.get_default_graph()
  9. self.a = tf.placeholder(tf.float32)
  10. self.b = tf.placeholder(tf.float32)
  11. #operation
  12. self.c = self.a + self.b
  13. ue.log('setup complete')
  14. pass
  15. #expected optional api: parse input object and return a result object, which will be converted to json for UE4
  16. def on_json_input(self, json_input):
  17. ue.log(json_input)
  18. feed_dict = {self.a: json_input['a'], self.b: json_input['b']}
  19. raw_result = self.sess.run(self.c, feed_dict)
  20. ue.log('raw result: ' + str(raw_result))
  21. return {'c':raw_result.tolist()}
  22. #custom function to change the op
  23. def change_operation(self, type):
  24. if(type == '+'):
  25. self.c = self.a + self.b
  26. elif(type == '-'):
  27. self.c = self.a - self.b
  28. ue.log('operation changed to ' + type)
  29. #expected optional api: start training your network
  30. def on_begin_training(self):
  31. pass
  32. #NOTE: this is a module function, not a class function. Change your CLASSNAME to reflect your class
  33. #required function to get our api
  34. def get_api():
  35. #return CLASSNAME.get_instance()
  36. return ExampleAPI.get_instance()

mnist_simple

One of the most basic ML examples using tensorflow to train a softmax mnist recognizer.

  1. #Converted to ue4 use from: https://www.tensorflow.org/get_started/mnist/beginners
  2. #mnist_softmax.py: https://github.com/tensorflow/tensorflow/blob/r1.1/tensorflow/examples/tutorials/mnist/mnist_softmax.py
  3. # Import data
  4. from tensorflow.examples.tutorials.mnist import input_data
  5. import tensorflow as tf
  6. import unreal_engine as ue
  7. from mlpluginapi import MLPluginAPI
  8. import operator
  9. class MnistSimple(MLPluginAPI):
  10. #expected api: storedModel and session, json inputs
  11. def on_json_input(self, jsonInput):
  12. #expect an image struct in json format
  13. pixelarray = jsonInput['pixels']
  14. ue.log('image len: ' + str(len(pixelarray)))
  15. #embedd the input image pixels as 'x'
  16. feed_dict = {self.model['x']: [pixelarray]}
  17. result = self.sess.run(self.model['y'], feed_dict)
  18. #convert our raw result to a prediction
  19. index, value = max(enumerate(result[0]), key=operator.itemgetter(1))
  20. ue.log('max: ' + str(value) + 'at: ' + str(index))
  21. #set the prediction result in our json
  22. jsonInput['prediction'] = index
  23. return jsonInput
  24. #expected api: no params forwarded for training? TBC
  25. def on_begin_training(self):
  26. ue.log("starting mnist simple training")
  27. self.scripts_path = ue.get_content_dir() + "Scripts"
  28. self.data_dir = self.scripts_path + '/dataset/mnist'
  29. mnist = input_data.read_data_sets(self.data_dir)
  30. # Create the model
  31. x = tf.placeholder(tf.float32, [None, 784])
  32. W = tf.Variable(tf.zeros([784, 10]))
  33. b = tf.Variable(tf.zeros([10]))
  34. y = tf.matmul(x, W) + b
  35. # Define loss and optimizer
  36. y_ = tf.placeholder(tf.int64, [None])
  37. # The raw formulation of cross-entropy,
  38. #
  39. # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
  40. # reduction_indices=[1]))
  41. #
  42. # can be numerically unstable.
  43. #
  44. # So here we use tf.losses.sparse_softmax_cross_entropy on the raw
  45. # outputs of 'y', and then average across the batch.
  46. cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y)
  47. train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  48. #update session for this thread
  49. self.sess = tf.InteractiveSession()
  50. tf.global_variables_initializer().run()
  51. # Train
  52. for i in range(1000):
  53. batch_xs, batch_ys = mnist.train.next_batch(100)
  54. self.sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  55. if i % 100 == 0:
  56. ue.log(i)
  57. if(self.should_stop):
  58. ue.log('early break')
  59. break
  60. # Test trained model
  61. correct_prediction = tf.equal(tf.argmax(y, 1), y_)
  62. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  63. finalAccuracy = self.sess.run(accuracy, feed_dict={x: mnist.test.images,
  64. y_: mnist.test.labels})
  65. ue.log('final training accuracy: ' + str(finalAccuracy))
  66. #return trained model
  67. self.model = {'x':x, 'y':y, 'W':W,'b':b}
  68. #store optional summary information
  69. self.summary = {'x':str(x), 'y':str(y), 'W':str(W), 'b':str(b)}
  70. self.stored['summary'] = self.summary
  71. return self.stored
  72. #required function to get our api
  73. def get_api():
  74. #return CLASSNAME.get_instance()
  75. return MnistSimple.get_instance()

C++ API

Available since 0.3.1.

Same as blueprint API except for one additional callback variant. Use the lambda overloaded functions e.g. assuming you have a component defined as

  1. UMachineLearningRemoteComponent* MLComponent; //NB: this needs to be allocated with NewObject or CreateDefaultSubobject

SendRawInput

  1. //Let's say you want to send some raw data
  2. TArray<float> InputData;
  3. //... fill
  4. MLComponent->SendRawInput(InputData, [this](TArray<float>& ResultData)
  5. {
  6. //Now we got our results back, do something with them here
  7. }, FunctionName);

SendStringInput

Keep in mind that if you’re using USIOJConvert utilities you’ll need to add SIOJson, and Json as dependency modules in your project build.cs.

  1. PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Json", "SIOJson" });

Sending just a String

  1. FString InputString = TEXT("Some Data");
  2. MLComponent->SendStringInput(InputString, [this](const FString& ResultData)
  3. {
  4. //e.g. just print the result
  5. UE_LOG(LogTemp, Log, TEXT("Got some results: %s"), *ResultData);
  6. }, FunctionName);

A custom JsonObject

  1. //Make an object {"myKey":"myValue"}
  2. TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
  3. JsonObject->SetStringField(TEXT("myKey"), TEXT("myValue"));
  4. FString InputString = USIOJConvert::ToJsonString(JsonObject);
  5. MLComponent->SendStringInput(InputString, [this](const FString& ResultData)
  6. {
  7. //assuming you got a json string response we could query it, e.g. assume {"someNumber":5}
  8. TSharedPtr<FJsonObject> JsonObject = USIOJConvert::ToJsonObject(ResultData);
  9. double MyNumber = JsonObject->GetNumberField("someNumber");
  10. //do something with your number result
  11. }, FunctionName);

Structs via Json

  1. //Let's say you want to send some struct data in json format
  2. USTRUCT()
  3. struct FTestCppStruct
  4. {
  5. GENERATED_BODY()
  6. UPROPERTY()
  7. int32 Index;
  8. UPROPERTY()
  9. float SomeNumber;
  10. UPROPERTY()
  11. FString Name;
  12. };
  13. //...
  14. FTestCppStruct TestStruct;
  15. TestStruct.Name = TEXT("George");
  16. TestStruct.Index = 5;
  17. TestStruct.SomeNumber = 5.123f;
  18. FString StructJsonString = USIOJConvert::ToJsonString(USIOJConvert::ToJsonObject(FTestCppStruct::StaticStruct(), &TestStruct));
  19. //In this example we're using the same struct type for the result, but you could use a different one or custom Json
  20. FTestCppStruct ResultStruct;
  21. MLComponent->SendStringInput(StructJsonString, [this, &ResultStruct](const FString& ResultData)
  22. {
  23. //do something with the result, let's say we we have another struct of same type and we'd like to fill it with the results
  24. USIOJConvert::JsonObjectToUStruct(USIOJConvert::ToJsonObject(ResultData), FTestCppStruct::StaticStruct(), &ResultStruct);
  25. }, FunctionName);