在TensorFlow中保存或导出权重和偏差以进行非Python复制 [英] Save or export weights and biases in TensorFlow for non-Python replication

查看:146
本文介绍了在TensorFlow中保存或导出权重和偏差以进行非Python复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个性能良好的神经网络,我想在非Python环境中复制我的模型.我的网络设置如下:

I've built a neural network that performs reasonably well, and I'd like to replicate my model in a non-Python environment. I set up my network as follows:

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 23])
y_ = tf.placeholder(tf.float32, shape=[None, 2])
W = tf.Variable(tf.zeros([23,2]))
b = tf.Variable(tf.zeros([2]))
sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x,W) + b)

如何获取我的权重和偏差可理解的.csv或.txt?

How can I obtain a decipherable .csv or .txt of my weights and biases?

以下是我的完整脚本:

import csv
import numpy
import tensorflow as tf

data = list(csv.reader(open("/Users/sjayaram/developer/TestApp/out/production/TestApp/data.csv")))
[[float(j) for j in i] for i in data]
numpy.random.shuffle(data)
results=data

#delete results from data
data = numpy.delete(data, [23, 24], 1)
#delete data from results
results = numpy.delete(results, range(23), 1)

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 23])
y_ = tf.placeholder(tf.float32, shape=[None, 2])
W = tf.Variable(tf.zeros([23,2]))
b = tf.Variable(tf.zeros([2]))
sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x,W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

#train the model, saving 80 entries for testing
#batch-size: 40
for i in range(0, 3680, 40):
  train_step.run(feed_dict={x: data[i:i+40], y_: results[i:i+40]})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval(feed_dict={x: data[3680:], y_: results[3680:]}))

推荐答案

您可以将变量作为NumPy数组获取,并使用

You can fetch the variables as NumPy arrays, and use numpy.savetxt() to write out the contents as text or CSV:

import numpy as np

W_val, b_val = sess.run([W, b])

np.savetxt("W.csv", W_val, delimiter=",")
np.savetxt("b.csv", b_val, delimiter=",")

请注意,在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆