我已经使用以下代码设置了张量流神经网络,并且它的工作非常好:
from master2 import create_feature_sets_and_labels
import tensorflow as tf
import numpy as np
from datetime import datetime as timer
start=timer.now()
train_x,train_y,test_x,test_y = create_feature_sets_and_labels('temp1c.txt','temp2c.txt')
print('Starting neural network')
n_nodes_hl1 = 3
n_classes = 2 #Set to label size
batch_size = 50
x = tf.placeholder('float', [None, len(train_x[0])])
y = tf.placeholder('float')
def neural_network_model(data):
hidden_1_layer = {'weights':tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])),
'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_classes])),
'biases':tf.Variable(tf.random_normal([n_classes])),}
l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)
output = tf.matmul(l1,output_layer['weights']) + output_layer['biases']
return output
def train_neural_network(x):
prediction = neural_network_model(x)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)
hm_epochs = 50
with tf.Session() as sess:
writer = tf.summary.FileWriter("output", sess.graph)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epochs):
epoch_loss = 0
i=0
while i < len(train_x):
start = i
end = i+batch_size
batch_x = np.array(train_x[start:end])
batch_y = np.array(train_y[start:end])
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
epoch_loss += c
i+=batch_size
print('Epoch', epoch+1, 'completed out of',hm_epochs,'loss:',epoch_loss)
#print(timer.now()-start)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))
writer.close()
save_path = saver.save(sess, "model.ckpt")
print("Model saved in path: %s" % save_path)
train_neural_network(x)
print(timer.now()-start)
print('Done.')
我遇到的问题是在恢复中,我看似无法让模型读回内存。单独文件中的代码是:
import tensorflow as tf
import pandas as pd
import datetime
#lexicon was length 2912 for x[0] above
x = tf.Variable('float', [None, 2912])
y = tf.Variable('float')
saver = tf.train.Saver()
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, "model.ckpt")
print("Model restored.")
有谁知道为什么我无法恢复体重和偏见?错误如下:
DataLossError: Invalid size in bundle entry: key Variable; stored size 11648; expected size 93184
[[Node: save/RestoreV2 = RestoreV2[dtypes=[DT_STRING], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2/tensor_names, save/RestoreV2/shape_and_slices)]]
答案 0 :(得分:0)
解决。这是一个dtype问题。我在原始文件中使用了占位符,并且在Variable类型未对齐时出现问题。