机器学习 程序题

本文介绍了K-近邻算法在手写数据集上的应用,通过sklearn库实现了KNN分类器,并进行了8:2的数据划分,计算了准确率。同时,展示了线性回归(正规方程)在波士顿房价预测中的运用,以及逻辑回归在癌症分类预测中的应用。此外,还使用KMeans聚类算法对手顾客数据进行分析,完成了顾客群体的划分。
摘要由CSDN通过智能技术生成

代码如下开始背

1、已知训练集数据的特征值如下:

题干

raw_data_x=[[3.3144558 , 2.33542461],
       [3.75497175, 1.93856648],
       [1.38327539, 3.38724496],
       [3.09203999, 4.47090056],
       [2.58593831, 2.13055653],
       [7.41206251, 4.80305318],
       [5.912852  , 3.72918089],
       [9.21547627, 2.8132231 ],
       [7.36039738, 3.35043406],
       [7.13698009, 0.40130301]]

训练集的目标值:raw_data_y=[0,0,0,0,0,1,1,1,1,1]
请使用K-近邻算法(k值取5)预测新的样本点[8.093607318,3.365731514]的目标值?

import numpy as np
#定义特征值
raw_data_x=[[3.3144558 , 2.33542461],
       [3.75497175, 1.93856648],
       [1.38327539, 3.38724496],
       [3.09203999, 4.47090056],
       [2.58593831, 2.13055653],
       [7.41206251, 4.80305318],
       [5.912852  , 3.72918089],
       [9.21547627, 2.8132231 ],
       [7.36039738, 3.35043406],
       [7.13698009, 0.40130301]]
#定义目标值
raw_data_y=[0,0,0,0,0,1,1,1,1,1]
#将训练集和测试集转换成Numpy数组类型
X_train = np.array(raw_data_x)
y_train = np.array(raw_data_y)
x=np.array([8.093607318,3.365731514])
#代码实现如下(可直接使用sklearn创建knn算法的分类器)(以下都记)
#导入模型方法
A
#创建knn算法的分类器实例
B
#拟合训练数据
C
#将样本维度变为二维
D
#利用knn算法进行预测
E
#得出预测结果
F

代码

A、 from sklearn.neighbors import KNeighborsClassifier 
B、 knn_classifier = KNeighborsClassifier(n_neighbors=5) 
C、 knn_classifier.fit(X_train,y_train) 
D、 x1 = x.reshape(1, -1) 
E、 y_predict = knn_classifier.predict(x1) 
F、 y_predict[0] 

2、请编程实现手写数据集的K-近邻算法实现过程。要求: k值取6,按8:2划分训练集和测试集,最后给出准确率。

题干

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn import datasets
#加载手写数字集图片数据
digits = datasets.load_digits()
#查看该数据集的描述信息
digits.DESCR
#查看数据集的shape
X = digits.data
X.shape
y = digits.target
y.shape
#取出某个数据集绘制图像:
some_digit = X[666]
y[666]
#将数据集变为(8,8)的二维数据
some_digit_image = some_digit.reshape(8,8)
#绘制二维图片
plt.imshow(some_digit_image,cmap=matplotlib.cm.binary)
plt.show()

请利用knn算法进行分类预测,重点:可直接使用sklearn创建knn算法的分类器,k值取6,按8:2划分训练集和测试集,最后给出准确率。

#代码实现如下
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
#划分数据集,测试集占20%
A
#生产knn模型实例
B
#训练knn模型
C
#预测测试集
D
#导入准确率模型
E
#计算准确率
F

代码

A、 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2) 
B、 knn_classifier = KNeighborsClassifier(n_neighbors=6) 
C、 knn_classifier.fit(X_train,y_train) 
D、 y_predict = knn_classifier.predict(X_test) 
E、 from sklearn.metrics import accuracy_score 
F、 knn_classifier.score(X_test,y_test) 

3、请用线性回归(正规方程)算法编程实现波士顿房价的预测过程。

题干

要求: k值取6,按8:2划分训练集和测试集,最后给出准确率。

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import SGDRegressor
from sklearn.linear_model import LinearRegression
# 1.获取数据
data = load_boston()
# 2.数据集划分
x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, random_state=22)
# 3.特征工程-标准化
#生产标准化对象
A
#训练集标准化
B
#测试集标准化
C
# 4.机器学习-线性回归(正规方程)
#生产线性方程模型对象
D
#训练模型
E
# 5.模型评估
# 5.1 获取系数等值
#预测
F
print("预测值为:\n", y_predict)
print("模型中的系数为:\n", estimator.coef_)
print("模型中的偏置为:\n", estimator.intercept_)
# 5.2 评价
# 均方误差
error = mean_squared_error(y_test, y_predict)
print("误差为:\n", error)

代码

A、 transfer = StandardScaler() 
B、 x_train = transfer.fit_transform(x_train) 
C、 x_test = transfer.transform(x_test) 
D、 estimator = LinearRegression() 
E、 estimator.fit(x_train, y_train) 
F、 y_predict = estimator.predict(x_test) 

4、题目:使用逻辑回归模型实现癌症分类预测。

题干

数据描述(附件中下载breast-cancer-wisconsin.data文件,拷贝至程序同一目录下)
(1)699条样本,共11列数据,第一列用语检索的id,后9列分别是与肿瘤相关的医学特征,最后一列表示肿瘤类型的数值。
(2)包含16个缺失值,用”?”标出。
要求:部分代码已给出,请根据提示编程实现题目,将代码填入选项中,一个选项只填一行代码。

部分代码如下:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
 
# 1.获取数据
names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']
 
data = pd.read_csv("breast-cancer-wisconsin.data",names=names)
data.head()
# 2.基本数据处理
# 2.1 缺失值处理
# 查看缺失值
data[data.replace(to_replace="?", value=np.NaN).isna().any(axis=1)]
# 处理缺失值
data = data.replace(to_replace="?", value=np.NaN)
data = data.dropna()
# 2.2 确定特征值,目标值
x = data.iloc[:, 1:10]
x.head()
y = data["Class"]
y.head()
# 2.3 分割数据
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
# 3.特征工程(标准化)
#实例化一个标准化模型
         A
#训练集标准化
        B
#测试集标准化
        C
# 4.机器学习(逻辑回归)
#实例化逻辑回归模型
        D
#训练回归模型
        E
# 5.模型评估
# 模型预测
        F
# 查看预测结果
y_predict
# 评估模型
       G

代码

A、 transfer = StandardScaler() 
B、 x_train = transfer.fit_transform(x_train) 
C、 x_test = transfer.transform(x_test) 
D、 estimator = LogisticRegression() 
E、 estimator.fit(x_train, y_train) 
F、 y_predict = estimator.predict(x_test) 
G、 estimator.score(x_test, y_test) 

5、题目:使用聚类算法模型实现顾客数据聚类分析。

题干

数据为附件中的customers.csv,下载附件至程序同一文件夹下。
部分代码已给出,请按照提示编程,将代码填入选项中,一个选项只填一行代码。

部分代码如下:

import pandas as pd

#读入文件
    A
#查看文件前5行数据
    B
#考虑最后两列作为分群依据:全部行,第四第五列Annual Income(k$) 和 Spending Score(1-100)
    C
#导入KMeans模型
    D
#生产实例化对象,聚5类,使用默认的k-means++算法,随机种子为42
    E
#直接训练并生成聚类结果
    F
#输出聚类结果
print(y_kmeans)

代码

A、 dataset = pd.read_csv('customers.csv') 
B、 dataset.head() 
C、 X = dataset.iloc[:, [3, 4]].values  
D、 from sklearn.cluster import KMeans 
E、 kmeans = KMeans(n_clusters = 5, init = 'k-means++', random_state = 42) 
F、 y_kmeans = kmeans.fit_predict(X) 

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Programming Exercise 1: Linear Regression Machine Learning Introduction In this exercise, you will implement linear regression and get to see it work on data. Before starting on this programming exercise, we strongly recom- mend watching the video lectures and completing the review questions for the associated topics. To get started with the exercise, you will need to download the starter code and unzip its contents to the directory where you wish to complete the exercise. If needed, use the cd command in Octave/MATLAB to change to this directory before starting this exercise. You can also find instructions for installing Octave/MATLAB in the “En- vironment Setup Instructions” of the course website. Files included in this exercise ex1.m - Octave/MATLAB script that steps you through the exercise ex1 multi.m - Octave/MATLAB script for the later parts of the exercise ex1data1.txt - Dataset for linear regression with one variable ex1data2.txt - Dataset for linear regression with multiple variables submit.m - Submission script that sends your solutions to our servers [?] warmUpExercise.m - Simple example function in Octave/MATLAB [?] plotData.m - Function to display the dataset [?] computeCost.m - Function to compute the cost of linear regression [?] gradientDescent.m - Function to run gradient descent [†] computeCostMulti.m - Cost function for multiple variables [†] gradientDescentMulti.m - Gradient descent for multiple variables [†] featureNormalize.m - Function to normalize features [†] normalEqn.m - Function to compute the normal equations ? indicates files you will need to complete † indicates optional exercises
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寂静花开

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值