Я работаю над набором данных, который выглядит следующим образом: а>
На приложенном снимке экрана вы можете видеть, что мой набор данных содержит 16 строк и 12 кортежей, но на самом деле он содержит 521 строку и 12 кортежей.
- 1-я колонка: «Менархе начинается рано».
- 2-я колонка: «Оральная контрацепция».
- 3-й столбец: «Поддержание диеты».
- 4-я колонка: «Пострадавшие от рака молочной железы».
- 5-я колонка: «Пострадал от рака шейки матки?»
- 6-я колонка: «Рак в семье?»
- 7-я колонка: «Образование?»
- 8-я колонка: «Возраст мужа».
- 9-я колонка: «Возраст окончания менопаузы?»
- 10-я колонка: «Пища содержит много жира?»
- 11-я колонка: «Аборт?»
- 12-я колонка: «Затронуты раком яичников?».
Здесь все столбцы содержат категориальные переменные. Поэтому я предварительно обработал набор данных с помощью LabelEncoder и OneHotEncoder и, чтобы избежать ловушки фиктивных переменных, я удалил 1-й столбец фиктивных переменных, который создает более 2 столбцов.
Затем я разделил набор данных на 2 части с test_size = 0,25 и random_state = 18, затем я подогнал X_train и y_train к MultinomialNB() и получил показатель точности 0,7938931297709924.
Затем я построил несколько кривых обучения, которые выглядят следующим образом: и этот < img src="https://i.stack.imgur.com/E1miw.png" alt="this one"> но, что наиболее важно, моя модель дает значение для R-квадрата: 0,557 и Adj. R-квадрат: 0,543, что, я полагаю, не очень хорошо.
Вот моя матрица путаницы
Я хочу, чтобы значения r в квадрате и adj r в квадрате были где-то около 1, но я не понимаю, как я могу сделать это эффективно, поскольку я новичок в этой области и раньше не работал с каким-либо набором данных, который содержит все категориальные переменные и не содержит значений, пожалуйста, помогите мне с этим, чтобы сделать мою модель лучше, используя алгоритм наивного Байеса, а также, если вы обнаружите какую-либо ошибку в моей модели, пожалуйста, дайте мне знать и помогите и Также, пожалуйста, помогите мне, предоставив ресурсы и учебные пособия + примеры кода для построения графика визуализации данных из моей модели. Вот мой код для этого проекта:
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
dataset = pd.read_csv('RiskFactor.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 11].values
#dummy_x = dataset.iloc[:, [0,6,7,8]].values
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
label_x = LabelEncoder()
X[:,0] = label_x.fit_transform(X[:,0] ) #Menarche start early
label_x = LabelEncoder()
X[:,1] = label_x.fit_transform(X[:,1] )
label_x = LabelEncoder()
X[:,2] = label_x.fit_transform(X[:,2] )
label_x = LabelEncoder()
X[:,3] = label_x.fit_transform(X[:,3] )
label_x = LabelEncoder()
X[:,4] = label_x.fit_transform(X[:,4] )
label_x = LabelEncoder()
X[:,5] = label_x.fit_transform(X[:,5] )
label_x = LabelEncoder()
X[:,6] = label_x.fit_transform(X[:,6] ) #Education
label_x = LabelEncoder()
X[:,7] = label_x.fit_transform(X[:,7] ) #Age of Husband
label_x = LabelEncoder()
X[:,8] = label_x.fit_transform(X[:,8] ) #Menopause End age?
label_x = LabelEncoder()
X[:,9] = label_x.fit_transform(X[:,9] )
label_x = LabelEncoder()
X[:,10] = label_x.fit_transform(X[:,10] )
onehotencoder = OneHotEncoder(categorical_features = "all")
X = onehotencoder.fit_transform(X).toarray()
#avoiding dummy variable trap by removing extra columns
X = X[: ,[1,2,3,4,5,6,7,8,9,10,11,12,14,15,17,18,20,21,22,23,24,25,26]]
# Encoding the Dependent Variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)
# Splitting the dataset into the Training set and Test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =0.25,
random_state = 18)
from sklearn.naive_bayes import GaussianNB,BernoulliNB,MultinomialNB
classifier = MultinomialNB()
classifier.fit(X_train, y_train)
print(classifier)
y_expect = y_test
#predicting the test set result
y_pred = classifier.predict(X_test)
#Making the Confusion Matrix
from sklearn.metrics import confusion_matrix,accuracy_score
cm = confusion_matrix (y_test, y_pred)
print(accuracy_score(y_expect,y_pred))
# finding P value from statsmodels
import statsmodels.formula.api as sm
regressor_OLS = sm.OLS(endog=y,exog = X).fit()
regressor_OLS.summary()
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
"""
Generate a simple plot of the test and training learning curve.
Parameters
----------
estimator : object type that implements the "fit" and "predict" methods
An object of that type which is cloned for each validation.
title : string
Title for the chart.
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape (n_samples) or (n_samples, n_features), optional
Target relative to X for classification or regression;
None for unsupervised learning.
ylim : tuple, shape (ymin, ymax), optional
Defines minimum and maximum yvalues plotted.
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if ``y`` is binary or multiclass,
:param train_sizes:
:class:`StratifiedKFold` used. If the estimator is not a classifier
or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validators that can be used here.
n_jobs : integer, optional
Number of jobs to run in parallel (default 1).
"""
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
plt.legend(loc="best")
return plt
estimator = MultinomialNB()
title = "Learning Curves (Naive Bayes classifier ALGORITHM)"
# Cross validation with 100 iterations to get smoother mean test and train
# score curves, each time with 20% data randomly selected as a validation
#set.
cv = ShuffleSplit(n_splits=100, test_size=0.25, random_state=17)
#cv = None
plot_learning_curve(estimator, title, X, y, ylim=(0.7, 1.01), cv=cv,
n_jobs=1)
plt.show()
X[: ,[1,2,3,4,5,6,7,8,9,10,11,12,14,15,17,18,20,21,22,23,24,25,26]]
? Вы взяли столбцы с 1 по 26 в своих характеристиках? Откуда вы знаете, что это те столбцы, из которых выпадает ловушка фиктивной переменной? - person Vivek Kumar   schedule 03.08.2018