Python split()的一点困惑

今天看到论坛关于字符串分割问题,见http://www.iteye.com/topic/1117302,看看别人的思路自己用python写了下,竟然报错,list index 越界。

 

'''
Created on 2011-11-2

@author:dudong0726
'''

if __name__ == '__main__':
    str="[Type=UPC-A][Final=10][Nnmber=9]"
    for item in str.split("]"):
        print(item.split("=")[1])
        

 python分割出来最后有个空串,导致再次对=分割时报错,正确代码如下:

 


'''
Created on 2011-11-2

@author:dudong0726
'''

if __name__ == '__main__':
    str="[Type=UPC-A][Final=10][Nnmber=9]"
    for item in str.split("]")[0:-1]:
        print(item.split('=')[1])
        
 
好的,以下是使用困惑度指标选择最优参数的 Python 代码示例: 首先,我们需要导入相应的库: ```python import numpy as np from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation from gensim.models import LdaModel from gensim.corpora import Dictionary from gensim.test.utils import common_corpus, common_dictionary from gensim.models.wrappers import DtmModel from gensim.models.wrappers.dtmmodel import DtmParameters from sklearn.model_selection import train_test_split ``` 然后,我们可以使用 `fetch_20newsgroups` 函数加载 20 Newsgroups 数据集,并将其划分为训练集和测试集: ```python data = fetch_20newsgroups(subset='all', shuffle=True, random_state=42) X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42) ``` 接着,我们需要将文本数据转换成词袋向量,以便用于模型训练: ```python vectorizer = CountVectorizer(max_features=5000, stop_words='english') X_train_vec = vectorizer.fit_transform(X_train) X_test_vec = vectorizer.transform(X_test) ``` 然后,我们可以定义一个函数来训练不同的主题模型,并计算在测试集上的困惑度: ```python def train_model(model_type, k_range): perplexity = [] for k in k_range: if model_type == 'pLSA': model = NMF(n_components=k, init='nndsvd', random_state=42) model.fit(X_train_vec) perplexity.append(model.reconstruction_err_) elif model_type == 'LDA': model = LatentDirichletAllocation(n_components=k, learning_method='online', random_state=42) model.fit(X_train_vec) perplexity.append(model.perplexity(X_test_vec)) elif model_type == 'DMM': dictionary = Dictionary(common_corpus) corpus = [dictionary.doc2bow(text) for text in X_train] params = DtmParameters(alpha=0.01, num_topics=k, id2word=dictionary, time_slices=[len(X_train)], initialize_lda=True) model = DtmModel('/path/to/dtm/binary', corpus=corpus, time_slices=[len(X_train)], id2word=dictionary, num_topics=k, params=params) perplexity.append(model.log_perplexity(corpus)) return perplexity ``` 在这个函数中,我们首先定义了一个列表 `perplexity`,用于存储在不同主题数下的困惑度。然后,根据传入的模型类型和主题数范围,分别训练不同的主题模型,并计算在测试集上的困惑度。最后,返回困惑度列表。 接下来,我们可以调用 `train_model` 函数来训练不同的模型,并选择困惑度最小的模型作为最优模型: ```python k_range = range(5, 50, 5) perplexity_plsa = train_model('pLSA', k_range) perplexity_lda = train_model('LDA', k_range) perplexity_dmm = train_model('DMM', k_range) min_perplexity_plsa = np.argmin(perplexity_plsa) min_perplexity_lda = np.argmin(perplexity_lda) min_perplexity_dmm = np.argmin(perplexity_dmm) print('The optimal number of topics for pLSA is', k_range[min_perplexity_plsa]) print('The optimal number of topics for LDA is', k_range[min_perplexity_lda]) print('The optimal number of topics for DMM is', k_range[min_perplexity_dmm]) ``` 在这个示例中,我们尝试了 5 到 50 个主题数,每隔 5 个尝试一次。然后,分别计算了 pLSA、LDA 和 DMM 模型在不同主题数下的困惑度,并选择困惑度最小的模型作为最优模型。最后,打印出最优的主题数。 希望这个示例能够帮到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值