Tensorflow Code2

参考资料,莫烦的tensorflow讲解传送门,以下是对他讲解的总结。
代码2

# View more python tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""

from __future__ import print_function
import tensorflow as tf
import numpy as np

# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3

### create tensorflow structure start ###
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))

y = Weights*x_data + biases

loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
### create tensorflow structure end ###

sess = tf.Session()

sess.run(init)

for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(Weights), sess.run(biases))

tensorflow的代码需要定义图结构
再init,采用方法如下

init = tf.global_variables_initializer()

之后建立一个Session,再对于Session.run(init),再Session.run(train)才算是真正开始运行程序了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Here is an example of using TensorFlow with NDK in Android: 1. First, you need to download the TensorFlow library for Android from the official website. Then, extract the archive and copy the "libtensorflow_inference.so" file to your project's jniLibs folder. 2. Create a new C++ file in your project's jni folder, for example "tensorflow_jni.cpp". This file will contain the code that interacts with the TensorFlow API. 3. Include the TensorFlow header files in your C++ file: ```c++ #include <jni.h> #include <string> #include "tensorflow/core/public/session.h" #include "tensorflow/core/platform/env.h" ``` 4. Define a function that loads the TensorFlow model: ```c++ JNIEXPORT jlong JNICALL Java_com_example_tensorflow_TensorFlowModel_loadModel(JNIEnv *env, jobject thiz, jstring model_path) { const char *path = env->GetStringUTFChars(model_path, 0); tensorflow::Session *session; tensorflow::SessionOptions options; tensorflow::Status status = tensorflow::NewSession(options, &session); if (!status.ok()) { // error handling } tensorflow::GraphDef graph_def; status = tensorflow::ReadBinaryProto(tensorflow::Env::Default(), path, &graph_def); if (!status.ok()) { // error handling } status = session->Create(graph_def); if (!status.ok()) { // error handling } env->ReleaseStringUTFChars(model_path, path); return reinterpret_cast<jlong>(session); } ``` This function takes the path to the TensorFlow model file as input, loads it into a session and returns a pointer to the session object. 5. Define a function that runs the TensorFlow model: ```c++ JNIEXPORT jfloatArray JNICALL Java_com_example_tensorflow_TensorFlowModel_runModel(JNIEnv *env, jobject thiz, jlong session_ptr, jfloatArray input_data) { tensorflow::Session *session = reinterpret_cast<tensorflow::Session *>(session_ptr); jfloat *input = env->GetFloatArrayElements(input_data, NULL); const int input_size = env->GetArrayLength(input_data); tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1, input_size})); float *input_tensor_data = input_tensor.flat<float>().data(); memcpy(input_tensor_data, input, input_size * sizeof(float)); std::vector<tensorflow::Tensor> output_tensors; tensorflow::Status status = session->Run({{"input", input_tensor}}, {"output"}, {}, &output_tensors); if (!status.ok()) { // error handling } const int output_size = output_tensors[0].shape().dim_size(1); jfloatArray output_data = env->NewFloatArray(output_size); env->SetFloatArrayRegion(output_data, 0, output_size, output_tensors[0].flat<float>().data()); env->ReleaseFloatArrayElements(input_data, input, JNI_ABORT); return output_data; } ``` This function takes the session pointer and the input data as input, runs the session with the input data and returns the output data as a float array. 6. Finally, define the JNI interface functions in your "Android.mk" file: ```makefile LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := tensorflow_jni LOCAL_SRC_FILES := tensorflow_jni.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include LOCAL_LDLIBS := -llog -ljnigraphics -landroid LOCAL_LDFLAGS += -L$(LOCAL_PATH)/../libs/$(TARGET_ARCH_ABI) -ltensorflow_inference include $(BUILD_SHARED_LIBRARY) ``` That's it! You can now call the "loadModel" and "runModel" functions from your Java code to use TensorFlow in your Android app.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值