Logistic Regression Define X and Y for Prediction

Mike C ianoda at hotmail.com
Tue Nov 12 10:38:38 EST 2019


Hi All,
I have the below code.
X = df.iloc[:, [4, 403]].values​
y = df.iloc[:, 404].values

Dummy Data looks like:

host                  Mnemonic
12.234.13.6       start
22.22.44.67       something
23.44.44.14       begin

When I define the X and Y values for prediction in the train and test data, should I capture all the columns that has been "OneHotEncoded" (that is all columns with 0 and 1) for the X and Y values???

import numpy                    as np
import pandas                   as pd ​
import os
import matplotlib               as mpl ​
mpl.rcParams['figure.dpi'] = 400      ​
import matplotlib.pyplot        as plt ​
​
# Importing the df​
# Importing the df​
os.chdir('c:\directory\data')                # Location of data files​
df = pd.read_csv('blahblahfile.csv')​
 ​
from sklearn.preprocessing import LabelEncoder​
hostip = LabelEncoder()​
mnemonic = LabelEncoder()​
df['host_encoded'] = hostip.fit_transform(df.reported_hostname)​
df['mnemonic_encoded'] = mnemonic.fit_transform(df.mnemonic)​
​
from sklearn.preprocessing import OneHotEncoder​
hostip_ohe = OneHotEncoder()​
mnemonic_ohe = OneHotEncoder()​
X = hostip_ohe.fit_transform(df.host_encoded.values.reshape(-1,1)).toarray()​
Y = mnemonic_ohe.fit_transform(df.mnemonic_encoded.values.reshape(-1,1)).toarray()​

## Add back X and Y into the original dataframe​
dfOneHot = pd.DataFrame(X, columns = ["host_"+str(int(i)) for i in range(X.shape[1])])​
df = pd.concat([df, dfOneHot], axis=1)​
​
dfOneHot = pd.DataFrame(Y, columns = ["mnemonic_encoded"+str(int(i)) for i in range(Y.shape[1])])​
df = pd.concat([df, dfOneHot], axis=1)​
​
########​ here is where I am not sure if all "host_" and "mnemonic_encoded" values assigned to X and Y
​
X = df.iloc[:, [4, 403]].values​
y = df.iloc[:, 404].values​
​
​
​
# Splitting the dataset into the Training set and Test set​
from sklearn.model_selection import train_test_split​
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)​
​
​
# Feature Scaling​
from sklearn.preprocessing import StandardScaler​
sc = StandardScaler()​
X_train = sc.fit_transform(X_train)​
X_test = sc.transform(X_test)​
​
# Fitting Logistic Regression to the Training set​
from sklearn.linear_model import LogisticRegression​
classifier = LogisticRegression(random_state = 0)​
classifier.fit(X_train, y_train)​
​
# Predicting the Test set results​
y_pred = classifier.predict(X_test)​
​
# Making the Confusion Matrix​
from sklearn.metrics import confusion_matrix​
cm = confusion_matrix(y_test, y_pred)​
​
# Visualising the Training set results​
from matplotlib.colors import ListedColormap​
X_set, y_set = X_train, y_train​
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),​
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))​
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),​
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))​
plt.xlim(X1.min(), X1.max())​
plt.ylim(X2.min(), X2.max())​
for i, j in enumerate(np.unique(y_set)):​
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],​
                c = ListedColormap(('red', 'green'))(i), label = j)​
plt.title('Logistic Regression (Training set)')​
plt.xlabel('Age')​
plt.ylabel('Estimated Salary')​
plt.legend()​
plt.show()​
​
# Visualising the Test set results​
from matplotlib.colors import ListedColormap​
X_set, y_set = X_test, y_test​
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),​
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))​
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),​
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))​
plt.xlim(X1.min(), X1.max())​
plt.ylim(X2.min(), X2.max())​
for i, j in enumerate(np.unique(y_set)):​
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],​
                c = ListedColormap(('red', 'green'))(i), label = j)​
plt.title('Logistic Regression (Test set)')​
plt.xlabel('Host IP')​
plt.ylabel('Mnemonic')​
plt.legend()​
plt.show()


More information about the Python-list mailing list