``````            贴一下代码：
``````
``````import numpy as np
import matplotlib.pyplot as plt
import h5py

#参数初始化，将所有w/b都封装在一个dict中
def initialize_parameters(layer_dims):
parameters = {}
L = len(layer_dims)

for i in range(1,L):
parameters['w'+ str(i)] = np.random.randn(layer_dims[i],layer_dims[i-1])*0.01
parameters['b'+ str(i)] = np.zeros((layer_dims[i],1))

assert(parameters['w'+ str(i)]).shape == (layer_dims[i],layer_dims[i-1])
assert(parameters['b'+ str(i)]).shape == (layer_dims[i],1)

return parameters

#定义激活函数
def relu(Z):
A=(Z+abs(Z))/2
assert(A.shape == Z.shape)
return A

def sigmoid(Z):
A=1.0/(1+np.exp(-Z))
assert(A.shape == Z.shape)
return A

#向前传播
def forward_propagation(X,parameters):
#caches存储了每一层计算得到的A，Z值
caches = {}

L=len(parameters)//2
A_prev=X

for i in range(1,L):
Z=np.dot(parameters['w'+str(i)],A_prev)+parameters['b'+str(i)]
A=relu(Z)
caches['Z'+str(i)]=Z
caches['A'+str(i)]=A
#这一层计算得到的A需要保留，下一层计算Z要用
A_prev=A

#输出层的激活函数时sigmoid
Z=np.dot(parameters['w'+str(L)],A_prev)+parameters['b'+str(L)]
A=sigmoid(Z)

caches['Z'+str(L)]=Z
caches['A'+str(L)]=A

#这里多存一个X是因为反向传播的时候要用到
caches['A0'] = X

return A,caches

#计算代价
def cpmpute_cost(A,Y):
m=Y.shape[1]
cost=-1/m*np.sum(np.multiply(np.log(A),Y)+np.multiply((1-Y),np.log(1-A)))
cost=np.squeeze(cost)
return cost

#relu函数的导数
def relu_back(Z,dA):
deri = Z

deri[Z < 0]=0
deri[Z >=0]=1

return deri

#反向传播
def back_propagation(Y,caches,parameters):
#所有的dw和db

L=len(caches)//2
m=Y.shape[1]

#AL其实就是一次迭代得到的预测值
AL=caches['A'+str(L)]

#因为sigmoid反向传和relu不同，所以单独处理
dZ=AL-Y
dW=np.dot(dZ,caches['A'+str(L-1)].T)/m
db=np.sum(dZ,axis=1,keepdims=True)/m

for i in reversed(range(1,L)):
dA=np.dot(parameters['w'+str(i+1)].T,dZ)
dZ=np.multiply(dA,relu_back(caches['Z'+str(i)],dA))
dW=1.0/m * np.dot(dZ,caches['A'+str(i-1)].T)
db=1.0/m * np.sum(dZ,axis=1,keepdims=True)

#更新参数
L = len(parameters)//2
for l in range(L):
parameters['w'+str(l+1)] = parameters['w'+str(l+1)] - alphs * grads['dw'+str(l+1)]
parameters['b'+str(l+1)] = parameters['b'+str(l+1)] - alphs * grads['db'+str(l+1)]
return parameters

#模型预测
def predict(X,parameters):

A2,caches=forward_propagation(X,parameters)

temp=A2.shape[1]
Y_pred=np.zeros([1,temp])

for i in range(temp):
if A2[:,i]>0.5:
Y_pred[:,i]=1
else:
Y_pred[:,i]=0

return Y_pred

#模型整合
def model(X,Y,layer_dims,iter_times,alphs,print_flag):
np.random.seed(1)
parameters=initialize_parameters(layer_dims)
for i in range(0,iter_times):

A,caches=forward_propagation(X,parameters)
cost=cpmpute_cost(A,Y)

if print_flag and i % 100 == 0:
print('iteration at ',i,' cost :',cost)

return parameters

n=train_data_finalX.shape[0]
layer_dims=[n,20,7,5,1]
parameters=model(train_data_finalX,train_data_finalY,layer_dims,2500,0.0075,True)

y_pred_train=predict(train_data_finalX,parameters)
print('train acc is ',np.mean(y_pred_train == train_data_finalY)*100,'%')

y_pred_test=predict(test_data_finalX,parameters)
print('test acc is ',np.mean(y_pred_test == test_data_finalY)*100,'%')

``````

iteration at 0 cost : 0.6932015486338629
iteration at 100 cost : 0.6482987506672847
iteration at 200 cost : 0.6443527436694975
iteration at 300 cost : 0.6439059082659386
iteration at 400 cost : 0.6436651460852033
iteration at 500 cost : 0.6431109804509275

1个回答

tensorflow框架训练好的神经网络模型，加载之后再去测试准确率特别低 图中是我的加载方法 麻烦大神帮忙指正，是不是网络加载出现问题 首先手动重新构建了模型：以下代码省略了权值、偏置和网络搭建 ``` # 构建模型 pred = alex_net(x, weights, biases, keep_prob) # 定义损失函数和优化器 cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=pred))#softmax和交叉熵结合 optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # 评估函数 correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # 3.训练模型和评估模型 # 初始化变量 init = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session() as sess: # 初始化变量 sess.run(init) saver.restore(sess, tf.train.latest_checkpoint(model_dir)) pred_test=sess.run(pred,{x:test_x, keep_prob:1.0}) result=sess.run(tf.argmax(pred_test, 1)) ```

``` with tf.name_scope('input_layer'): #输出层。将输出层权重、偏置、净输入放在一起 with tf.name_scope('weight_i'): Weights0 = tf.Variable(tf.random_normal([21, 8])) variable_summaries(Weights0) with tf.name_scope('bias_i'): biases0 = tf.Variable(tf.zeros([1, 8]) + 0.1) variable_summaries(biases0) with tf.name_scope('Wx_plus_b_i'): Wx_plus_b00 = tf.matmul(X, Weights0) + biases0 variable_summaries(Wx_plus_b00) l00 = tf.nn.sigmoid(Wx_plus_b00) with tf.name_scope('output_layer'): with tf.name_scope('weight_o'): Weights1 = tf.Variable(tf.random_normal([8, 1])) variable_summaries(Weights1) with tf.name_scope('bias_o'): biases1 = tf.Variable(tf.zeros([1, 1]) + 0.1) variable_summaries(biases1) with tf.name_scope('Wx_plus_b_o'): Wx_plus_b1 = tf.matmul(l00, Weights1) + biases1 variable_summaries(Wx_plus_b1) prediction = tf.nn.sigmoid(Wx_plus_b1) ``` 这是我的网络结构 ``` cost=tf.reduce_mean(tf.square(pred - ys)) optm=tf.train.GradientDescentOptimizer(0.01).minimize(cost) ``` 这是我的均方差函数和梯度下降函数 ![图片说明](https://img-ask.csdn.net/upload/201904/10/1554877016_12870.png)

Minimum Transport Cost

These are N cities in Spring country. Between each pair of cities there may be one transportation track or none. Now there is some cargo that should be delivered from one city to another. The transportation fee consists of two parts: The cost of the transportation on the path between these cities, and a certain tax which will be charged whenever any cargo passing through one city, except for the source and the destination cities. You must write a program to find the route which has the minimum cost. Input First is N, number of cities. N = 0 indicates the end of input. The data of path cost, city tax, source and destination cities are given in the input, which is of the form: a11 a12 ... a1N a21 a22 ... a2N ............... aN1 aN2 ... aNN b1 b2 ... bN c d e f ... g h where aij is the transport cost from city i to city j, aij = -1 indicates there is no direct path between city i and city j. bi represents the tax of passing through city i. And the cargo is to be delivered from city c to city d, city e to city f, ..., and g = h = -1. You must output the sequence of cities passed by and the total cost which is of the form: Output From c to d : Path: c-->c1-->......-->ck-->d Total cost : ...... ...... From e to f : Path: e-->e1-->..........-->ek-->f Total cost : ...... Note: if there are more minimal paths, output the lexically smallest one. Print a blank line after each test case. Sample Input 5 0 3 22 -1 4 3 0 5 -1 -1 22 5 0 9 20 -1 -1 9 0 4 4 -1 20 4 0 5 17 8 3 1 1 3 3 5 2 4 -1 -1 0 Sample Output From 1 to 3 : Path: 1-->5-->4-->3 Total cost : 21 From 3 to 5 : Path: 3-->4-->5 Total cost : 16 From 2 to 4 : Path: 2-->1-->5-->4 Total cost : 17

logistic regression costFunction问题

J = m^-1 * sum(((-1) * y.*log(h)).-((1- y).*log(1 - h))); 在matlab2014b里面提示运算符异常应该如何修改。

1.假如说我有一份采样间隔是按天算的数据集，训练集1,2,3,4,5天，那如果要实现提前2天预测，那我的测试集应该选哪个，第7天？还是第6和7两天的？之前查了下网上对horizon说的都很模糊。 2.滞后性怎么体现呢？比如训练集1,2,3,4天，测试集第5天，那如果滞后一期，表示的是什么？预测的其实是第4天数据吗？

Minimal search cost

Problem Description As we know, we need to spend O(n) time in the abstract finding a key(every two keys are different) in a non-sorted array. But if we make up a BST(binary search tree) before, then for each access, you need to spend log(N) time to do it. And for each access, there exists a road from the root node to the target node, whose length Ci is the number of the edges of the road. Because there is an accessing frequency Fi for each key. And the total value of the tree is defined as following rule: SUM=Sigma(Ci*Fi), for i from 0 to N-1, N is the number of the keys. You need to find the minimal value M_SUM to make up a tree. Input There are a lot of cases. In each case, in the first line, there is an integer N to represent the number of keys. In the second line, there are N sorted integers Ki. In the third line, there are N integers Fi, which are the accessing frequency. 0<N<=1000, 0<=Fi<65536. Output For each case, just output the minimal search cost. Sample Input 5 1 2 3 4 5 2 5 4 9 6 Sample Output 23

<div class="post-text" itemprop="text"> <p>I have developed a POS system with purchasing and selling. When purchasing i am saving cost price for each products as a GRN with other details and update purchase quantity as a total for each item in the stocks table. But i dont have an idea to calculate costs for these products according to FIFO or LIFO.</p> <p><strong>GRN TABLE</strong></p> <pre><code>`id` `department_id` `grn_no` `grn_date` `supplier_id` `reference` `description` </code></pre> <p><strong>GRN DETAILS TABLE</strong></p> <pre><code>`id` `grn_id` `item_id` `quantity` `expiry_date` `cost_price` </code></pre> <p>Selling price set to newest price always.</p> <p><strong>STOCKS TABLE</strong></p> <pre><code>`id` `item_id` `department_id` `price` `wholesale_price` `quantity` </code></pre> <p>When i am selling, i am reducing stock quantity from stocks table. But i dont have idea to calculate cost price according to LIFO or FIFO. If someone know it, please guide me through.</p> <p><strong>DATA SAMPLE</strong></p> <pre><code>Jan 1 - Purchased item1 - 100 units at \$10 Jan 10 - Purchased item1 - 100 Units at \$11 Jan 20 - Purchased item1 - 100 Units at \$9 Jan 30 - Purchased item1 - 100 Units at \$12 </code></pre> <p><strong>EXPECTED RESULT</strong></p> <p><strong>Costing Report for Jan 10</strong></p> <pre><code>Total sales for item1 is 25 Units at XX cost according to FIFO Total sales for item1 is 30 Units at YY cost according to FIFO System has 150 Units from item1 as current stock and current cost is ZZ according to FIFO </code></pre> </div>

Matlab实现Logistic Regression时的一个小问题

Ng机器学习编程作业matlab实现LR时里有这样一段 %% ============= Part 3: Optimizing using fminunc ============= % In this exercise, you will use a built-in function (fminunc) to find the % optimal parameters theta. % Set options for fminunc options = optimset('GradObj', 'on', 'MaxIter', 400); % Run fminunc to obtain the optimal theta % This function will return theta and the cost [theta, cost] = ... fminunc(@(t)(costFunction(t, X, y)), initial_theta, options); ... ================================ 不是很能理解optimset和fminunc的用法 [theta, cost] = ... fminunc(@(t)(costFunction(t, X, y)), initial_theta, options); =============================== 我是matlab初学者，这里需要用这个函数来实现梯度下降算法，也就是迭代多次学习theta。请问在fminunc里是怎样实现迭代的呢？那个@t是什么意思？optimset里的‘GradObj’是什么意思？ 跪等大神解救！

HM编码器如何打印最优深度为非64x64CU的rdcost

HM中的单位都是pCtu，在xcompresscu函数之后如何打印例如最优深度为32x32的rdcost？

<div class="post-text" itemprop="text"> <p>I have a Custom Product Attribute named as 'ship_cost' with an input type 'text field'. While putting a value on back-end, it automatically adds four extra zeros after the decimal point.</p> <p>I want this price in 'Rs. 45.00' format but currently it is showing as 'Rs. 45.0000'.</p> <p>I have not worked with Magento for a long time, basically, I am a newbie.</p> </div>

<div class="post-text" itemprop="text"> <p>I was wondering if someone could help with this. I'm trying to do a php query to update post meta values on Wordpress. Pb : the string has to be very long and full of unorthodox characters like double quotes. </p> <p>The result is somewhat strange as it gets updated but adds another serial around the value, breaking it, like this :</p> <p>s:5086:"<strong>a:28:{i:0;a:7:.....</strong></p> <p>Here's the initial query, if someone could figure out how to make it compliant that'd be amazing :</p> <pre><code>update_post_meta( \$product_id, '_wc_booking_pricing', 'a:28:{i:0;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:5:"0.027";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"1";s:2:"to";s:1:"3";}i:1;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.02914814815";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"4";s:2:"to";s:1:"4";}i:2;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:12:"0.0312962963";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"5";s:2:"to";s:1:"5";}i:3;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.03344444444";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"6";s:2:"to";s:1:"6";}i:4;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.03559259259";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"7";s:2:"to";s:1:"7";}i:5;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.03774074074";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"8";s:2:"to";s:1:"8";}i:6;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.03988888889";s:13:"base_modifier";s:5:"times";s:4:"from";s:1:"9";s:2:"to";s:1:"9";}i:7;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.04203703704";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"10";s:2:"to";s:2:"10";}i:8;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.04418518519";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"11";s:2:"to";s:2:"11";}i:9;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.04633333333";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"12";s:2:"to";s:2:"12";}i:10;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.04848148148";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"13";s:2:"to";s:2:"13";}i:11;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.05062962963";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"14";s:2:"to";s:2:"14";}i:12;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.05277777778";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"15";s:2:"to";s:2:"15";}i:13;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.05492592593";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"16";s:2:"to";s:2:"16";}i:14;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.05707407407";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"17";s:2:"to";s:2:"17";}i:15;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.05922222222";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"18";s:2:"to";s:2:"18";}i:16;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.06137037037";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"19";s:2:"to";s:2:"19";}i:17;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.06351851852";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"20";s:2:"to";s:2:"20";}i:18;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.06566666667";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"21";s:2:"to";s:2:"21";}i:19;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.06781481481";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"22";s:2:"to";s:2:"22";}i:20;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.06996296296";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"23";s:2:"to";s:2:"23";}i:21;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.07211111111";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"24";s:2:"to";s:2:"24";}i:22;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.07425925926";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"25";s:2:"to";s:2:"25";}i:23;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.07640740741";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"26";s:2:"to";s:2:"26";}i:24;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.07855555556";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"27";s:2:"to";s:2:"27";}i:25;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:12:"0.0807037037";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"28";s:2:"to";s:2:"28";}i:26;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:13:"0.08285185185";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"29";s:2:"to";s:2:"29";}i:27;a:7:{s:4:"type";s:6:"blocks";s:4:"cost";s:0:"";s:8:"modifier";s:0:"";s:9:"base_cost";s:5:"0.085";s:13:"base_modifier";s:5:"times";s:4:"from";s:2:"30";s:2:"to";s:2:"30";}}'); </code></pre> </div>

C++(数据结构与算法)78:---分而治之

springboot+jwt实现token登陆权限认证

win10暴力查看wifi密码

MySQL数据库面试题（2020最新版）

!大部分程序员只会写3年代码

2020阿里全球数学大赛：3万名高手、4道题、2天2夜未交卷

HashMap底层实现原理，红黑树，B+树，B树的结构原理 Spring的AOP和IOC是什么？它们常见的使用场景有哪些？Spring事务，事务的属性，传播行为，数据库隔离级别 Spring和SpringMVC，MyBatis以及SpringBoot的注解分别有哪些？SpringMVC的工作原理，SpringBoot框架的优点，MyBatis框架的优点 SpringCould组件有哪些，他们...

Python爬虫，高清美图我全都要（彼岸桌面壁纸）

Java岗开发3年，公司临时抽查算法，离职后这几题我记一辈子