您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了python函數(shù)中如何將變量名轉(zhuǎn)換成字符串,內(nèi)容簡(jiǎn)而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會(huì)有收獲的,下面讓小編帶大家一起來(lái)看看吧。
考慮到在日常中,常常需要對(duì)模型指標(biāo)輸出,但涉及多個(gè)模型的時(shí)候,需要對(duì)其有標(biāo)示輸出,故需要將模型變量名轉(zhuǎn)換成字符串。
看到的基本方法有兩種:
一、方法層面:
方法1(函數(shù)內(nèi)推薦):
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 in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) if m: return m.group(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 = processing.transform(X_train) X_test = processing.transform(X_test) model.fit(X_train, y_train) y_pred = model.predict(X_test) # print(namestr(model,globals())) print('**small-%s的準(zhǔn)確率**: %.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的準(zhǔn)確率**: 0.789
for model in [svm_origin, svm_rbf, lr_origin]:
small_feature_model(model)
輸出
**small-svm_origin的準(zhǔn)確率**: 0.789 **small-svm_rbf的準(zhǔn)確率**: 0.811 **small-lr_origin的準(zhǔn)確率**: 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 = processing.transform(X_train) X_test = processing.transform(X_test) model.fit(X_train, y_train) y_pred = model.predict(X_test) # print(namestr(model,globals())) print('**small-%s的準(zhǔn)確率**: %.3f' %(varname(model),accuracy_score(y_pred=y_pred, y_true=y_test))) small_feature_model(svm_origin)
輸出
**small-model的準(zhǔn)確率**: 0.789
for model in [svm_origin, svm_rbf, lr_origin]:
small_feature_model(model)
輸出
**small-model的準(zhǔn)確率**: 0.789 **small-model的準(zhǔn)確率**: 0.811 **small-model的準(zhǔn)確率**: 0.835
補(bǔ)充知識(shí):一個(gè)python實(shí)現(xiàn)翻轉(zhuǎn)字符串的函數(shù)
實(shí)現(xiàn)字符串翻轉(zhuǎn)的函數(shù)(python)
string = 'abcdef' def demo1(string): if len(string) <= 1: return string return demo1(string[1:]) +string[0] print(demo1(string))
中間用到了遞歸和切片不知道效率如何
以上就是關(guān)于python函數(shù)中如何將變量名轉(zhuǎn)換成字符串的內(nèi)容,如果你們有學(xué)習(xí)到知識(shí)或者技能,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。