我在 Scikit-Learn 中使用 Logistic 回归模型(特别是LogisticRegressionCV)。当我使用默认tol值(即1e-4)并用不同的random_state值测试模型时,特征系数波动不大。至少,我可以看到哪些功能是重要的。
然而,当我设置较高的tol值(例如2.3)时,每次运行模型时,特征系数都会大幅波动。当在一次试验中特征 A 的系数为 -0.9 时,在下一次试验中它可能为 0.4。
这让我认为正确(或有利)的tol值应该是结果更加一致的值。
以下是我的代码的相关部分:
classifier = LogisticRegressionCV(penalty='l1', class_weight='balanced',
#tol=2.2,
solver='liblinear')
Run Code Online (Sandbox Code Playgroud)
我想知道是否有指南可以确定适当的tol值。
我想知道对数据框列(熊猫)的每个列表进行排序。例如:
id values
------------------------
1 ['cdf','abc','efg']
2 ['xyz' ,'rsy','abc']
Run Code Online (Sandbox Code Playgroud)
预期的 :
id values
------------------------
1 ['abc','cdf','efg']
2 ['abc' ,'rsy','xyz']
Run Code Online (Sandbox Code Playgroud)
谢谢:我也想知道是否存在逗号分隔的字符串而不是列表。
您知道scikit-learn中的模型是自动使用多线程还是仅使用顺序指令?
谢谢
我正在尝试在我的一个数据集上创建随机森林回归模型。我还需要找到每个变量的重要性顺序以及它们的名称。我尝试了几件事,但无法实现我想要的。以下是我在Boston Housing数据集中尝试的示例代码:
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
boston = load_boston()
rf=RandomForestRegressor(max_depth=50)
idx=range(len(boston.target))
np.random.shuffle(idx)
rf.fit(boston.data[:500], boston.target[:500])
instance=boston.data[[0,5, 10]]
print rf.predict(instance[0])
print rf.predict(instance[1])
print rf.predict(instance[2])
important_features=[]
for x,i in enumerate(rf.feature_importances_):
important_features.append(str(x))
print 'Most important features:',', '.join(important_features)
Run Code Online (Sandbox Code Playgroud)
最重要的功能:0、1、2、3、4、5、6、7、8、9、10、11、12
如果我打印此:
impor = rf.feature_importances_
impor
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
array([ 3.45665230e-02, 4.58687594e-04, 5.45376404e-03,
3.33388828e-04, 2.90936201e-02, 4.15908448e-01,
1.04131089e-02, 7.26451301e-02, 3.51628079e-03,
1.20860975e-02, 1.40417760e-02, 8.97546838e-03,
3.92507707e-01])
Run Code Online (Sandbox Code Playgroud)
我需要获取与这些值关联的名称,然后从这些功能中选择前n个。
这个问题与机器学习有关。我用灰度图像的值填充数组。
ben = io.ImageCollection('./Ben_bw.png')[0]
ben = np.array(ben)#array of all pixels
Run Code Online (Sandbox Code Playgroud)
现在我用以下方法展平数组:
ben_flat = ben.reshape((1, -1))
Run Code Online (Sandbox Code Playgroud)
当我打印 ben_flat.shape 然后我得到一个非零的 (1, 10304) 数组
然后当我尝试使用 PCA 并拟合数组时:
pca = PCA(n_components=200)
ben_reduced = pca.fit(ben_flat)
Run Code Online (Sandbox Code Playgroud)
当我适合数组时,我收到一个错误:
RuntimeWarning: invalid value encountered in true_divide
Run Code Online (Sandbox Code Playgroud)
据我所知,某处有一个零分频器。但我无法理解它在哪里或它如何结束。
我正在尝试找到应用于众所周知的威斯康星癌症数据集(569个样本,31个特征+目标)的乳腺癌样本分类的最佳模型神经网络模型.我正在使用sklearn 0.18.1.到目前为止我还没有使用Normalization.当我解决这个问题时,我会添加它.
# some init code omitted
X_train, X_test, y_train, y_test = train_test_split(X, y)
Run Code Online (Sandbox Code Playgroud)
为GridSearchCV定义params NN params
tuned_params = [{'solver': ['sgd'], 'learning_rate': ['constant'], "learning_rate_init" : [0.001, 0.01, 0.05, 0.1]},
{"learning_rate_init" : [0.001, 0.01, 0.05, 0.1]}]
Run Code Online (Sandbox Code Playgroud)
CV方法和模型
cv_method = KFold(n_splits=4, shuffle=True)
model = MLPClassifier()
Run Code Online (Sandbox Code Playgroud)
应用网格
grid = GridSearchCV(estimator=model, param_grid=tuned_params, cv=cv_method, scoring='accuracy')
grid.fit(X_train, y_train)
y_pred = grid.predict(X_test)
Run Code Online (Sandbox Code Playgroud)
如果我跑:
print(grid.best_score_)
print(accuracy_score(y_test, y_pred))
Run Code Online (Sandbox Code Playgroud)
结果为0.746478873239和0.902097902098
根据文档"best_score_:float,best_estimator得分左侧数据".我认为在运行8种不同配置的那些中获得的最佳准确度是在tuned_params中指定的次数,由KFold指定的次数,在左边的数据中由KFold指定.我对吗?
还有一个问题.有没有一种方法可以找到在train_test_split中使用的最佳测试数据大小,默认为0.25?
非常感谢
参考
无法使用scikit-learn 0.19.1导入sklearn.qda和sklearn.lda
我得到:ImportError:没有名为'sklearn.qda'的模块ImportError:没有名为'sklearn.lda'的模块
更新:
import sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
Run Code Online (Sandbox Code Playgroud)
得到:
ImportError: No module named 'sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis'; 'sklearn.discriminant_analysis' is not a package
Run Code Online (Sandbox Code Playgroud)
import sklearn.discriminant_analysis.LinearDiscriminantAnalysis给出:
ImportError: No module named 'sklearn.discriminant_analysis.LinearDiscriminantAnalysis'; 'sklearn.discriminant_analysis' is not a package
Run Code Online (Sandbox Code Playgroud) 这是一个 sample.csv 文件,其中我有 3 列 int 类型数据。
它在预测一列数据时工作正常,
但在预测两列 col2 和 col3 时显示错误。
col1,col2,col3
1,5,1
3,6,5
8,5,2
6,4,2
6,9,5
import pandas as pd
data = pd.read_csv('sample.csv')
input = data
objective = data[["col2","col3"]]
xtr,xtst,ytr,ytst = train_test_split(input,objective,test_size=0.25,
train_size=0.75,random_state=4)
from sklearn.svm import SVR
classifier = SVR()
classifier.fit(xtr,ytr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\svm\base.py", line 149, in fit
X, y = check_X_y(X, y, dtype=np.float64, order='C', accept_sparse='csr')
File "C:\Users\User\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 547, in check_X_y
y = column_or_1d(y, warn=True)
File …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用分类的决策树根据某些参数来识别两个类(重命名为0和1)。我使用数据集训练它,然后在“测试数据集”上运行它。当我尝试计算测试数据集中每个数据点的概率时,它仅返回0或1。我想知道是什么问题。
这是示例代码:
clf=tree.DecisionTreeClassifier(random_state=0)
trained=clf.fit(data,identifier) # training data where identifier is 0 or 1
predict=trained.predict(test_data)
结果是:
In [9]: predict
Out[9]:
array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0])
In [10]: trained.predict_proba(test_data)[:,1]
Out[10]:
array([ 0., 0., 0., 0., …Run Code Online (Sandbox Code Playgroud) 任何人都可以检查以下代码的问题吗?我在构建模型的任何步骤中都错了吗?我已经在参数中添加了两个“clf__”。
clf=RandomForestClassifier()
pca = PCA()
pca_clf = make_pipeline(pca, clf)
kfold = KFold(n_splits=10, random_state=22)
parameters = {'clf__n_estimators': [4, 6, 9], 'clf__max_features': ['log2',
'sqrt','auto'],'clf__criterion': ['entropy', 'gini'], 'clf__max_depth': [2,
3, 5, 10], 'clf__min_samples_split': [2, 3, 5],
'clf__min_samples_leaf': [1,5,8] }
grid_RF=GridSearchCV(pca_clf,param_grid=parameters,
scoring='accuracy',cv=kfold)
grid_RF = grid_RF.fit(X_train, y_train)
clf = grid_RF.best_estimator_
clf.fit(X_train, y_train)
grid_RF.best_score_
cv_result = cross_val_score(clf,X_train,y_train, cv = kfold,scoring =
"accuracy")
cv_result.mean()
Run Code Online (Sandbox Code Playgroud) 在sklearn中,可以定义串行管道,以使管道的所有连续部分都获得超参数的最佳组合。串行管道可以实现如下:
from sklearn.svm import SVC
from sklearn import decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
digits = datasets.load_digits()
X_train = digits.data
y_train = digits.target
#Use Principal Component Analysis to reduce dimensionality
# and improve generalization
pca = decomposition.PCA()
# Use a linear SVC
svm = SVC()
# Combine PCA and SVC to a pipeline
pipe = Pipeline(steps=[('pca', pca), ('svm', svm)])
# Check the training time for the SVC
n_components = [20, 40, 64]
params_grid = {
'svm__C': …Run Code Online (Sandbox Code Playgroud) python ×10
scikit-learn ×9
python-3.x ×4
pandas ×3
grid-search ×2
pca ×2
arrays ×1
dataframe ×1
pipeline ×1
roc ×1