我想要一段代码,如果它不存在,则在一个范围内创建一个变量,如果它已经存在,则访问该变量.我需要它是相同的代码,因为它将被多次调用.
但是,Tensorflow需要我指定是否要创建或重用变量,如下所示:
with tf.variable_scope("foo"): #create the first time
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True): #reuse the second time
v = tf.get_variable("v", [1])
Run Code Online (Sandbox Code Playgroud)
我怎样才能弄清楚是否自动创建或重用它?即,我希望上面两个代码块相同并运行程序.
我所指的名字是:
tf.placeholder(tf.float32, name='NAME')
tf.get_variable("W", [n_in, n_out],initializer=w_init())
Run Code Online (Sandbox Code Playgroud)
我有几个占位符,我想从外部函数访问而不传递引用,假设存在给定名称的占位符存在如何获得对它们的引用?(这是在图形构建期间,而不是运行时)
我的第二个问题是,无论范围如何,我如何获得具有给定名称的所有变量?
示例:我的所有权重在许多范围内都具有名称"W",我想将它们全部放入列表中.我不想手动添加每一个.偏见也可以这样做,假设我想做直方图.
python machine-learning neural-network deep-learning tensorflow
我正在尝试在keras中实现完全梯度下降.这意味着对于每个纪元,我都在训练整个数据集.这就是批量大小被定义为训练集的长度大小的原因.
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD,Adam
from keras import regularizers
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import random
from numpy.random import seed
import random
def xrange(start_point,end_point,N,base):
temp = np.logspace(0.1, 1, N,base=base,endpoint=False)
temp=temp-temp.min()
temp=(0.0+temp)/(0.0+temp.max()) #this is between 0 and 1
return (end_point-start_point)*temp +start_point #this is the range
def train_model(x_train,y_train,x_test):
#seed(1)
model=Sequential()
num_units=100
act='relu'
model.add(Dense(num_units,input_shape=(1,),activation=act))
model.add(Dense(num_units,activation=act))
model.add(Dense(num_units,activation=act))
model.add(Dense(num_units,activation=act))
model.add(Dense(1,activation='tanh')) #output layer 1 unit ; activation='tanh'
model.compile(Adam(),'mean_squared_error',metrics=['mse'])
history=model.fit(x_train,y_train,batch_size=len(x_train),epochs=500,verbose=0,validation_split = 0.2 ) #train …Run Code Online (Sandbox Code Playgroud) python machine-learning gradient-descent deep-learning keras
我正在尝试按照本指南提供我的再培训初始模型(您可能还会看到本指南,它解释了如何重新训练开始).我已经修改了retrain.py来导出我的模型,如下所示:
... # Same as in the original script:
# Set up the pre-trained graph.
maybe_download_and_extract()
graph, bottleneck_tensor, jpeg_data_tensor, resized_image_tensor = (create_inception_graph())
... # Same as in the original script:
# Add the new layer that we'll be training.
(train_step, cross_entropy, bottleneck_input, ground_truth_input, final_tensor) = add_final_training_ops(len(image_lists.keys()),
FLAGS.final_tensor_name,
bottleneck_tensor)
... # Added at the end of the original script:
# Export model
with graph.as_default():
export_path = sys.argv[-1]
print('Exporting trained model to', export_path)
saver = tf.train.Saver(sharded=True) …Run Code Online (Sandbox Code Playgroud) 如果我有一个具有 shape 的层[batch_size, height, width, depth]和另一个shape张量的输出,[depth]我如何将第一个张量乘以第二个,使得沿depth方向的每个切片都乘以第二个张量中的相应值。也就是说,如果第二张量是[4, 5, 6],那么乘法是:
tensor1[:, :, :, 0] * 4
tensor1[:, :, :, 1] * 5
tensor1[:, :, :, 2] * 6
Run Code Online (Sandbox Code Playgroud)
另外,有没有我不知道要搜索的这种乘法的名称?谢谢!
我们尝试过使用tf.nn.embedding_lookup它并且有效.但它需要密集的输入数据,现在我们需要tf.nn.embedding_lookup_sparse稀疏输入.
我写了以下代码,但得到了一些错误.
import tensorflow as tf
import numpy as np
example1 = tf.SparseTensor(indices=[[4], [7]], values=[1, 1], shape=[10])
example2 = tf.SparseTensor(indices=[[3], [6], [9]], values=[1, 1, 1], shape=[10])
vocabulary_size = 10
embedding_size = 1
var = np.array([0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0])
#embeddings = tf.Variable(tf.ones([vocabulary_size, embedding_size]))
embeddings = tf.Variable(var)
embed = tf.nn.embedding_lookup_sparse(embeddings, example2, None)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
print(sess.run(embed))
Run Code Online (Sandbox Code Playgroud)
错误日志如下所示.
现在我不知道如何正确修复和使用此方法.任何评论都可以表示赞赏.
潜入后safe_embedding_lookup_sparse的单元测试,我更困惑,为什么我如果给稀疏的权重,尤其是为什么我们得到的东西像得到这个结果embedding_weights[0][3],其中3在代码中没有出现以上.
我训练了一个神经网络,其中第一层在 Keras 中具有固定的权重(不可训练)。
这些层执行的计算在训练期间非常密集。为每个输入缓存层激活并在下一个时期传递相同的输入数据时重用它们以节省计算时间是有意义的。
是否有可能在 Keras 中实现这种行为?
我正在尝试将图像序列分为 2 类。每个序列有 5 帧。我已用作ConvLSTM2D第一层,但出现上述错误。该input_shape参数是input_shape = (timesteps, rows, columns, channels)。
我生成的数据是这种格式:
self.data = np.random.random((self.number_of_samples,
self.timesteps,
self.rows,
self.columns,
self.channels))
Run Code Online (Sandbox Code Playgroud)
第一层实现如下:
model = Sequential()
# time distributed is used - working frame by frame
model.add(ConvLSTM2D(filters=10,
input_shape=input_shape,
kernel_size=(3, 3),
activation='relu',
data_format="channels_last"))
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我解决这个问题吗?
编辑:这是我的玩弄代码:
import numpy as np
from keras.layers import Dense, Dropout, LSTM
from keras.layers import Conv2D, Flatten, ConvLSTM2D
from keras.models import Sequential
from keras.layers.wrappers import TimeDistributed
import time
class Classifier():
"""Classifier model to classify image sequences""" …Run Code Online (Sandbox Code Playgroud) 我有个问题。我建立了一个ConvNet。在最终输出之前隐藏的那个隐藏层的输出形状是(None,64,32,32)。我想要的是取这64个通道的元素明智的平均值。我已经试过了:
main_inputs=[]
outputs=[]
def convnet(channels,rows,columns):
input=Input(shape=(channels,rows,columns))
main_inputs.append(input)
conv1=Convolution2D(kernel_size=(3,3) ,filters=64, padding="same")(input)
activation1= Activation('relu')(conv1)
conv2=Convolution2D(kernel_size=(3,3), filters=64, padding="same")(activation1)
activation2 = Activation('relu')(conv2)
conv3=Convolution2D(kernel_size=(3,3), filters=64, padding="same")(activation2)
activation3 = Activation('relu')(conv3)
conv4=Convolution2D(kernel_size=(3,3), filters=channels, padding="same")(activation3)
out=keras.layers.Average()(conv4)
activation4 = Activation('linear')(out)
outputs.append(activation4)
print(np.shape(outputs))
model = Model(inputs=main_inputs, outputs=outputs)
return model
Run Code Online (Sandbox Code Playgroud)
但是当我遇到错误时:
ValueError: A merge layer should be called on a list of inputs
Run Code Online (Sandbox Code Playgroud)
之后,我尝试使用后端文档,而不是keras.layer.average:
out=K.mean(conv4,axis=1)
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
'Tensor' object has no attribute '_keras_history'
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?