2023-11-14 課程補充資料 Week 10

Demo Project

  1. Logistic regression demo code, 資料來源: LINK
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# file from url as below
# https://www.kaggle.com/datasets/erscodingzone/user-datacsv/
dataset = pd.read_csv("User_Data.csv")

# input, 我們主要是看年齡 薪資 對 購買商品的 推算
x = dataset.iloc[:, [2, 3]].values

# output, 買: 1 或是不買: 0
y = dataset.iloc[:, 4].values

# Splitting The Dataset: Train and Test dataset, 75% for training, 25% testing data
from sklearn.model_selection import train_test_split

xtrain, xtest, ytrain, ytest = train_test_split(
    x, y, test_size=0.25, random_state=0)

from sklearn.preprocessing import StandardScaler

sc_x = StandardScaler()
xtrain = sc_x.fit_transform(xtrain)
xtest = sc_x.transform(xtest)
# scale the age variable value because the salary vs age, the number is too different
print(xtrain[0:10, :])

from sklearn.linear_model import LogisticRegression

#Train The Model
classifier = LogisticRegression(random_state = 0)
classifier.fit(xtrain, ytrain)

# After training the model, it is time to use it to do predictions on testing data.
y_pred = classifier.predict(xtest)

# Confusion Matrix
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(ytest, y_pred)
print ("Confusion Matrix : \n", cm)

from sklearn.metrics import accuracy_score

print("Accuracy : ", accuracy_score(ytest, y_pred))

# Visualizing the performance of our model.
from matplotlib.colors import ListedColormap

X_set, y_set = xtest, ytest
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())

#paint dots
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('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

User_Data.csv, 請到這邊下載 DOWNLOAD

健康相關的 data 也可以拿來試試, 下載連結 DOWNLOAD