这种迁移学习并不能将两个模型合成一个,用起来很不方便
# -*- coding:utf-8 -*-
import input_data as inputimport tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_Variable(shape):
initial = tf.constant(0.1,shape=shape)
return initial
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
def padding_2d(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
def transfer():
mnist = input.read_data_sets("/home/myjob/Downloads/Mnist/", one_hot=True)model_path_pb = "/home/myjob/Downloads/Mnist/"
x = tf.placeholder("float32", [None, 1024], name='x')
y_ = tf.placeholder("float32", [None, 10], name='input_y')
with tf.Session() as sess:
with gfile.FastGFile(model_path_pb + 'model.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='') # 导入计算图
input_x = sess.graph.get_tensor_by_name('input_x:0')
h_fc = sess.graph.get_tensor_by_name('fc1:0')
w_fc1 = weight_variable([1024, 1024])
b_fc1 = bias_Variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(x, w_fc1) + b_fc1, name="fc2")
w_fc2 = weight_variable([1024, 10])
b_fc2 = bias_Variable([10])
y_conv2d = tf.nn.softmax(tf.matmul(h_fc1, w_fc2) + b_fc2, name="outt")
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv2d))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv2d, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float32"))
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(101):
batch = mnist.train.next_batch(64)
if i % 2 == 0:
result = sess.run(h_fc,feed_dict={input_x: batch[0]})
train_accuracy = accuracy.eval(feed_dict={
x: result, y_: batch[1]})
print "step %d, training accuracy %g" % (i, train_accuracy)
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph_def, ['outt'])
with tf.gfile.FastGFile(model_path_pb + 'model_transform1.pb', mode='wb') as f:
f.write(constant_graph.SerializeToString())
result = sess.run(h_fc, feed_dict={input_x: batch[0]})
train_step.run(feed_dict={x: result, y_: batch[1]})
v = sess.graph.get_tensor_by_name('Variable_1:0')
print "========================================"
print sess.run(v[0])