我刚刚完成了section1,并注意到没有关于如何将项目推送到数组的特定位置的方法。例如,如果我想要显示数组
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import matplotlib.pyplot as plt
import random
import numpy as np
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
nb_classes = 10
X = tf.placeholder(tf.float32,[None,28*28], name='x-input')
Y = tf.placeholder(tf.float32,[None,nb_classes], name='y-input')
with tf.name_scope('layer1') as scope:
W1 = tf.Variable(tf.random_normal([28*28,28*28]),name='weight1')
b1 = tf.Variable(tf.random_normal([28*28]),name='bias1')
layer1 = tf.nn.relu(tf.matmul(X,W1)+b1)
w1_hist = tf.summary.histogram('weight1', W1)
layer1_hist = tf.summary.histogram('layer1', layer1)
with tf.name_scope('layer2') as scope:
W2 = tf.Variable(tf.random_normal([28*28,28*28]),name='weight2')
b2 = tf.Variable(tf.random_normal([28*28]),name='bias2')
layer2 = tf.nn.relu(tf.matmul(layer1,W2)+b2)
# 1. From TF graph, decide which tensors you want to log
w2_hist = tf.summary.histogram('weight2', W2)
layer2_hist = tf.summary.histogram('layer2', layer2)
with tf.name_scope('layer3') as scope:
W3 = tf.Variable(tf.random_normal([28*28,nb_classes]),name='weight3')
b3 = tf.Variable(tf.random_normal([nb_classes]),name='bias3')
logits = tf.matmul(layer2,W3)+b3
#hypothesis = tf.div(tf.exp(logits),tf.exp(logit,dim)
hypothesis = tf.nn.softmax(logits)
w3_hist = tf.summary.histogram('weight3', W3)
hypothesis_hist = tf.summary.histogram('hypothesis', hypothesis)
with tf.name_scope('cost') as scope:
# the method of l2reg, when deep
l2reg = tf.reduce_sum(tf.square(W1)) + tf.nn.l2_loss(W2) + tf.nn.l2_loss(W3)
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis),reduction_indices=1)) + (0.01 * l2reg)
# cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis,labels=Y))+ (0.01 * l2reg) => this worked very well
cost_summ = tf.summary.scalar('cost',cost)
with tf.name_scope('train') as scope:
train = tf.train.AdamOptimizer(learning_rate=1e-2).minimize(cost)
predicted = tf.argmax(hypothesis,1)
correction = tf.cast(tf.equal(predicted,tf.argmax(Y,1)),dtype=tf.float32)
Accuracy = tf.reduce_mean(correction)
# parameters
training_epochs = 15
batch_size = 100
with tf.Session() as sess:
# 2. merge all summaries
summary = tf.summary.merge_all()
# 3. Create writer and add graph
writer = tf.summary.FileWriter('./logs/mnist_l2reg_1e-2',sess.graph)
#writer.add_graph(sess.graph)
# 4. Run summary merge and add_summary
sess.run(tf.global_variables_initializer())
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
s,cost_val,_ = sess.run([summary,cost,train],feed_dict={X:batch_xs,Y:batch_ys})
writer.add_summary(s, global_step=i)
avg_cost += cost_val / total_batch
print('{:5} cost: {:.2f}'.format(epoch+1,avg_cost))
print('Accuracy: ',Accuracy.eval(session=sess,feed_dict={X:mnist.test.images, Y:mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples - 1)
print(r, 'test_num: {}, train_num: {}'.format(mnist.test.num_examples,mnist.train.num_examples))
# numpy.array[something] mean the row of the array
# notice that if slice like numpy.array[s:s+1], shape will be printed [1,-1]
print(mnist.test.labels[r],np.shape(mnist.test.labels))
print('argmax test none axis when array vector{}'.format(tf.argmax(mnist.test.labels[r]).eval(session=sess)))
print('Label:',sess.run(tf.argmax(mnist.test.labels[r:r+1], 1)))
print('Prediction:', sess.run(tf.argmax(hypothesis, 1),feed_dict={X: mnist.test.images[r:r +1]}))
plt.imshow(mnist.test.images[r:r+1].reshape(28,28), cmap='Greys', interpolation='nearest')
plt.show()
我怎样才能将“Brooks Brothers”推入阵列套装的位置[2],并将其余部分向下移动?在javascript中是否有类似push的内置函数可以让我这样做?
我想我总能带着一些困难:
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]
答案 0 :(得分:2)
您可以使用Array.splice
将项目插入到特定位置的数组中。
const suits = ["hearts", "clubs", "Brooks Brothers", "diamonds", "spades"];
suits.splice(2, 0, 'newItem');
console.log(suits);
答案 1 :(得分:1)
在JavaScript中没有内置函数,但您只需使用splice
执行此操作var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];
suits.splice(2, 0, "Brooks Brothers");
这会将项目X插入数组套装的索引2 ["hearts", "clubs", "Brooks Brothers", "Brooks Brothers", "diamonds", "spades"]
<强>语法强>
<array-name>.splice(<position-to-insert-items>,0,<item-1>,<item-2>,..,<item-n>)
始终将第二个参数传递为0,因为我们不想删除 拼接时阵列中的任何项目。
答案 2 :(得分:1)
您应该使用 splice 功能
arr.splice(index, 0, item);
会在指定索引处将项目插入arr(首先删除0项,即它只是一个插入)。
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"]
suits.splice(2, 0, "somevalue");
console.log(suits);
答案 3 :(得分:1)
您可以使用内置的 Splice 功能
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。
1-插入单个值
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];
//1st param is insert index = 2 means insert at index 2
//2nd param is delete item count = 0 means delete 0 elements
//3rd param is new item that you want to insert
suits.splice(2, 0 , "Test");
console.log(suits);
2-将阵列插入您的套装阵列
var suits = ["hearts","clubs","Brooks Brothers", "diamonds","spades"];
var newSuitsToInsert = ["test1", "test2","hello"];
//1st param is insert index = 2 means insert at index 2
//2nd param is delete item count = 0 means delete 0 elements
//3rd param is new item that you want to insert
//... is the spread syntax which will expand elements as one
suits.splice(2, 0 , ...newSuitsToInsert);
console.log(suits);