Python进行决策树剪枝提示AttributeError: 'function' object has no attribute 'deepcopy'。

图片说明
在进行决策树剪枝的时候出现AttributeError: 'function' object has no attribute 'deepcopy'错误,一直解决不了。

1个回答

import copy
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
决策树剪枝中,合并子树前后,熵的变化量如何计算?

小弟在学习决策树剪枝,有一部分需要判断合并两个子树前后,熵的变化量 熵的计算公式和变化量的计算公式如下: ``` # 计算子树tb和fb在合并前后熵的变化量 delta=entropy(tb+fb)-(entropy(tb)+entropy(fb)/2) #计算熵,rows是一个数据表,uniquecounts计算该表最后一列每种值出现的次数,是一个dict
 def entropy(rows):
 from math import log
 log2 = lambda x:log(x)/log(2)
 results = uniquecounts(rows)

 ent = 0.0
 for r in results.keys():
 p = float(results[r])/len(rows)
 ent = ent-p*log2(p)
 return ent ``` 计算熵变化量的那里,为啥有个除以2? 我觉得应该是 delta=entropy(tb+fb)-(entropy(tb)+entropy(fb))

R语言实现决策树的步骤和分析

R语言中决策树的代码是如何实现的,有没有一个具体的例子,最后有实现后期的分析解释。。

求助:(Python)目标检测FPS经剪枝后为什么反而变小?

如题: 根据ssd进行剪枝后得到的网络参数减小,理想上是FPS会增大,起到加速的作用,但是实际情况是FPS随剪枝程度降低了,这是为什么呢?求大佬指点~ ![图片说明](https://img-ask.csdn.net/upload/201907/08/1562598037_733210.png) 我用的是添加bn层的network slimming方法剪枝,应该是结构化剪枝,结果上显示并没有实现加速,这是为什么呢? 是直接扔掉了部分通道,通道数减少。 原本: Configuration: [64, 64, 'M', 128, 128, 'M', 256, 256, 255, 'C', 512, 512, 512, 'M', 512, 512, 512] 剪枝后: Configuration: [14, 22, 'M', 28, 39, 'M', 67, 84, 58, 'C', 126, 107, 153, 'M', 140, 175, 254] (代码是在开源的ssd的基础上修改得到的)

python算法编码问题咨询

以下是apriori关联算法的实例代码实现,是用python实现的,IDE是myeclipse,没有报错: #coding:utf-8 samples = [ ["I1","I2","I5"], ["I2","I4"], ["I2","I3"], ["I1","I2","I4"], ["I1","I3"], ["I2","I3"], ["I1","I3"], ["I1","I2","I3","I5"], ["I1","I2","I3"] ] min_support = 2 min_confidence = 0.6 fre_list = list() def get_c1(): global record_list global record_dict new_dict = dict() for row in samples: for item in row: if item not in fre_list: fre_list.append(item) new_dict[item] = 1 else: new_dict[item] = new_dict[item] + 1 fre_list.sort() print ("candidate set:") print_dict(new_dict) for key in fre_list: if new_dict[key] < min_support: del new_dict[key] print ("after pruning:") print_dict(new_dict) record_list = fre_list record_dict = record_dict def get_candidateset(): new_list = list() #自连接 for i in range(0,len(fre_list)): for j in range(0,len(fre_list)): if i == j: continue #如果两个k项集可以自连接,必须保证它们有k-1项是相同的 if has_samesubitem(fre_list[i],fre_list[j]): curitem = fre_list[i] + ',' + fre_list[j] curitem = curitem.split(",") curitem = list(set(curitem)) curitem.sort() curitem = ','.join(curitem) #如果一个k项集要成为候选集,必须保证它的所有子集都是频繁的 if has_infresubset(curitem) == False and already_constains(curitem,new_list) == False: new_list.append(curitem) new_list.sort() return new_list def has_samesubitem(str1,str2): str1s = str1.split(",") str2s = str2.split(",") if len(str1s) != len(str2s): return False nums = 0 for items in str1s: if items in str2s: nums += 1 str2s.remove(items) if nums == len(str1s) - 1: return True else: return False def judge(candidatelist): # 计算候选集的支持度 new_dict = dict() for item in candidatelist: new_dict[item] = get_support(item) print ("candidate set:") print_dict(new_dict) #剪枝 #频繁集的支持度要大于最小支持度 new_list = list() for item in candidatelist: if new_dict[item] < min_support: del new_dict[item] continue else: new_list.append(item) global fre_list fre_list = new_list print ("after pruning:") print_dict(new_dict) return new_dict def has_infresubset(item): # 由于是逐层搜索的,所以对于Ck候选集只需要判断它的k-1子集是否包含非频繁集即可 subset_list = get_subset(item.split(",")) for item_list in subset_list: if already_constains(item_list,fre_list) == False: return True return False def get_support(item,splitetag=True): if splitetag: items = item.split(",") else: items = item.split("^") support = 0 for row in samples: tag = True for curitem in items: if curitem not in row: tag = False continue if tag: support += 1 return support def get_fullpermutation(arr): if len(arr) == 1: return [arr] else: newlist = list() for i in range(0,len(arr)): sublist = get_fullpermutation(arr[0:i]+arr[i+1:len(arr)]) for item in sublist: curlist = list() curlist.append(arr[i]) curlist.extend(item) newlist.append(curlist) return newlist def get_subset(arr): newlist = list() for i in range(0,len(arr)): arr1 = arr[0:i]+arr[i+1:len(arr)] newlist1 = get_fullpermutation(arr1) for newlist_item in newlist1: newlist.append(newlist_item) newlist.sort() newlist = remove_dumplicate(newlist) return newlist def remove_dumplicate(arr): newlist = list() for i in range(0,len(arr)): if already_constains(arr[i],newlist) == False: newlist.append(arr[i]) return newlist def already_constains(item,curlist): import types items = list() if type(item) is types.StringType: items = item.split(",") else: items = item for i in range(0,len(curlist)): curitems = list() if type(curlist[i]) is types.StringType: curitems = curlist[i].split(",") else: curitems = curlist[i] if len(set(items)) == len(curitems) and len(list(set(items).difference(set(curitems)))) == 0: return True return False def print_dict(curdict): keys = curdict.keys() keys.sort() for curkey in keys: print ("%s:%s"%curkey,curdict[curkey]) # 计算关联规则的方法 def get_all_subset(arr): rtn = list() while True: subset_list = get_subset(arr) stop = False for subset_item_list in subset_list: if len(subset_item_list) == 1: stop = True rtn.append(subset_item_list) if stop: break return rtn def get_all_subses(s): from itertools import combinations return sum(map(lambda r: list(combinations(s, r)), range(1, len(s)+1)), []) def cal_associative_rule(frelist): rule_list = list() rule_dict = dict() for fre_item in frelist: fre_items = fre_item.split(",") subitem_list = get_all_subset(fre_items) for subitem in subitem_list: # 忽略为为自身的子集 if len(subitem) == len(fre_items): continue else: difference = set(fre_items).difference(subitem) rule_list.append("^".join(subitem)+"->"+"^".join(difference)) print ("The rule is:") for rule in rule_list: conf = cal_rule_confidency(rule) print (rule,conf) if conf >= min_confidence: rule_dict[rule] = conf print ("The associative rule is:") for key in rule_list: if key in rule_dict.keys(): print (key,":",rule_dict[key]) def cal_rule_confidency(rule): rules = rule.split("->") support1 = get_support("^".join(rules),False) support2 = get_support(rules[0],False) if support2 == 0: return 0 rule_confidency = float(support1)/float(support2) return rule_confidency if __name__ == '__main__': record_list = list() record_dict = dict() get_c1() # 不断进行自连接和剪枝,直到得到最终的频繁集为止;终止条件是,如果自连接得到的已经不再是频繁集 # 那么取最后一次得到的频繁集作为结果 while True: record_list = fre_list new_list = get_candidateset() judge_dict = judge(new_list) if len(judge_dict) == 0: break else: record_dict = judge_dict print ("The final frequency set is:") print (record_list) # 根据频繁集计算关联规则 cal_associative_rule(record_list) 运行后,出错,结果输出如下: Traceback (most recent call last): File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 213, in <module> candidate set: get_c1() File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 29, in get_c1 print_dict(new_dict) File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 160, in print_dict keys.sort() AttributeError: 'dict_keys' object has no attribute 'sort' 找了很久,不知道出错点在哪,求指教。

数据结构方面的树形剪枝算法的一个例题,怎么采用C语言的实现的?

Problem Description Disney's FastPass is a virtual queuing system created by the Walt Disney Company. First introduced in 1999 (thugh the idea of a ride reservation system was first introduced in world fairs), Fast-Pass allows guests to avoid long lines at the attractions on which the system is installed, freeing them to enjoy other attractions during their wait. The service is available at no additional charge to all park guests. --- wikipedia Disneyland is a large theme park with plenties of entertainment facilities, also with a large number of tourists. Normally, you need to wait for a long time before geting the chance to enjoy any of the attractions. The FastPass is a system allowing you to pick up FastPass-tickets in some specific position, and use them at the corresponding facility to avoid long lines. With the help of the FastPass System, one can arrange his/her trip more efficiently. You are given the map of the whole park, and there are some attractions that you are interested in. How to visit all the interested attractions within the shortest time? Input The first line contains an integer T(1<=T<=25), indicating the number of test cases. Each test case contains several lines. The first line contains three integers N,M,K(1 <= N <= 50; 0 <= M <= N(N - 1)/2; 0 <= K <= 8), indicating the number of locations(starting with 1, and 1 is the only gate of the park where the trip must be started and ended), the number of roads and the number of interested attractions. The following M lines each contains three integers A,B,D(1 <= A,B <= N; 0 <= D <= 10^4) which means it takes D minutes to travel between location A and location B. The following K lines each contains several integers Pi, Ti, FTi,Ni, Fi,1, Fi,2 ... Fi,Ni-1, FiNi ,(1 <= Pi,Ni, Fi,j <=N, 0 <= FTi <= Ti <= 10^4), which means the ith interested araction is placed at location Pi and there are Ni locations Fi,1; Fi,2 ... Fi,Ni where you can get the FastPass for the ith attraction. If you come to the ith attraction with its FastPass, you need to wait for only FTi minutes, otherwise you need to wait for Ti minutes. You can assume that all the locations are connected and there is at most one road between any two locations. Note that there might be several attrractions at one location. Output For each test case in the input, print one line: "Case #X: Y", where X is the test case number (starting with 1) and Y is the minimum time of the trip. Sample Input 2 4 5 2 1 2 8 2 3 4 3 4 19 4 1 6 2 4 7 2 25 18 1 3 4 12 6 1 3 4 6 2 1 2 5 1 4 4 3 1 1 3 2 1 3 4 1 2 4 10 2 8 3 1 4 4 8 3 1 2 Sample Output Case #1: 53 Case #2: 14

回溯、深搜、剪枝的区别是什么?

在刷题中,看题解时总是遇到DFS、回溯、剪枝这类字眼,但总是搞不懂他们有什么区别。 **以下是我的理解,不知是否正确?** **剪枝是用来优化的,深搜是将一种可能执行到底,而回溯是碰到不可行的情况就结束,开始下次遍历, 那么深搜+剪枝=回溯。**

人工智能alpha-beta剪枝和离散数学的练习题

/3. 应用归结反演来检查输入的句子是否包含知识库。写下解决步骤。 KB P ˅ Q ¬ P ˅ Q P ˅ ¬ Q Input Sentence P ∧ Q

关于中国象棋程序里面的阿尔法贝塔剪枝算法的缺点

如题, 最近在研究中国象棋,参考中国象棋程序一书的代码, 利用阿尔法贝塔剪枝法实现了简单的象棋程序, 后发现基于此算法的象棋程序有一定缺陷, 如果红方不主动进攻,黑方(AI)将不会进攻,只会不断地上士或者出将, 应该怎么解决呢?

请问一下,搜索对抗算法中AlphaBeta剪枝算法树中的叶子节点的分数是怎么来的?

![图片说明](https://img-ask.csdn.net/upload/201710/15/1508045375_933214.png) 如图,叶子节点(圈圈表示的)里的分数是怎么来的? 是这一步应该有的分数还是往上父节点到顶累加出来的?

数据结构里的剪枝算法的问题运用C语言编程技术的实现的做法

Problem Description A rooted graph is an indirected graph with every edge attached by some path to a special vertex called the root or the ground. The ground is denoted in the below figures that follow by a dotted line. A bamboo stalk with n segments is a linear graph of n edges with the bottom of the n edges rooted to the ground. A move consists of hacking away one of the segments, and removing that segment and all segments above it no longer connectd to the ground. Two players alternate moves and the last player to move wins. A single bamboo stalk of n segments can be moved into a bamboo stalk of any smaller number of segments from n-1 to 0. So a single bamboo stalk of n segments is equivalent to a nim pile of n chips. As you known, the player who moves first can win the the game with only one bamboo stalk. So many people always play the game with several bamboo stalks. One example is as below: Playing a sum of games of bamboo stalks is thus equivalent to playing a nim game that with several piles. A move consisits of selecting a bamboo stalk containg n segments and hacking away one of the segments in the selected bamboo stalk. I think the nim game is easy for you, the smart ACMers. So, today, we play a game named "cutting trees". A "rooted tree" is a graph with a distinguished vertex called the root, with the property that from every vertex there is unique path(that doesn't repeat edges) to the root. Essentially this means there are no cycles. Of course, in the game "cutting trees", there are several trees.Again, a move consisits of selecting a tree and hacking away any segment and removing segment and anything not connected to the ground. The player who cuts the last segment wins the game. Input Standard input will contain multiple test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each case begins with a N(1<=N<=1000), the number of trees in the game.A tree is decribed by a number m, the nodes of the tree and R(0<=R<=m-1), the root of the tree. Then m-1 lines follow, each line containg two positive integers A,B∈[0,m-1], means that there is a edge between A and B. In the game, the first player always moves first. Output Results should be directed to standard output. For each case, if the first player wins, ouput "The first player wins", or else, output "The second player wins",in a single line. Sample Input 1 1 4 0 0 1 1 2 1 3 Sample Output The first player wins

这样写minmax算法怎么α-β剪枝

请各位大大在下面的部分补上剪枝的部分(*^__^*) minmax() { Max(chessboard, -∞, ∞, depth - 1, CurMover); } Max() { best=-∞; for(遍历棋盘) { if(叶子节点) value=评价局面; else { 假设落子; value=Min(chessboa, a, b, depth - 1, NextMover); } if(best<value) best=value; } return best; } Min() { best=∞; for(遍历棋盘) { if(叶子节点) value=评价局面; else { 假设落子; value=Max(chessboa, a, b, depth - 1, NextMover); } if(best>value) best=value; } return best; }

关于Python学习,求指点

我想学Python, 怎么样才能把它学的透呢?求各位大神指点迷津,推荐教程或者Python培训机构 。教的好就行。

下面的代码dfs剪枝的if语句是什么意思????

描述 小珂最近收集了些邮票,他想把其中的一些给他的好朋友小明。每张邮票上都有分值,他们想把这些邮票分成两份,并且使这两份邮票的分值和相差最小(就是小珂得到的邮票分值和与小明的差值最小),现在每张邮票的分值已经知道了,他们已经分好了,你知道最后他们得到的邮票分值和相差多少吗? ``` #include <stdio.h> #define max(a,b) a>b?a:b int V,ans,n,w[110],sum[110]; void dfs(int i,int cnt) { if(i == 0) { ans = max(ans,cnt); return ; } if(ans == V || cnt+sum[i] <= ans) //cut return ; if(cnt+w[i] <= V) dfs(i-1,cnt+w[i]); dfs(i-1,cnt); } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d",&n); ans = 0; for(int i=1;i<=n;i++) { scanf("%d",&w[i]); sum[i] = sum[i-1] + w[i]; } V = sum[n]/2; dfs(n,0); printf("%d\n",sum[n]-2*ans); } return 0; } ```

多分枝结果的排序和剪枝算法的使用运用,采用C语言的实现

Problem Description If you want to buy a new cellular phone, there are many various types to choose from. To decide which one is the best for you, you have to consider several important things: its size and weight, battery capacity, WAP support, colour, price. One of the most important things is also the list of games the phone provides. Nokia is one of the most successful phone makers because of its famous Snake and Snake II. ACM wants to make and sell its own phone and they need to program several games for it. One of them is Master-Mind, the famous board logical game. The game is played between two players. One of them chooses a secret code consisting of P ordered pins, each of them having one of the predefined set of C colours. The goal of the second player is to guess that secret sequence of colours. Some colours may not appear in the code, some colours may appear more than once. The player makes guesses, which are formed in the same way as the secret code. After each guess, he/she is provided with an information on how successful the guess was. This feedback is called a hint. Each hint consists of B black points and W white points. The black point stands for every pin that was guessed right, i.e. the right colour was put on the right position. The white point means right colour but on the wrong position. For example, if the secret code is "white, yellow, red, blue, white" and the guess was "white, red, white, white, blue", the hint would consist of one black point (for the white on the first position) and three white points (for the other white, red and blue colours). The goal is to guess the sequence with the minimal number of hints. The new ACM phone should have the possibility to play both roles. It can make the secret code and give hints, but it can also make its own guesses. Your goal is to write a program for the latter case, that means a program that makes Master-Mind guesses. Input There is a single positive integer T on the first line of input. It stands for the number of test cases to follow. Each test case describes one game situation and you are to make a guess. On the first line of each test case, there are three integer numbers, P, C and M. P ( 1 <= P <= 10) is the number of pins, C (1 <= C <= 100) is the number of colours, and M (1 <= M <= 100) is the number of already played guesses. Then there are 2 x M lines, two lines for every guess. At the first line of each guess, there are P integer numbers representing colours of the guess. Each colour is represented by a number Gi, 1 <= Gi <= C. The second line contains two integer numbers, B and W, stating for the number of black and white points given by the corresponding hint. Let's have a secret code S1, S2, ... SP and the guess G1, G2, ... GP. Then we can make a set H containing pairs of numbers (I,J) such that SI = GJ, and that any number can appear at most once on the first position and at most once on the second position. That means for every two different pairs from that set, (I1,J1) and (I2,J2), we have I1 <> I2 and J1 <> J2. Then we denote B(H) the number of pairs in the set, that meet the condition I = J, and W(H) the number of pairs with I <> J. We define an ordering of every two possible sets H1 and H2. Let's say H1 <= H2 if and only if one of the following holds: B(H1) < B(H2), or B(H1) = B(H2) and W(H1) <= W(H2) Then we can find a maximal set Hmax according to this ordering. The numbers B(Hmax) and W(Hmax) are the black and white points for that hint. Output For every test case, print the line containing P numbers representing P colours of the next guess. Your guess must be valid according to all previous guesses and hints. The guess is valid if the sequence could be a secret code, i.e. the sequence was not eliminated by previous guesses and hints. If there is no valid guess possible, output the sentence You are cheating!. If there are more valid guesses, output the one that is lexicographically smallest. I.e. find such guess G that for every other valid guess V there exists such a number I that: GJ = VJ for every J<I, and GI<VI. Sample Input 3 4 3 2 1 2 3 2 1 1 2 1 3 2 1 1 4 6 2 3 3 3 3 3 0 4 4 4 4 2 0 8 9 3 1 2 3 4 5 6 7 8 0 0 2 3 4 5 6 7 8 9 1 0 3 4 5 6 7 8 9 9 2 0 Sample Output 1 1 1 3 You are cheating! 9 9 9 9 9 9 9 9

急,跪求pycharm跑yolov3-train.py报错

![图片说明](https://img-ask.csdn.net/upload/201905/23/1558616226_449733.png) ``` import numpy as np import keras.backend as K from keras.layers import Input, Lambda from keras.models import Model from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss from yolo3.utils import get_random_data def _main(): annotation_path = 'train.txt' log_dir = 'logs/000/' classes_path = 'model_data/voc_classes.txt' anchors_path = 'model_data/yolo_anchors.txt' class_names = get_classes(classes_path) anchors = get_anchors(anchors_path) input_shape = (416,416) # multiple of 32, hw model = create_model(input_shape, anchors, len(class_names) ) train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir) def train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'): model.compile(optimizer='adam', loss={ 'yolo_loss': lambda y_true, y_pred: y_pred}) logging = TensorBoard(log_dir=log_dir) checkpoint = ModelCheckpoint(log_dir + "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5", monitor='val_loss', save_weights_only=True, save_best_only=True, period=1) batch_size = 8 val_split = 0.1 with open(annotation_path) as f: lines = f.readlines() np.random.shuffle(lines) num_val = int(len(lines)*val_split) num_train = len(lines) - num_val print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) model.fit_generator ( data_generator_wrapper ( lines[:num_train] , batch_size , input_shape , anchors , num_classes ) , steps_per_epoch=max ( 1 , num_train // batch_size ) , validation_data=data_generator_wrapper ( lines[num_train:] , batch_size , input_shape , anchors , num_classes ) , validation_steps=max ( 1 , num_val // batch_size ) , epochs=10 , initial_epoch=0 , callbacks=[logging , checkpoint] ) model.save_weights(log_dir + 'trained_weights.h5') def get_classes(classes_path): with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def get_anchors(anchors_path): with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) def create_model(input_shape, anchors, num_classes, load_pretrained=False, freeze_body=False, weights_path='model_data/yolo_weights.h5'): K.clear_session() # get a new session h, w = input_shape image_input = Input(shape=(w, h, 3)) num_anchors = len(anchors) y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], num_anchors//3, num_classes+5)) for l in range(3)] model_body = yolo_body(image_input, num_anchors//3, num_classes) print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes)) if load_pretrained: model_body.load_weights(weights_path, by_name=True, skip_mismatch=True) print('Load weights {}.'.format(weights_path)) if freeze_body in [1, 2]: # Do not freeze 3 output layers. num = (185 , len ( model_body.layers ) - 3)[freeze_body - 1] for i in range(num): model_body.layers[i].trainable = False print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers))) model_loss = Lambda ( yolo_loss , output_shape=(1 ,) , name='yolo_loss', arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5} )(model_body.output + y_true) model = Model(inputs=[model_body.input] + y_true, outputs=model_loss) return model def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): n = len(annotation_lines) i = 0 while True: image_data = [] box_data = [] for b in range(batch_size): if i==0: np.random.shuffle(annotation_lines) image, box = get_random_data(annotation_lines[i], input_shape, random=True) image_data.append(image) box_data.append(box) i = (i+1) % n image_data = np.array(image_data) box_data = np.array(box_data) y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes) yield [image_data]+y_true, np.zeros(batch_size) def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes): n = len(annotation_lines) if n==0 or batch_size<=0: return None return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes) if __name__ == '__main__': _main() ``` 报了一个:tensorflow.python.framework.errors_impl.InvalidArgumentError: Inputs to operation training/Adam/gradients/AddN_24 of type _MklAddN must have the same size and shape. Input 0: [2768896] != input 1: [8,26,26,512] [[Node: training/Adam/gradients/AddN_24 = _MklAddN[N=2, T=DT_FLOAT, _kernel="MklOp", _device="/job:localhost/replica:0/task:0/device:CPU:0"](training/Adam/gradients/batch_normalization_65/FusedBatchNorm_grad/FusedBatchNormGrad, training/Adam/gradients/batch_n

关于xgboost.train()和xgboost.XGBClassifier().fit()的预测输出问题

问题:在用xgboost做多分类学习时遇到了问题,参数均一样,训练集和验证集也是一样的,评估用的是自己写的评估函数ndcg算法,但是用xgb.train()和XGBClassifier().fit()后评估打分的差距相差太大,想问是predict的结果不一样嘛?为什么会有这种情况出现? ``` # 数据集整理均是一样的 X_train, X_test, y_train, y_test = train_test_split(xtrain_new,ytrain_new,test_size=0.2,random_state=RANDOM_STATE) train_xgb = xgb.DMatrix(X_train, label= y_train) test_xgb = xgb.DMatrix(X_test, label = y_test) ``` **sklearn接口:**_ ``` # 用sklearn接口 xgb1 = XGBClassifier(max_depth=6,# 构建树的深度 learning_rate=0.1,# 如同学习率 n_estimators=100,#决策树数量 silent=False, objective='multi:softprob', booster='gbtree', num_class=12,# 类别数 n_jobs=4, gamma=0.2, min_child_weight=1, subsample=0.8,# 随机采样训练样本 colsample_bytree=0.7,# 生成树列采样 seed=RANDOM_STATE)# 随机种子 xgb_bst1 = xgb1.fit(X_train,y_train) y_pred = xgb_bst1.predict(X_test) test_ndcg_score = ndcg_score(y_test, y_pred, k=k_ndcg) print(test_ndcg_score) #评估打分 ``` 结果: ![图片说明](https://img-ask.csdn.net/upload/202005/20/1589905774_281258.png) **下面是原生接口:** ``` # 下面是原生接口,参数也是一样 params={ 'max_depth':6,# 构建树的深度,越大越容易过拟合 'eta':0.1,# 如同学习率 'num_round':100,#决策树数量 'objective':'multi:softprob',# 多分类的问题 'booster':'gbtree', 'num_class':12,# 类别数,与 multisoftmax 并用 'n_jobs':4, 'gamma':0.2,# 用于控制是否后剪枝的参数,越大越保守 'min_child_weight':1, 'subsample':0.8,# 随机采样训练样本 'colsample_bytree':0.7, 'seed':RANDOM_STATE# 随机种子 } watchlist = [ (train_xgb,'train'), (test_xgb, 'test') ] # 训练模型 xgb2 = xgb.train(params, train_xgb, params['num_round'], watchlist, feval = customized_eval, verbose_eval = 3, early_stopping_rounds = 5) # 预测模型评估 y_pred = np.array(xgb2.predict(test_xgb)) test_ndcg_score = ndcg_score(y_test, y_pred, k=k_ndcg) print(test_ndcg_score)# 评估打分 ``` 结果:![图片说明](https://img-ask.csdn.net/upload/202005/20/1589905808_668246.png) ndcg_score函数是自己写的,multi:softprob的输出应该是一个概率矩阵,不明白为什么评估差距很大,希望有人能解答!!谢谢!!

HDU-1010的剪枝问题的困惑

在做HDU-1010的时候,真的很无奈很痛苦,永远TLE,我在网上也查了很久,我的代码 几乎把网上所有说的剪枝方法都用上了,但还是TLE 附上题目链接: [](http://acm.hdu.edu.cn/showproblem.php?pid=1010 "") 再附上我的代码: ``` #include<iostream> #include<queue> #include<cstring> #include<cmath> using namespace std; int n, m, t, br, bc, er, ec, flag, wall; char maze[10][10],vis[10][10]; int dirr[4] = { -1,1,0,0 }; int dirc[4] = { 0,0,-1,1 }; inline bool checkr(int r) { return r >= 0 && r < n; } inline bool checkc(int c) { return c >= 0 && c < m; } /*int solve(int r, int c) //BFS { queue<pair<int, int> >q; q.push(make_pair(r, c)); while (!q.empty()) { pair<int, int> x = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { if (checkr(x.first, i) && checkc(x.second, i)) { int newr = x.first + dirr[i], newc = x.second + dirc[i]; if (maze[newr][newc] != 'X') { if (!time[newr][newc] && maze[newr][newc]!='S') { time[newr][newc] = time[x.first][x.second] + 1; q.push(make_pair(newr, newc)); } if (maze[newr][newc] == 'D') { return time[newr][newc]; } } } } } }*/ void solve(int r, int c, int t) { int tem = t - abs(er - r) - abs(ec - c); // cout << r << " " << c << " " << t << endl; // if (((r + c) % 2 + t % 2) != (er + ec) % 2) return; if (tem < 0 || tem & 1) return; if (t < er - r + ec - c) return; //两种剪枝 if (flag) return; // cout << r << " " << c << endl; --t; for (int i = 0; i < 4; ++i) { int newr = r + dirr[i], newc = c + dirc[i]; if (checkr(newr) && checkc(newc) && maze[newr][newc] != 'X' && !vis[newr][newc]) { if (newr == er && newc == ec && t != 0) continue; if (t >= 1) { // cout << "ok" << endl; vis[newr][newc] == 1; solve(newr, newc, t); if (flag) { return; } vis[newr][newc] == 0; } if (t == 0) { if (newr==er && newc==ec) { flag = 1; break; } } } } } int main() { cin >> n >> m >> t; while (n != 0) { memset(maze, 0, sizeof(maze)); memset(vis, 0, sizeof(vis)); flag = 0; wall = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cin >> maze[i][j]; if (maze[i][j] == 'S') { br = i; bc = j; } if (maze[i][j] == 'D') { er = i; ec = j; } if (maze[i][j] == 'X') { ++wall; } } } // cout << er << " " << ec << endl; if (n*m - wall <= t) { cout << "NO" << endl; cin >> n >> m >> t; continue; } vis[br][bc] = 1; solve(br, bc, t); // cout << res << endl; if (flag) { cout << "YES" << endl; } else { cout << "NO" << endl; } cin >> n >> m >> t; } return 0; } ``` 希望各位能指点一二,谢谢了

人工智能练习题,求解

4. 应用解析反驳来检查输入的句子是否包含知识库。写下决议的每一步。 KB P ˅ Q ¬ P ˅ Q P ˅ ¬ Q Input Sentence P ∧ Q

Java新人求解答:自己制作一个网站,出现问题,求详细解答。

我自己制作了一个网站,该网页上设定了插入图片这一选项,可是当我插入一张名为 Peter_Jackson.jpg 的图片后,网页上没有显示, 而且myeclipse的console还报出了如下错误: java.io.FileNotFoundException: C:\mysoftware\apache-tomcat-7.0.37\webapps\friend2\upload\pic_3\E:\David_Liu\picture\Peter_Jackson.jpg (文件名、目录名或卷标语法不正确。) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:221) at java.io.FileOutputStream.<init>(FileOutputStream.java:171) at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:439) at web.ActionServlet.service(ActionServlet.java:130) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745)

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

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

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

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

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

美团面试,问了ThreadLocal原理,这个回答让我通过了

他想都想不到,ThreadLocal我烂熟于心

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

立即提问
相关内容推荐