0% found this document useful (0 votes)
30 views4 pages

Machine Learning Code Examples

The document provides a collection of Python code snippets for various machine learning techniques, including Linear Regression, KNN, Neural Networks with Keras, Logistic Regression, Decision Trees, Random Forests, KMeans Clustering, PCA, and CNNs. Each section includes the necessary imports, data preparation, model training, and evaluation, demonstrating the implementation of these algorithms using popular libraries like scikit-learn and TensorFlow. The examples cover both supervised and unsupervised learning methods, showcasing their applications on datasets like Iris, MNIST, and Breast Cancer.

Uploaded by

billthanh7777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views4 pages

Machine Learning Code Examples

The document provides a collection of Python code snippets for various machine learning techniques, including Linear Regression, KNN, Neural Networks with Keras, Logistic Regression, Decision Trees, Random Forests, KMeans Clustering, PCA, and CNNs. Each section includes the necessary imports, data preparation, model training, and evaluation, demonstrating the implementation of these algorithms using popular libraries like scikit-learn and TensorFlow. The examples cover both supervised and unsupervised learning methods, showcasing their applications on datasets like Iris, MNIST, and Breast Cancer.

Uploaded by

billthanh7777
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Tổng hợp code Machine Learning

1. Hồi quy tuyến tính (Linear Regression)


from sklearn.linear_model import LinearRegression
import numpy as np

X = [Link]([[1], [2], [3], [4], [5]])


y = [Link]([1.5, 3.5, 3.0, 4.5, 5.5])

model = LinearRegression()
[Link](X, y)

X_test = [Link]([[6]])
y_pred = [Link](X_test)

print("Hệ số:", model.coef_)


print("Intercept:", model.intercept_)
print("Dự đoán tại X=6:", y_pred)

2. KNN - K Nearest Neighbors


from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier

iris = load_iris()
X, y = [Link], [Link]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

knn = KNeighborsClassifier(n_neighbors=3)
[Link](X_train, y_train)

print("Độ chính xác:", [Link](X_test, y_test))

3. Neural Network với Keras (MNIST)


import tensorflow as tf
from [Link] import mnist
from [Link] import Sequential
from [Link] import Dense, Flatten

(x_train, y_train), (x_test, y_test) = mnist.load_data()


x_train, x_test = x_train / 255.0, x_test / 255.0
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])

[Link](optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
[Link](x_train, y_train, epochs=5, validation_data=(x_test, y_test))

loss, acc = [Link](x_test, y_test)


print(f"Độ chính xác: {acc*100:.2f}%")

4. Logistic Regression
from [Link] import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score

data = load_breast_cancer()
X, y = [Link], [Link]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LogisticRegression(max_iter=10000)
[Link](X_train, y_train)

y_pred = [Link](X_test)
print("Độ chính xác:", accuracy_score(y_test, y_pred))

5. Decision Tree
from [Link] import load_iris
from [Link] import DecisionTreeClassifier, export_text

iris = load_iris()
X, y = [Link], [Link]

clf = DecisionTreeClassifier(random_state=0, max_depth=3)


[Link](X, y)

print(export_text(clf, feature_names=iris.feature_names))
6. Random Forest
from [Link] import load_wine
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier

wine = load_wine()
X, y = [Link], [Link]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

clf = RandomForestClassifier(n_estimators=100, random_state=42)


[Link](X_train, y_train)

print("Độ chính xác:", [Link](X_test, y_test))

7. KMeans Clustering
import [Link] as plt
from [Link] import make_blobs
from [Link] import KMeans

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6, random_state=0)

kmeans = KMeans(n_clusters=4)
[Link](X)
y_kmeans = [Link](X)

[Link](X[:, 0], X[:, 1], c=y_kmeans, s=50, cmap='viridis')


[Link](kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red',
marker='X')
[Link]()

8. PCA - Giảm số chiều


from [Link] import PCA
from [Link] import load_digits
import [Link] as plt

digits = load_digits()
X, y = [Link], [Link]

pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

[Link](X_pca[:, 0], X_pca[:, 1], c=y, cmap='tab10', alpha=0.7)


[Link]()
[Link]("Biểu diễn dữ liệu bằng PCA")
[Link]()

9. CNN với Keras (MNIST)


import tensorflow as tf
from [Link] import layers, models
from [Link] import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(-1, 28, 28, 1) / 255.0


x_test = x_test.reshape(-1, 28, 28, 1) / 255.0

model = [Link]([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D((2,2)),
[Link](),
[Link](64, activation='relu'),
[Link](10, activation='softmax')
])

[Link](optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
[Link](x_train, y_train, epochs=5, validation_data=(x_test, y_test))

print("Độ chính xác:", [Link](x_test, y_test)[1])

You might also like