我有一个数据集,以前分为3组:训练,验证和测试.必须使用这些集合以便比较不同算法的性能.
我现在想使用验证集优化我的SVM的参数.但是,我无法找到如何明确输入验证集sklearn.grid_search.GridSearchCV().下面是我之前用于在训练集上进行K折叠交叉验证的一些代码.但是,对于这个问题,我需要使用给定的验证集.我怎样才能做到这一点?
from sklearn import svm, cross_validation
from sklearn.grid_search import GridSearchCV
# (some code left out to simplify things)
skf = cross_validation.StratifiedKFold(y_train, n_folds=5, shuffle = True)
clf = GridSearchCV(svm.SVC(tol=0.005, cache_size=6000,
class_weight=penalty_weights),
param_grid=tuned_parameters,
n_jobs=2,
pre_dispatch="n_jobs",
cv=skf,
scoring=scorer)
clf.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud) 我创建了一个python脚本来连接到remserver.
datfile = []
for dk in range(len(files)):
dfnt=files[dk]
dpst=dfnt.find('.dat')
if dpst == 15:
dlist = dfnt[:]
datfile.append(dlist)
assert datfile == ['a.dat','b.dat']
# True
Run Code Online (Sandbox Code Playgroud)
如你所见,创建一个列表.现在我将此列表传递给
ftp.retrbinary('datfile')
Run Code Online (Sandbox Code Playgroud)
但是这一行会返回一个错误:
typeerror: retrbinary() takes at least 3 arguments (2 given)
Run Code Online (Sandbox Code Playgroud)
不知道在找什么?
我已经安装了tensorflow 2.0.0-alpha0。尝试使用tf.logging.set_verbosity(tf.logging.ERROR)命令设置日志记录详细信息时,出现以下错误:
模块'tensorflow'没有属性'logging'。
2.0.0-alpha0版本中的这一点是否有变化?
我尝试构建自己的自定义层,tensorflow/keras强制该层对称,最终得到的结果如下:
import tensorflow as tf
from tensorflow.python.framework.ops import enable_eager_execution
enable_eager_execution()
class MyDenseLayer(tf.keras.layers.Layer):
def __init__(self, num_outputs):
super(MyDenseLayer, self).__init__()
self.num_outputs = num_outputs
def build(self, input_shape):
X = tf.random.uniform([int(input_shape[-1]),self.num_outputs],minval=0,maxval=1,dtype=tf.dtypes.float32,)
k = tf.Variable(X, name="kernel")
self.kernel = 0.5 * (k+tf.transpose(k))
def call(self, input):
return tf.matmul(input, self.kernel)
layer = MyDenseLayer(5)
print(layer(tf.ones([3, 5])))
print(layer.trainable_variables)
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切都很好。我不明白的是:为什么最后一行
print(layer.trainable_variables)
Run Code Online (Sandbox Code Playgroud)
给我一个空列表:
[]
Run Code Online (Sandbox Code Playgroud)
我认为这layer.trainable_variables会告诉我我的矩阵是什么样子,这样我就可以检查它是否对称。
如上。我试过那些无济于事:
tf.random.shuffle( (a,b) )
tf.random.shuffle( zip(a,b) )
Run Code Online (Sandbox Code Playgroud)
我曾经连接它们并进行改组,然后取消连接/解包。但是现在我处于 (a) 是 4D 秩张量而 (b) 是 1D 的情况,因此,无法连接。
我还尝试将种子参数提供给 shuffle 方法,以便它重现相同的洗牌,我使用它两次 => 失败。还尝试用随机洗牌的数字范围自己进行洗牌,但 TF 在花式索引方面不如 numpy 灵活,而且东西 ==> 失败了。
我现在正在做的是,将所有内容转换回 numpy,然后使用 sklearn 中的 shuffle,然后通过重铸返回张量。这完全是愚蠢的方式。这应该发生在图表内。
我正在尝试使用下面的代码片段加载 keras 模型:
from tensorflow import keras
from PIL import Image, ImageOps
import numpy as np
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
# Load the model
model = keras.models.load_model('keras_model.h5')
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# …Run Code Online (Sandbox Code Playgroud) 我正在尝试找出如何匹配activation=sigmoid正确activation=softmax的model.compile()损失参数。特别是那些与binary_crossentropy.
我研究了相关主题并阅读了文档。我还建立了一个模型并让它与 一起工作,sigmoid但没有softmax。我无法让它与“ from_logits”参数正常工作。
具体来说,这里说:
参数:
from_logits:是否output预期为 Logits 张量。默认情况下,我们认为output编码了概率分布。
这对我来说,如果你使用sigmoid激活,你想要“ from_logits=True”。对于softmax激活,默认情况下您需要“ from_logits=False”。这里我假设sigmoid提供logits并softmax提供概率分布。
接下来是一些代码:
model = Sequential()
model.add(LSTM(units=128,
input_shape=(n_timesteps, n_features),
return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(units=64, return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(units=32))
model.add(Dropout(0.3))
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(1, activation='sigmoid'))
Run Code Online (Sandbox Code Playgroud)
请注意,最后一行正在使用sigmoid激活。然后:
model.compile(optimizer=optimizer,
loss='binary_crossentropy',
metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)
这工作正常,但它使用默认的“from_logits=False”,它期望概率分布。
如果我执行以下操作,则会失败:
model.compile(optimizer=optimizer,
loss='binary_crossentropy',
metrics=['accuracy'],
from_logits=True) # For 'sigmoid' in above …Run Code Online (Sandbox Code Playgroud) 我正在使用tf.keras,但出现以下错误:
ValueError:检查输入时出错:预期 conv2d_input 有 4 个维度,但得到了形状为 (24946, 50, 50) 的数组
有人可以帮我吗?
代码(IMAGE_SIZE是:50x50)
import tensorflow as tf
import numpy as np
import pickle
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
pickle_ind = open("x.pickle", "rb")
x = pickle.load(pickle_ind)
x = np.array(x, dtype=float)
# x = x/255.0
pickle_ind = open("y.pickle", "rb")
y = pickle.load(pickle_ind)
n_batch = len(x)
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(50, 50, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu')) …Run Code Online (Sandbox Code Playgroud) 我正在执行一些与图像字幕相关的任务,并且已经像这样加载了初始模型的权重
model = InceptionV3(weights='imagenet')
Run Code Online (Sandbox Code Playgroud)
但是我得到这样的错误:
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
Run Code Online (Sandbox Code Playgroud)
我该怎么办?请帮忙。这是上面代码的完整输出。
1。-------------------------------------------------- ------------------------- AttributeError Traceback(最近一次通话最近)在()1#加载初始v3模型----> 2模型= InceptionV3(include_top = True,weights ='imagenet')3#InceptionV3(weights ='imagenet')
~/anaconda3/lib/python3.6/site-packages/keras/applications/__init__.py
in wrapper(*args, **kwargs)
26 kwargs['models'] = models
27 kwargs['utils'] = utils
---> 28 return base_fun(*args, **kwargs)
29
30 return wrapper
~/anaconda3/lib/python3.6/site-packages/keras/applications/inception_v3.py
in InceptionV3(*args, **kwargs)
9 @keras_modules_injection
10 def InceptionV3(*args, **kwargs):
---> 11 return inception_v3.InceptionV3(*args, **kwargs)
12
13
~/anaconda3/lib/python3.6/site-packages/keras_applications/inception_v3.py
in InceptionV3(include_top, weights, input_tensor, input_shape,
pooling, classes, **kwargs)
155
156 if input_tensor is None:
--> 157 img_input = …Run Code Online (Sandbox Code Playgroud) 我仅在测试阶段遇到此错误,但在训练和验证阶段没有遇到任何问题。
IndexError: tensors used as indices must be long, byte or bool tensors
Run Code Online (Sandbox Code Playgroud)
我在给定代码片段的最后一行收到此错误。
代码片段如下所示,
IndexError: tensors used as indices must be long, byte or bool tensors
Run Code Online (Sandbox Code Playgroud)
“lab”是一个张量值,并以这种方式打印出范围,
tensor([6, 7, 8])
tensor([ 9, 10, 11])
tensor([21, 22, 23])
Run Code Online (Sandbox Code Playgroud)
(注*:根据 ElementsPerClass 的值,该实验张量的长度可以是长度“n”)
基本上,我想编写一个损失函数来计算比较批次的标签和输出的分数。为此,我需要修复批量大小。
我之前在 Tensorflow 中做过,我可以在占位符函数中设置批量大小。现在,我需要在提供给我的 Keras 代码中使用类似的机制。我不知道在这里怎么做。
conv1 = (Conv2D(32, (3,3), padding='same', kernel_regularizer=regularizers.l2(weight_decay), input_shape=x_train.shape[1:], activation='elu'))(input_img)
print(conv1.shape)
Run Code Online (Sandbox Code Playgroud)
打印语句的输出显然是[?, 32, 32, 3]. 我该怎么做,说[64, 32, 32, 3]?
python ×10
tensorflow ×7
keras ×6
keras-layer ×2
ascii ×1
binary ×1
ftp ×1
image ×1
keras-2 ×1
list ×1
python-3.x ×1
pytorch ×1
scikit-learn ×1
validation ×1