在这篇文章中,我们将带领您了解如何在Keras中获得图层的权重?的全貌,包括keras加载权重的相关情况。同时,我们还将为您介绍有关ios–如何在可可中获得图像的作者、python–为什么即使我设置了
在这篇文章中,我们将带领您了解如何在Keras中获得图层的权重?的全貌,包括keras加载权重的相关情况。同时,我们还将为您介绍有关ios – 如何在可可中获得图像的作者、python – 为什么即使我设置了随机种子,我也无法在Keras中获得可重现的结果?、python – 在keras中拆分图层的输出、traefik如何在kubernetes中获得客户端真实IP的知识,以帮助您更好地理解这个主题。
本文目录一览:- 如何在Keras中获得图层的权重?(keras加载权重)
- ios – 如何在可可中获得图像的作者
- python – 为什么即使我设置了随机种子,我也无法在Keras中获得可重现的结果?
- python – 在keras中拆分图层的输出
- traefik如何在kubernetes中获得客户端真实IP
如何在Keras中获得图层的权重?(keras加载权重)
我正在使用Windows 10,Python 3.5和tensorflow 1.1.0。我有以下脚本:
import tensorflow as tfimport tensorflow.contrib.keras.api.keras.backend as Kfrom tensorflow.contrib.keras.api.keras.layers import Densetf.reset_default_graph()init = tf.global_variables_initializer()sess = tf.Session()K.set_session(sess) # Keras will use this sesssion to initialize all variablesinput_x = tf.placeholder(tf.float32, [None, 10], name=''input_x'') dense1 = Dense(10, activation=''relu'')(input_x)sess.run(init)dense1.get_weights()
我得到错误: AttributeError: ''Tensor'' object has no attribute ''weights''
答案1
小编典典如果您写:
dense1 = Dense(10, activation=''relu'')(input_x)
然后dense1
不是图层,而是图层的输出。该层是Dense(10, activation=''relu'')
所以看来您的意思是:
dense1 = Dense(10, activation=''relu'')y = dense1(input_x)
这是完整的代码段:
import tensorflow as tffrom tensorflow.contrib.keras import layersinput_x = tf.placeholder(tf.float32, [None, 10], name=''input_x'') dense1 = layers.Dense(10, activation=''relu'')y = dense1(input_x)weights = dense1.get_weights()
ios – 如何在可可中获得图像的作者
有一个代码.
CFDataRef dataRef = CGDataProvidercopyData(CGImageGetDataProvider(img.CGImage)); //(UIImage *img) CGImageSourceRef mySourceRef = CGImageSourceCreateWithData(dataRef,NULL); NSDictionary *MetaDic = (NSDictionary *) CGImageSourcecopyPropertiesAtIndex(mySourceRef,NULL); NSDictionary *tiffDic = (NSDictionary *)[MetaDic objectForKey:(Nsstring *)kCGImagePropertyTIFFDictionary]; Nsstring *AuthorName = [tiffDic objectForKey:(Nsstring *)kCGImagePropertyTIFFArtist];
我做了一些获取图片的变种.在这里我发现了:
获取信息的一种方式 – 我需要从网站上获取它,并在那里得到我的信息:
// NSURL *UrlPath - path of picture image.jpg from web site NSData *dataimg = [NSData dataWithContentsOfURL:UrlPath]; CGImageSourceRef mySource = CGImageSourceCreateWithData((CFDataRef)dataimg,NULL); NSDictionary *MetaDic = (NSDictionary *) CGImageSourcecopyPropertiesAtIndex(mySource,NULL); NSDictionary *tiffDic = [MetaDic objectForKey:(Nsstring *)kCGImagePropertyTIFFDictionary]; /// Log of tiffDic tiffDic = { Artist =( "mr. Smith" ); }
另一种方式 – 从NSBoudle mainBundle读取图片:
// NSURL *NSBundleUrl - - path of the same picture image.jpg from [[NSBundle mainBundle] CGImageSourceRef mySource = CGImageSourceCreateWithURL( (CFURLRef) NSBundleUrl,NULL); NSDictionary *MetaDic = (NSDictionary *) CGImageSourcecopyPropertiesAtIndex(mySource,NULL); NSDictionary *tiffDic = [MetaDic objectForKey:(Nsstring *)kCGImagePropertyTIFFDictionary]; /// Log of tiffDic tiffDic = { Artist = "mr. Smith"; }
当图片数据来自网站时,为什么它会为艺术家的名字提供大括号?
解决方法
UIImage -> CGImage -> CGDataProvider -> CGImageSource
这是清理元数据图像的第三步. CGDataProviders是一种“旧”机制,用于将数据以“limited functionality”的形式传入Quartz – 这意味着 – 除其他外 – 它们不支持元数据.
尝试这样的事情:
NSData* jpegData = UIImageJPEGRepresentation(image,1.0); CFDataRef dataRef = (__bridge CFDataRef)jpegData; CGImageSourceRef source = CGImageSourceCreateWithData(dataRef,NULL);
数据路径:
UIImage -> NS/CFData -> CGImageSource
这将保留元数据.
如果您使用UIImage作为起点,那么以这种方式获取authorName可能没什么好运. UIImage剥离了许多可能伴随原始图像源的元数据(TiffDict似乎被剥离到只有方向标记).您真的希望从它的源读取“未解释的”数据并在不读取图像数据的情况下提取元数据(这是使用CGImageSourceRef的好处之一).
我有a little test project up on github比较从各种来源提取图像元数据的方法 – 文件系统,网络URL,资产库,相机,也许你应该看看.
更新
正如彼得指出的那样(我的项目显示) – 您不应该使用UIImage,而是使用原始数据源.在你的情况下,它是一个文件系统源,如下所示:
Nsstring* path = @"/path/to/resource"; NSData *data = [NSData dataWithContentsOfFile:path]; CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data,NULL);
或者更好(正如彼得指出的那样!)你可以使用CGImageSourceCreateWithURL并完全跳过NSData步骤.
python – 为什么即使我设置了随机种子,我也无法在Keras中获得可重现的结果?
python Keras_test.py
所以这不是状态问题(我没有使用Jupyter或IPython:每次运行代码时都应该重置环境).
编辑:我在导入Keras之前通过移动所有种子的设置来更改我的代码.结果仍然不确定,但结果的方差比以前小得多.这非常离奇.
目前的模型非常小(就深度神经网络而言)并不是微不足道的,它不需要GPU运行,它可以在几分钟内在现代笔记本电脑上进行训练,因此重复我的实验是在任何人的能力范围内.我邀请你这样做:我对了解从系统到另一个系统的变化程度非常感兴趣.
import numpy as np # random seeds must be set before importing keras & tensorflow my_seed = 512 np.random.seed(my_seed) import random random.seed(my_seed) import tensorflow as tf tf.set_random_seed(my_seed) # Now we can import keras import keras.utils from keras.applications import MobileNet from keras.callbacks import ModelCheckpoint from keras.optimizers import Adam import os height = 224 width = 224 channels = 3 epochs = 10 num_classes = 10 # Generate dummy data batch_size = 32 n_train = 256 n_test = 64 x_train = np.random.random((n_train,height,width,channels)) y_train = keras.utils.to_categorical(np.random.randint(num_classes,size=(n_train,1)),num_classes=num_classes) x_test = np.random.random((n_test,channels)) y_test = keras.utils.to_categorical(np.random.randint(num_classes,size=(n_test,num_classes=num_classes) # Get input shape input_shape = x_train.shape[1:] # Instantiate model model = MobileNet(weights=None,input_shape=input_shape,classes=num_classes) model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) # Viewing Model Configuration model.summary() # Model file name filepath = 'model_epoch_{epoch:02d}_loss_{loss:0.2f}_val_{val_loss:.2f}.hdf5' # Define save_best_only checkpointer checkpointer = ModelCheckpoint(filepath=filepath,monitor='val_acc',verbose=1,save_best_only=True) # Let's fit! model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs,validation_data=(x_test,y_test),callbacks=[checkpointer])
和往常一样,这是我的Python,Keras& Tensorflow版本:
python -c 'import keras; import tensorflow; import sys; print(sys.version,'keras.__version__','tensorflow.__version__')' /anaconda2/lib/python2.7/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future,it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Using TensorFlow backend. ('2.7.15 |Anaconda,Inc.| (default,May 1 2018,18:37:05) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]','2.1.6','1.8.0')
以下是多次运行此代码所获得的一些结果:如您所见,代码使用描述性文件名保存10个时期中的最佳模型(最佳验证准确性),因此比较不同运行中的文件名可以判断结果的可变性.
model_epoch_01_loss_2.39_val_3.28.hdf5 model_epoch_01_loss_2.39_val_3.54.hdf5 model_epoch_01_loss_2.40_val_3.47.hdf5 model_epoch_01_loss_2.41_val_3.08.hdf5
解决方法
简而言之,为了确保您可以在一台计算机/笔记本电脑的cpu上使用python脚本获得可重现的结果,那么您将不得不执行以下操作:
>将PYTHONHASHSEED环境变量设置为固定值
>将python内置伪随机生成器设置为固定值
>将numpy伪随机生成器设置为固定值
>将tensorflow伪随机生成器设置为固定值
>配置新的全局张量流会话
在顶部的Keras链接之后,我使用的源代码如下:
# Seed value # Apparently you may use different seed values at each stage seed_value= 0 # 1. Set `PYTHONHASHSEED` environment variable at a fixed value import os os.environ['PYTHONHASHSEED']=str(seed_value) # 2. Set `python` built-in pseudo-random generator at a fixed value import random random.seed(seed_value) # 3. Set `numpy` pseudo-random generator at a fixed value import numpy as np np.random.seed(seed_value) # 4. Set `tensorflow` pseudo-random generator at a fixed value import tensorflow as tf tf.set_random_seed(seed_value) # 5. Configure a new global `tensorflow` session from keras import backend as K session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1) sess = tf.Session(graph=tf.get_default_graph(),config=session_conf) K.set_session(sess)
毋庸置疑,您不必在python脚本中使用的numpy,scikit-learn或tensorflow / keras函数中指定任何种子或random_state,因为上面的源代码我们全局设置了伪 – 固定值的随机发电机.
python – 在keras中拆分图层的输出
我基本上寻找的是与Merge层相反的东西.我知道keras中没有分割层,但是在keras中有一个简单的方法吗?
解决方法
import keras.backend as K import numpy as np val = np.random.random((4,2,3)) t = K.variable(value=val) t1 = t[0,:,:] t2 = t[1,:] t3 = t[2,:] t4 = t[3,:] print('t1:\n',K.eval(t1)) print('t2:\n',K.eval(t2)) print('t3:\n',K.eval(t3)) print('t4:\n',K.eval(t4)) print('t:\n',K.eval(t))
它给出了以下输出:
t1: [[ 0.18787734 0.1085723 0.01127671] [ 0.06032621 0.14528386 0.21176969]] t2: [[ 0.34292713 0.56848335 0.83797884] [ 0.11579451 0.21607392 0.80680907]] t3: [[ 0.1908586 0.48186591 0.23439431] [ 0.93413448 0.535191 0.16410089]] t4: [[ 0.54303145 0.78971165 0.9961108 ] [ 0.87826216 0.49061012 0.42450914]] t: [[[ 0.18787734 0.1085723 0.01127671] [ 0.06032621 0.14528386 0.21176969]] [[ 0.34292713 0.56848335 0.83797884] [ 0.11579451 0.21607392 0.80680907]] [[ 0.1908586 0.48186591 0.23439431] [ 0.93413448 0.535191 0.16410089]] [[ 0.54303145 0.78971165 0.9961108 ] [ 0.87826216 0.49061012 0.42450914]]]
注意,现在t1,t2,t3,t4具有形状(2,3).
print(t1.shape.eval()) # prints [2 3]
因此,如果要保持3d形状,则需要执行以下操作:
t1 = t[0,:].reshape((1,3)) t2 = t[1,3)) t3 = t[2,3)) t4 = t[3,3))
现在,您可以获得正确尺寸的吐出张量.
print(t1.shape.eval()) # prints [1 2 3]
希望它能帮助您解决问题.
traefik如何在kubernetes中获得客户端真实IP
如何解决traefik如何在kubernetes中获得客户端真实IP?
我已阅读traefik doc,并告诉我traefik从x-forward-for http标头中获取客户端真实ip,然后我使用wireshark捕获了流量并发现请求中没有x-forward-for标头
那么traefik 2.2.1如何获得客户端真实IP?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
今天关于如何在Keras中获得图层的权重?和keras加载权重的分享就到这里,希望大家有所收获,若想了解更多关于ios – 如何在可可中获得图像的作者、python – 为什么即使我设置了随机种子,我也无法在Keras中获得可重现的结果?、python – 在keras中拆分图层的输出、traefik如何在kubernetes中获得客户端真实IP等相关知识,可以在本站进行查询。
本文标签: