# tf-lite-demo **Repository Path**: deng-yongsheng/tf-lite-demo ## Basic Information - **Project Name**: tf-lite-demo - **Description**: TensorflowLite Demo:拟合sin函数,并将模型移植到C语言下 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-10-26 - **Last Updated**: 2022-10-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # TensorflowLite Demo:拟合sin函数,并将模型移植到C语言下 ## keras训练模型拟合sin函数 ```python import keras from keras.layers import * from keras.models import Sequential import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split ``` ### 使用numpy生成sin函数的x和y映射 ```python x = np.linspace(0, 1, 10000, dtype='float32') y = (np.sin(x * 2 * np.pi) + 1) * 0.5 ``` ### 绘制`x`, `y`图像 ```python plt.figure(dpi=120) plt.plot(x, y) ``` ![png](md_files/1.keras%E6%A8%A1%E5%9E%8B%E6%9E%84%E5%BB%BA%E5%92%8C%E8%AE%AD%E7%BB%83_5_1.png) ### 将x,y矩阵转换,变成训练数据, ```python x_train = x.reshape((-1,1)) y_train = y.reshape((-1,1)) ``` ### 创建模型 ```python model = Sequential([ InputLayer((1,)), Dense(32,activation='relu'), Dense(64,activation='relu'), Dense(1,activation='sigmoid'), ]) model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) model.summary() ``` Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 32) 64 _________________________________________________________________ dense_1 (Dense) (None, 64) 2112 _________________________________________________________________ dense_2 (Dense) (None, 1) 65 ================================================================= Total params: 2,241 Trainable params: 2,241 Non-trainable params: 0 _________________________________________________________________ ### 模型训练 ```python model.fit(x_train, y_train, batch_size=10000, epochs=10000) ``` ### 模型测试 ```python predict_y = model.predict(x) ``` ### 拟合结果绘制图像 ```python plt.figure(dpi=72*2) plt.title('Neural network fitting sin function') plt.plot(x, y, color='b', label='sin') plt.plot(x, predict_y, color='r', label='fitted') plt.legend(loc=0) ``` ![png](md_files/1.keras%E6%A8%A1%E5%9E%8B%E6%9E%84%E5%BB%BA%E5%92%8C%E8%AE%AD%E7%BB%83_15_1.png) ​ ### 模型保存到文件 ```python model.save('sin.model.h5') ``` ## 将keras模型转换成tflite模型 ```python import keras import tensorflow as tf ``` ### 从文件中加载keras模型 ```python model = keras.models.load_model('sin.model.h5') model.summary() ``` Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense (Dense) (None, 32) 64 _________________________________________________________________ dense_1 (Dense) (None, 64) 2112 _________________________________________________________________ dense_2 (Dense) (None, 1) 65 ================================================================= Total params: 2,241 Trainable params: 2,241 Non-trainable params: 0 _________________________________________________________________ ### 从keras模型转换到tflite模型 ```python converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() ``` INFO:tensorflow:Assets written to: C:\Users\sheng\AppData\Local\Temp\tmpkxydx7qq\assets ### 将转换后的模型写入文件 ```python with open('sin.tf_lite.model','wb') as f: f.write(tflite_model) ``` ## tflite部署模型 ```python import tensorflow as tf import numpy as np import matplotlib.pyplot as plt ``` ### 从文件加载解释器 ```python interpreter = tf.lite.Interpreter('sin.tf_lite.model') interpreter.allocate_tensors() ``` ### 获取模型的输入输出信息 ```python interpreter.get_output_details() interpreter.get_input_details() ``` [{'name': 'input_1', 'index': 0, 'shape': array([1, 1]), 'shape_signature': array([-1, 1]), 'dtype': numpy.float32, 'quantization': (0.0, 0), 'quantization_parameters': {'scales': array([], dtype=float32), 'zero_points': array([], dtype=int32), 'quantized_dimension': 0}, 'sparsity_parameters': {}}] ### 生成测试数据 ```python x = np.linspace(0,1,num=1000,dtype='float32') ``` ### 获取输入和输出tensor的索引 ```python input_tensor_index = interpreter.get_input_details()[0]['index'] output_tensor_index = interpreter.get_output_details()[0]['index'] ``` ### 设置输入tensor ```python interpreter.set_tensor(input_tensor_index, x[0].reshape((-1,1))) ``` ### 调用解释器 ```python interpreter.invoke() ``` ### 获取输出tensor ```python interpreter.get_tensor(output_tensor_index) ``` array([[0.49774837]], dtype=float32) ## 批量预测 ```python y= [] for i in x: interpreter.set_tensor(input_tensor_index, i.reshape((1,1))) interpreter.invoke() y.append(interpreter.get_tensor(output_tensor_index)[0][0]) ``` ```python plt.plot(x,y) ``` ![png](md_files/3.tflite%E9%83%A8%E7%BD%B2%E6%A8%A1%E5%9E%8B_18_1.png)