刚入门机器学习相关的软件包时,里面好多函数参数不知道应该怎么填,很茫然,这就需要看他自己的函数是怎么实现的,最起码知道调用的函数需要什么参数,报错了也不知道为什么会报错,如果只是依赖网上查,出错了就去网上搜,有点不知所以然,以下总结了一些对应方法,需要的点赞、收藏:
如何查看Python函数的源代码:
inspect库
inspect模块用于收集python对象的信息,可以获取类或者函数的参数信息,源码,解析堆栈,对对象进行类型检查等
使用方法:
import tensorflow as tf
import inspect
##查看文档定义
inspect.getdoc(tf.compat.v1.constant) #tensorflow 2.0版本
insprct.getdoc(tf.constant) #tensorflow < 2.0
#查看源程序路径
inpect.getsourcefile(tf.compat.v1.constant)
输出结果如下所示:
另外,python还提供了一些底层的函数来查看函数内容:dir(function), help(function), function.__file__, python官网。但是这些函数在查看tensorflow相关函数时不是特别的有效。
另外比较简单的一种方法是在pycharm中选中一个函数,然后按F4,就可以直接定位tensorflow中的函数了。
如何查看tensorflow底层代码实现(c,c++):
tensorflow中op的实现基本上都是有底层的一些算法程序,这样可以充分发挥c,c++的计算效率以及python简单的优势,一般在tensorflow中定义新的op需要下面的步骤:
1. 定义op接口并注册到tensorflow中,
2. 注册op实现,调用宏REGISTER_KERNEL_BUILDER,如下面的形式:
因此,对于一般的op,在tensorflow源代码中搜索REGISTER_OP("OpName")和
REGISTER_KERNEL_BUILDER(Name("OpName")
基本上就可以精确定位到这个op的接口定义和具体实现了。
另外一种方法可以参照博客https://blog.youkuaiyun.com/yolan6824/article/details/82620521所示,通过写一些脚本来进行实现,截图如下:
import os
import sys
findCount = 0
findId = "bidirectional_dynamic_rnn"
findDir = "C:/Users/dell/Anaconda3/envs/tensorflow1/Lib"
resultDir = "" #自己写一个目录
resultFile = os.path.join(resultDir,"bilstm.txt")
def writeResultAndPrint(fullPath):
file = open(resultFile,'a')
file.write(fullPath)
file.write("\n")
print "write ok!\n"
file.close()
def findKey(findId,fullPath):
file = open(fullPath,'r')
content = file.read()
file.close()
isExist = content.find(findId)
if isExist > 0:
global findCount
findCount = findCount + 1
writeResultAndPrint(fullPath)
def findFiles():
clean()
for dirPath,dirNames,fileNames in os.walk(findDir):
for file in fileNames:
fullPath = os.path.join(dirPath,file)
findKey(findId,fullPath)
print "has the string!!:" + str(findCount)
def clean():
if os.path.exists(resultFile):
os.remove(resultFile)
if __name__ == '__main__':
# a = sys.argv[1:]
# findId += a[0]
# findDir += a[1]
# resultDir += a[2]
findFiles()
酌情使用!!!
参考文献:
https://blog.youkuaiyun.com/yolan6824/article/details/82620521