python函数中将变量名转换成字符串实例
考虑到在⽇常中,常常需要对模型指标输出,但涉及多个模型的时候,需要对其有标⽰输出,故需要将模型变量名转换成字符串。
python教程字符串函数看到的基本⽅法有两种:
⼀、⽅法层⾯:
⽅法1(函数内推荐):
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
print(namestr(lr_origin,globals()),'\n',
namestr(lr_origin,globals())[0])
输出:
‘lr_origin'
⽅法2:
import inspect, re
def varname(p):
for line frameinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
up(1)
varname(lr_origin)
输出:
'lr_origin'
⼆、⽰例
采⽤⽅法1
def small_feature_model(model,X_train=X_train,y_train=y_train,X_test=X_test, y_test=y_test):
pca = PCA(n_components=150,random_state=0,whiten=True)
pipeline = Pipeline([('scale',StandardScaler()),('pca',pca)])
processing = pipeline.fit(X_train)
X_train = ansform(X_train)
X_test = ansform(X_test)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# print(namestr(model,globals()))
print('**small-%s的准确率**: %.3f' %(namestr(model,globals())[0],accuracy_score(y_pred=y_pred, y_true=y_test)))
small_feature_model(svm_origin)
输出
['svm_origin']
**small-svm_origin的准确率**: 0.789
for model in [svm_origin, svm_rbf, lr_origin]:
small_feature_model(model)
输出
**small-svm_origin的准确率**: 0.789
**small-svm_rbf的准确率**: 0.811
**small-lr_origin的准确率**: 0.835
采⽤⽅法2
def small_feature_model(model,X_train=X_train,y_train=y_train,X_test=X_test, y_test=y_test):
pca = PCA(n_components=150,random_state=0,whiten=True)
pipeline = Pipeline([('scale',StandardScaler()),('pca',pca)])
processing = pipeline.fit(X_train)
X_train = ansform(X_train)
X_test = ansform(X_test)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# print(namestr(model,globals()))
print('**small-%s的准确率**: %.3f' %(varname(model),accuracy_score(y_pred=y_pred, y_true=y_test)))
small_feature_model(svm_origin)
输出
**small-model的准确率**: 0.789
for model in [svm_origin, svm_rbf, lr_origin]:
small_feature_model(model)
输出
**small-model的准确率**: 0.789
**small-model的准确率**: 0.811
**small-model的准确率**: 0.835
补充知识:⼀个python实现翻转字符串的函数
实现字符串翻转的函数(python)
string = 'abcdef'
def demo1(string):
if len(string) <= 1:
return string
return demo1(string[1:]) +string[0]
print(demo1(string))
中间⽤到了递归和切⽚不知道效率如何
以上这篇python函数中将变量名转换成字符串实例就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。