我是一个广泛使用MATLAB的Python新手.我正在转换一些log2在MATLAB 中使用的代码,我使用了NumPy log2函数,得到的结果与我预期的这么小的数字不同.我很惊讶,因为数字的精确度应该相同(即MATLAB double vs NumPy float64).
a = log2(64);
--> a=6
Run Code Online (Sandbox Code Playgroud)
import math
a = math.log2(64)
--> a = 6.0
Run Code Online (Sandbox Code Playgroud)
import numpy as np
a = np.log2(64)
--> a = 5.9999999999999991
Run Code Online (Sandbox Code Playgroud)
import numpy as np
a = np.log(64) / np.log(2)
--> a = 6.0
Run Code Online (Sandbox Code Playgroud)
因此,本机NumPy log2函数会产生导致代码失败的结果,因为它检查数字是2的幂.预期结果正好是6,本机Python log2函数和修改后的NumPy代码都使用了对数的属性.我是否在使用NumPy log2功能做错了什么?我现在改变了代码以使用原生Python log2,但我只是想知道答案.
我正在使用快速开发一个快速node.js应用程序,我是NODE的新手.对于页面我只是使用普通的HTML.
基本上我有一个表格如下:
<form id="tableForm" action="getJson">
<select class="selectpicker" data-style="btn-info" name="selectpicker">
<optgroup label="Select Table">
<option name="" value="0">Select table</option>
<option name="table1" value="1">Table 1</option>
<option name="table2" value="2">Table 2</option>
<option name="table3" value="3">Table 3</option>
</optgroup>
</select>
</form>
Run Code Online (Sandbox Code Playgroud)
基本上,我需要在完成后选择值,我需要通过app.get()调用,但我的问题是如何获取值并调用API?
var express = require('express'),
app = express();
app.use(express.bodyParser());
// as only one page can use res.sendfile to render the page which will
// contain the dropdowns ...
app.get('/', function(req, res){
res.sendfile('views/index.html');
});
app.get('/getJson', function (req, res) {
console.log(req.body.);
});
app.listen(process.env.PORT);
Run Code Online (Sandbox Code Playgroud)
所以我需要调用getJson()传入的值.
干杯!
我正在尝试使用tensorflow中的dropout功能:
sess=tf.InteractiveSession()
initial = tf.truncated_normal([1,4], stddev=0.1)
x = tf.Variable(initial)
keep_prob = tf.placeholder("float")
dx = tf.nn.dropout(x, keep_prob)
sess.run(tf.initialize_all_variables())
sess.run(dx, feed_dict={keep_prob: 0.5})
sess.close()
Run Code Online (Sandbox Code Playgroud)
此示例与本教程中的示例非常相似; 但是,我最终得到以下错误:
RuntimeError: min: Conversion function <function constant at 0x7efcc6e1ec80> for type <type 'object'> returned incompatible dtype: requested = float32_ref, actual = float32
Run Code Online (Sandbox Code Playgroud)
我很难理解dtype float32_ref,这似乎是问题的背景.我也尝试过指定dtype=tf.float32,但这并没有解决任何问题.
我也试过这个例子,它适用于float32:
sess=tf.Session()
x=tf.Variable(np.array([1.0,2.0,3.0,4.0]))
sess.run(x.initializer)
x=tf.cast(x,tf.float32)
prob=tf.Variable(np.array([0.5]))
sess.run(prob.initializer)
prob=tf.cast(prob,tf.float32)
dx=tf.nn.dropout(x,prob)
sess.run(dx)
sess.close()
Run Code Online (Sandbox Code Playgroud)
但是,如果我施放float64而不是float32我得到相同的错误:
RuntimeError: min: Conversion function <function constant at 0x7efcc6e1ec80> for …Run Code Online (Sandbox Code Playgroud) 我正在通过TensorFlow的CIFAR-10示例开始CNN入门指南
现在在cifar10_train.py的火车功能中我们得到的图像为
images,labels = cifar10.distorted_inputs()
Run Code Online (Sandbox Code Playgroud)
在distorted_inputs()函数中,我们在队列中生成文件名,然后将单个记录读取为
# Create a queue that produces the filenames to read.
filename_queue = tf.train.string_input_producer(filenames)
# Read examples from files in the filename queue.
read_input = cifar10_input.read_cifar10(filename_queue)
reshaped_image = tf.cast(read_input.uint8image, tf.float32)
Run Code Online (Sandbox Code Playgroud)
当我添加调试代码时,该read_input变量只包含一条带有图像的记录及其高度,宽度和标签名称.
然后,该示例将一些失真应用于读取的图像/记录,然后将其传递给_generate_image_and_label_batch()函数.
该函数然后返回形状的4D张量[batch_size, 32, 32, 3] ,其中batch_size = 128.
tf.train.shuffle_batch()返回批处理时,上述功能使用该功能.
我的问题是功能中额外的记录来自tf.train.shuffle_batch()哪里?我们没有传递任何文件名或读者对象.
有人可以说明我们如何从1条记录转到128条记录吗?我查看了文档,但不明白.
我正在尝试实现深度强化学习的异步方法,其中一个步骤需要在不同的步骤上累积渐变然后应用它.在tensorflow中实现这一目标的最佳方法是什么?我已经积累了渐变,我认为不是实现它的最快方法(从tensorflow到python和back的很多转移).欢迎任何建议.这是我的玩具NN的代码.它不会模拟或计算它只是运行我想要使用的操作的任何东西.
import tensorflow as tf
from model import *
graph = tf.Graph()
with graph.as_default():
state = tf.placeholder(tf.float32, shape=[None, 80,80,1])
with tf.variable_scope('layer1'):
W = weight_variable([8, 8, 1, 32])
variable_summaries(W, "layer1/W")
b = bias_variable([32])
variable_summaries(b, "layer1/b")
h = conv2d(state, W, 4) + b
activation = tf.nn.relu(h)
pool1 = max_pool_2x2(activation)
print(pool1.get_shape())
pool1 = tf.reshape(pool1, [-1, 3200])
with tf.variable_scope('readout'):
W = weight_variable([3200, 3])
b = bias_variable([3])
logits = tf.matmul(pool1, W) + b
variable_summaries(h, "y")
action_indexes = tf.placeholder(tf.int32, shape=[None], name="action_indexes")
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits, …Run Code Online (Sandbox Code Playgroud) 我想以批量方式从TensorFlow中的DNC实现中实现此公式.
使用批量密集张量,它非常简单.
# w [B, N], p [B, N], L [B, N, N], B=batch_size
dot_prod = tf.batch_matmul(tf.expand_dims(w, axis=2), tf.expand_dims(p, axis=1))
one_prod = 1 - tf.expand_dims(w, 1) - tf.expand_dims(w, 2)
L = one_prod * pre_L + dot_prod
Run Code Online (Sandbox Code Playgroud)
有没有办法用稀疏张量实现这个?w,p和L是稀疏的,但TensorFlow缺乏稀疏批处理matmul和稀疏索引.
我试图得到下面神经网络的训练过程的总结.
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".\MNIST",one_hot=True)
# Create the model
def train_and_test(hidden1,hidden2, learning_rate, epochs, batch_size):
with tf.name_scope("first_layer"):
input_data = tf.placeholder(tf.float32, [batch_size, 784], name = "input")
weights1 = tf.Variable(
tf.random_normal(shape =[784, hidden1],stddev=0.1),name = "weights")
bias = tf.Variable(tf.constant(0.0,shape =[hidden1]), name = "bias")
activation = tf.nn.relu(
tf.matmul(input_data, weights1) + bias, name = "relu_act")
tf.summary.histogram("first_activation", activation)
with tf.name_scope("second_layer"):
weights2 = tf.Variable(
tf.random_normal(shape =[hidden1, hidden2],stddev=0.1),
name = "weights")
bias2 = tf.Variable(tf.constant(0.0,shape =[hidden2]), name = "bias") …Run Code Online (Sandbox Code Playgroud)
我对张量流很困惑tf.layers.batch_normalization.
我的代码如下:
def my_net(x, num_classes, phase_train, scope):
x = tf.layers.conv2d(...)
x = tf.layers.batch_normalization(x, training=phase_train)
x = tf.nn.relu(x)
x = tf.layers.max_pooling2d(...)
# some other staffs
...
# return
return x
def train():
phase_train = tf.placeholder(tf.bool, name='phase_train')
image_node = tf.placeholder(tf.float32, shape=[batch_size, HEIGHT, WIDTH, 3])
images, labels = data_loader(train_set)
val_images, val_labels = data_loader(validation_set)
prediction_op = my_net(image_node, num_classes=2,phase_train=phase_train, scope='Branch1')
loss_op = loss(...)
# some other staffs
optimizer = tf.train.AdamOptimizer(base_learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(loss=total_loss, global_step=global_step)
sess = ...
coord …Run Code Online (Sandbox Code Playgroud) 在Keras中,作为TensorFlow的简化界面:教程描述了如何在TensorFlow张量上调用Keras模型.
from keras.models import Sequential
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=784))
model.add(Dense(10, activation='softmax'))
# this works!
x = tf.placeholder(tf.float32, shape=(None, 784))
y = model(x)
Run Code Online (Sandbox Code Playgroud)
他们还说:
注意:通过调用Keras模型,您将重用其体系结构和权重.当您在张量上调用模型时,您将在输入张量之上创建新的TF操作,并且这些操作正在重用模型中已存在的TF变量实例.
我将此解释为模型的权重与模型中的权重相同y.但是,对我来说,似乎重新初始化了生成的Tensorflow节点中的权重.一个最小的例子如下:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# Create model with weight initialized to 1
model = Sequential()
model.add(Dense(1, input_dim=1, kernel_initializer='ones',
bias_initializer='zeros'))
model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
# Save the weights
model.save_weights('file')
# Create another identical model except with weight initialized to 0
model2 = Sequential() …Run Code Online (Sandbox Code Playgroud) 手头的简单任务:运行N个时期的训练,在每个时期之后执行计算精确的验证准确性.时期大小可以等于完整训练集或某些预定义的迭代次数.在验证期间,每个验证集输入必须只进行一次评估.
将one_shot_iterators,初始化迭代器和/或句柄混合在一起的最佳方法是什么?
这是我认为它应该如何工作的脚手架:
def build_training_dataset():
pass
def build_validation_dataset():
pass
def construct_train_op(dataset):
pass
def magic(iterator):
pass
USE_CUSTOM_EPOCH_SIZE = True
CUSTOM_EPOCH_SIZE = 60
MAX_EPOCHS = 100
training_dataset = build_training_dataset()
validation_dataset = build_validation_dataset()
# Magic goes here to build a nice one-instance dataset
dataset = magic(training_dataset, validation_dataset)
train_op = construct_train_op(dataset)
# Run N epochs in which the training dataset is traversed, followed by the
# validation dataset.
with tf.Session() as sess:
for epoch in MAX_EPOCHS:
# train
if USE_CUSTOM_EPOCH_SIZE:
for _ in range(CUSTOM_EPOCH_SIZE): …Run Code Online (Sandbox Code Playgroud) tensorflow ×8
python ×2
dataset ×1
express ×1
keras ×1
matlab ×1
node.js ×1
numpy ×1
tensorboard ×1