实验主要内容:
现有两类数据集:第一类是与、或、非、异或四个数据集,第二类是MNIST手写体数字图片数据集。请分别用教材《机器学习》(周志华著)第3章中的线性模型(任务一,满分20分)、第4章中的决策树(任务二,满分20分)、以及第5章中的感知机(任务三,满分20分)和双隐层全连接神经网络(任务四,满分25分)分别对上述两类数据集进行分类并给出精度分析和可视化结果;以及尝试采用具有更多隐藏层的全连接神经网络对第二类数据集进行分类,并给出精度分析和可视化结果(任务五,满分10分);最后需要对比上述五种任务中的不同模型得到的精度差别,并分析可能的原因,以及由此受到的启发(任务六,满分5分)。
报告内容要求:
(1)编程采用MATLAB或Python,代码的所有行均需要有注释。代码单独提交,多个代码需要组织合理,环境配置要清楚指明。
(2)任务一到任务四的核心算法部分不可以调用库函数,否则最多得相应满分的60%。
(3)任务一到任务五都可能在编程正确的情况下依然效果不理想,请提出相应的改进方案。在改进时,任务一到任务四的模型类型不能改变,任务五的模型类型可以改变。
(4)任务一和任务二可以只采用一种算法进行实验,不要求采用所有相关算法。
(5)报告中可以粘贴代码,但是尽量控制粘贴的代码篇幅,代码的分析和评价以实际提交的代码为主。
我现在写,望采纳!!点击该回答右侧的“采纳”按钮即可采纳!!
这是一个比较全面的任务,需要用到 Python 中的不同机器学习库和模型来完成。
对于第一类数据集,我们可以使用 NumPy 库来生成数据,并使用 scikit-learn 中的线性模型、决策树、感知机和双隐层全连接神经网络模型来进行分类。我们可以使用 scikit-learn 中的 train_test_split 函数将数据分成训练集和测试集,然后使用不同的模型训练数据并预测结果。最后,我们可以使用 scikit-learn 中的 classification_report 函数来计算各种指标,例如精度、召回率和 F1 分数,以及使用 matplotlib 库进行可视化。
对于第二类数据集,我们可以使用 TensorFlow 库中的 MNIST 数据集加载器来载入数据。然后使用 TensorFlow 中的全连接神经网络模型对数据进行分类。我们可以使用 TensorFlow 中的数据划分器将数据划分为训练集和测试集,然后使用模型训练数据并预测结果。最后,我们可以使用 TensorFlow 中的 evaluate 函数来计算模型的准确率,并使用 matplotlib 库进行可视化。
在尝试使用具有更多隐藏层的全连接神经网络时,我们可以通过更改模型的结构来增加隐藏层的数量。具体来说,我们可以使用 TensorFlow 中的 Keras API 来构建全连接神经网络模型,并使用 add 函数来增加更多的隐藏层。然后我们可以使用 TensorFlow 中的 compile 函数来配置模型的优化器和损失函数,并使用 fit 函数来训练模型。最后,我们可以使用 evaluate 函数来计算模型的准确率,并使用 matplotlib 库进行可视化。
在比较不同模型的精度差异时,我们可以使用 classification_report 函数或 evaluate 函数计算出各种指标,并使用 matplotlib 库进行可视化。我们可以对比这些指标,来分析不同模型的优劣。此外,我们还可以考虑因素,例如模型的复杂度和训练数据的质量,来分析可能的原因。
下面是一个示例代码,它使用 NumPy 和 scikit-learn 库来处理第一类数据集,并使用线性模型、决策树、感知机和双隐层全连接神经网络对数据进行分类:
(1)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
# 生成数据
X = np.random.randint(2, size=(1000, 4))
y = np.logical_and(X[:, 0], X[:, 1])
# 将数据划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 定义模型
models = [
LogisticRegression(),
DecisionTreeClassifier(),
MLPClassifier(hidden_layer_sizes=(2,))
]
# 分别训练模型并计算准确率
for model in models:
# 训练模型
model.fit(X_train, y_train)
# 计算准确率
accuracy = model.score(X_test, y_test)
print(f'{model.__class__.__name__}的准确率为:{accuracy:.2f}')
你还可以使用 classification_report 函数计算更多的指标,例如精度、召回率和 F1 分数。
for model in models:
# 训练模型
model.fit(X_train, y_train)
# 预测测测试集结果
y_pred = model.predict(X_test)
# 计算指标
report = classification_report(y_test, y_pred)
print(f'{model.class.name}的指标:\n{report}')
如果你想要使用 matplotlib 库进行可视化,你可以使用 matplotlib 库中的 plot 函数绘制散点图或直方图来展示数据分布情况,或者使用 matplotlib 库中的 scatter 函数绘制散点图来展示模型的预测结果。
例如,下面是使用 matplotlib 库绘制散点图的示例代码:
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.title('数据分布情况')
plt.xlabel('特征1')
plt.ylabel('特征2')
plt.show()
最后,你可以对比各种模型的精度差异,分析可能的原因,并根据自己的目标来选择最优的模型。
下面是一个使用 TensorFlow 和 Keras API 对现有的与、或、非、异或数据集进行分类并给出精度分析和可视化结果的示例代码:
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
#生成数据
X = np.random.randint(2, size=(1000, 4))
y = np.logical_and(X[:, 0], X[:, 1])
#将数据划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
#使用 Keras API 构建双隐层全连接神经网络模型
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(4,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
#配置模型的优化器和损失函数
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
#训练模型
history = model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test))
#计算模型的准确率
accuracy = model.evaluate(X_test, y_test)[1]
print(f'模型的准确率为:{accuracy:.2f}')
#使用 matplotlib 库绘制训练损失和验证损失
plt.plot(history.history['loss'], label='train loss')
plt.plot(history.history['val_loss'], label='validation loss')
plt.legend()
plt.show()
#使用 matplotlib 库绘制训练精度和验证精度
plt.plot(history.history['accuracy'], label='train accuracy')
plt.plot(history.history['val_accuracy'], label='validation accuracy')
plt.legend()
plt.show()
(2)下面是一个示例代码,它使用 TensorFlow 和 matplotlib 库来处理 MNIST 数据集,并使用线性模型、决策树、感知机和双隐层全连接神经网络对数据进行分类:
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neural_network import MLPClassifier
import matplotlib.pyplot as plt
# 加载数据
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
#将图像数据转换为一维向量
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)
#定义模型
models = [
LogisticRegression(),
DecisionTreeClassifier(),
MLPClassifier(hidden_layer_sizes=(50,))
]
#分别训练模型并计算准确率
for model in models:
# 训练模型
model.fit(X_train, y_train)
# 计算准确率
accuracy = model.score(X_test, y_test)
print(f'{model.class.name}的准确率为:{accuracy:.2f}')
#使用 matplotlib 库进行可视化
for i, model in enumerate(models):
# 预测测试数据
y_pred = model.predict(X_test)
# 绘制前 25 个测试图像和预测结果
plt.figure(figsize=(10, 5))
for j in range(25):
plt.subplot(5, 5, j+1)
plt.imshow(X_test[j].reshape(28, 28), cmap='gray')
plt.title(f'Predicted: {y_pred[j]}')
plt.axis('off')
plt.suptitle(f'{model.class.name}')
plt.show()
注意,在上述代码中,我们使用了 scikit-learn 中的线性模型、决策树和感知机模型来处理 MNIST 数据集。这些模型可能不适用于图像数据,因此可能不会得到很好的结果。此外,我们也可以使用 TensorFlow 中的 Keras API 来构建全连接神经网络模型,并使用 fit 函数来训练模型。最后,我们可以使用 evaluate 函数来计算模型的准确率,并使用 matplotlib 库进行可视化。
下面是一个使用 TensorFlow 和 Keras API 构建双隐层全连接神经网络模型并训练 MNIST 数据集的示例代码:
import tensorflow as tf
from tensorflow import keras
#加载数据
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
#将图像数据转换为一维向量
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.reshape(X_test.shape[0], -1)
#归一化数据
X_train = X_train / 255.0
X_test = X_test / 255.0
#使用 Keras API 构建双隐层全连接神经网络模型
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(784,)),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
#配置模型的优化器和损失函数
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])训练模型
model.fit(X_train, y_train, epochs=5)
#评估模型
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
print(f'测试集的准确率:{test_acc:.2f}')
#使用 matplotlib 库进行可视化
y_pred = model.predict(X_test)
#绘制前 25 个测试图像和预测结果
plt.figure(figsize=(10, 5))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.imshow(X_test[i].reshape(28, 28), cmap='gray')
plt.title(f'Predicted: {np.argmax(y_pred[i])}')
plt.axis('off')
plt.show()
注意,在上述代码中,我们使用了 TensorFlow 和 Keras API 来构建双隐层全连接神经网络模型,并使用 fit 函数来训练模型。然后使用 evaluate 函数来计算模型的准确率,并使用 matplotlib 库进行可视化。
这个实验的目标是使用不同的机器学习模型,对两个数据集进行分类,并给出精度分析和可视化结果。需要使用线性模型、决策树、感知机和双隐层全连接神经网络来完成这个任务,并使用具有更多隐藏层的全连接神经网络来可以试试分类第二个数据集。需要对这五个任务中的不同模型的精度进行比较,并分析可能的原因。
为了开始这个实验,需要先准备好环境,包括安装Python和相应的机器学习库(例如scikit-learn)。然后需要加载数据集并进行预处理,包括分割训练集和测试集、归一化数据等。
接下来,可以使用线性模型、决策树、感知机和双隐层全连接神经网络来训练模型,并使用测试集来评估模型的精度。可以使用可视化工具来展示模型的分类结果。可以使用具有更多隐藏层的全连接神经网络来可以试试分类第二个数据集,并给出精度分析和可视化结果。可以对五个任务中的不同模型的精度进行比较,并分析可能的原因。
在分析精度差别时,需要考虑每个模型的优缺点,以及在不同数据集上的表现。例如线性模型通常对小型数据集有很好的表现,但对于大型数据集,它的表现可能会差些。决策树通常能够很好地处理高维度数据,但可能会出现过拟合的情况。感知机是一种简单的模型,它的训练速度很快,但可能不如其他模型的精度高。双隐层全连接神经网络就具有很高的准确率,但训练时间可能较长。
在分析原因时,还需要考虑模型的超参数设置是否合适,以及数据集的属性是否适合每个模型。假如数据集中存在很多噪声或不相关的特征,那么决策树可能会出现过拟合的情况。另外如果数据集的类别不平衡(即某些类别的数据量远远大于其他类别),那么某些模型的表现可能会受到影响。
可以先需要安装Python和相应的机器学习库(例如scikit-learn)。
其次需要加载数据集并进行预处理。可以使用pandas库来读取数据集文件,然后使用train_test_split函数来将数据集分割成训练集和测试集。还可以使用sklearn.preprocessing库中的StandardScaler函数来将数据进行归一化处理。
接下来,可以开始实现机器学习模型。对于任务一,可以使用线性回归来实现线性模型。可以使用numpy库来计算训练数据的最小二乘法回归系数,然后使用这些系数来对新数据进行预测。对于任务二,可以使用决策树算法来实现决策树模型。可以使用递归函数来构建决策树,并使用决策树来对数据进行分类。对于任务三,可以使用感知机算法来实现感知机模型。可以使用随机梯度下降算法来训练感知机,然后使用感知机来对数据进行分类。对于任务四,可以使用多层感知机算法来实现双隐层全连接神经网络。可以使用向前传播算法和反向传播算法来训练神经网络,并使用训练好的神经网络来对数据进行分类。
在训练完每个模型后,需要使用测试集来评估模型的精度。可以使用准确率、召回率、F1分数等指标来评估模型的表现。
线性模型:可以使用最小二乘法来计算训练数据的回归系数。需要自己实现计算损失函数和梯度的代码。还需要自己实现预测函数,使用回归系数对新数据进行预测。
决策树:可以使用信息熵或基尼指数来选择最优的分裂特征。需要自己实现决策树的构建函数,使用递归函数来构建决策树。还需要自己实现分类函数,使用决策树来对新数据进行分类。
感知机:可以使用随机梯度下降算法来训练感知机。需要自己实现计算损失函数和梯度的代码。还需要自己实现预测函数,使用训练好的感知机来对新数据进行预测。
示例代码仅供参考:
线性模型:
import numpy as np
def fit_linear_model(X, y):
# Add a column of ones to X
X = np.hstack([np.ones((X.shape[0], 1)), X])
# Compute the least squares solution
beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
return beta
def predict(X, beta):
# Add a column of ones to X
X = np.hstack([np.ones((X.shape[0], 1)), X])
y_pred = X.dot(beta)
return y_pred
def mean_squared_error(y_true, y_pred):
mse = np.mean((y_true - y_pred)**2)
return mse
决策树:
import numpy as np
class DecisionTree:
def __init__(self, max_depth=5):
self.max_depth = max_depth
def fit(self, X, y):
self.num_classes = np.unique(y).size
self.root = self._build_tree(X, y)
def _build_tree(self, X, y, depth=0):
num_samples, num_features = X.shape
label_counts = np.bincount(y)
# Check if we should stop splitting
if depth >= self.max_depth or num_samples <= 1 or np.unique(y).size == 1:
return DecisionTreeLeaf(y)
# Find the best feature to split on
best_feature = None
best_threshold = None
max_gain = -1
for feature_idx in range(num_features):
thresholds, gains = self._compute_thresholds_and_gains(X[:, feature_idx], y)
if gains[np.argmax(gains)] > max_gain:
best_feature = feature_idx
best_threshold = thresholds[np.argmax(gains)]
max_gain = gains[np.argmax(gains)]
# Split the data and build the sub-trees
left_mask = X[:, best_feature] < best_threshold
right_mask = ~left_mask
left_X = X[left_mask]
right_X = X[right_mask]
left_y = y[left_mask]
right_y = y[right_mask]
left_tree = self._build_tree(left_X, left_y, depth=depth+1)
right_tree = self._build_tree(right_X, right_y, depth=depth+1)
return DecisionTreeNode(best_feature, best_threshold, left_tree, right_tree)
def _compute_thresholds_and_gains(self, X, y):
thresholds = []
gains = []
# Calculate the entropy of the current data
labels, counts = np.unique(y, return_counts=True)
current_entropy = self._calculate_entropy(counts)
# Find the unique values in X and sort them
unique_values = np.unique(X)
unique_values.sort()
# Calculate the thresholds and gains for all possible splits
for i in range(len(unique_values) - 1):
threshold = (unique_values[i] + unique_values[i + 1]) / 2
left_mask = X < threshold
right_mask = ~left_mask
left_y = y[left_mask]
right_y = y[right_mask]
labels, left_counts = np.unique(left_y, return_counts=True)
left_entropy = self._calculate_entropy(left_counts)
labels, right_counts = np.unique(right_y, return_counts=True)
right_entropy = self._calculate_entropy(right_counts)
gain = current_entropy - (left_entropy * len(left_y) + right_entropy * len(right_y)) / len(y)
thresholds.append(threshold)
gains.append(gain)
return thresholds, gains
感知机:
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1, max_iter=1000):
self.learning_rate = learning_rate
self.max_iter = max_iter
def fit(self, X, y):
num_samples, num_features = X.shape
self.weights = np.zeros(num_features)
self.bias = 0
for i in range(self.max_iter):
for j in range(num_samples):
y_pred = self.predict(X[j])
if y_pred != y[j]:
self.weights += self.learning_rate * y[j] * X[j]
self.bias += self.learning_rate * y[j]
def predict(self, x):
y_pred = np.sign(np.dot(self.weights, x) + self.bias)
return y_pred
双隐层全连接神经网络:
import numpy as np
class NeuralNet:
def __init__(self, hidden_size=10, learning_rate=0.1, max_iter=1000):
self.hidden_size = hidden_size
self.learning_rate = learning_rate
self.max_iter = max_iter
def fit(self, X, y):
num_samples, num_features = X.shape
num_classes = np.unique(y).size
# Initialize weights and biases
self.W1 = np.random.randn(num_features, self.hidden_size)
self.b1 = np.zeros(self.hidden_size)
self.W2 = np.random.randn(self.hidden_size, num_classes)
self.b2 = np.zeros(num_classes)
# Perform backpropagation
for i in range(self.max_iter):
# Forward pass
Z1 = X.dot(self.W1) + self.b1
A1 = self._relu(Z1)
Z2 = A1.dot(self.W2) + self.b2
A2 = self._softmax(Z2)
# Backward pass
cost = self._cross_entropy(A2, y)
dZ2 = A2 - y
dW2 = A1.T.dot(dZ2)
db2 = np.sum(dZ2, axis=0)
dA1 = dZ2.dot(self.W2.T)
dZ1 = dA1 * self._relu_derivative(Z1)
dW1 = X.T.dot(dZ1)
db1 = np.sum(dZ1, axis=0)
# Update weights and biases
self.W1 -= self.learning_rate * dW1
self.b1 -= self.learning_rate *db1
self.W2 -= self.learning_rate * dW2
self.b2 -= self.learning_rate * db2
def predict(self, X):
Z1 = X.dot(self.W1) + self.b1
A1 = self._relu(Z1)
Z2 = A1.dot(self.W2) + self.b2
A2 = self._softmax(Z2)
return A2
def _relu(self, x):
return np.maximum(0, x)
def _softmax(self, x):
exp_x = np.exp(x)
return exp_x / np.sum(exp_x, axis=1, keepdims=True)
def _cross_entropy(self, y_pred, y_true):
m = y_true.shape[0]
log_likelihood = -np.log(y_pred[range(m), y_true])
loss = np.sum(log_likelihood) / m
return loss
def _relu_derivative(self, x):
x[x<=0] = 0
x[x>0] = 1
return x
仅供参考,望采纳,谢谢。