机器学习 python

1、用DecisionTreeRegressor()对波士顿房价进行预测:

1、导入数据(sklearn.datasets.load_boston)

2、数据拆分25%作为测试集(sklearn.model_selection.train_test_split)

3、数据标准化(sklearn.preprocessing.StandardScaler)

4、训练模型(sklearn.tree.DecisionTreeRegressor的fit方法)

5、预测数据(predict方法)

6、评估模型(sklearn.metric中r2_score、mean_squared_error、mean_absolute_error方法评价)

from sklearn.datasets import load_boston
boston = load_boston()

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(boston.data,boston.target,test_size=0.25,random_state=0)

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler1 = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
y_train = scaler1.fit_transform(y_train.reshape(-1,1))
y_test = scaler1.transform(y.reshape(-1,1))

from sklearn.tree import DecisionTreeRegressor
DecisionTreeRegressor = DecisionTreeRegressor()
DecisionTreeRegressor.fit(X_train,y_train.ravel())

y_predict = DecisionTreeRegressor.predict(X_test)

sklearn.metric.r2_score(y_test,y_predict)
sklearn.metric.mean_squared_error(y_test,y_predict)
sklearn.metric.mean_absolute_error(y_test,y_predict)

2、导入与.py相同路径下的数据文件“airlines.csv”,并**存入一个名为airlines的数据框内

import pandas as pd
path1 = './airlines.csv'
airlines = pd.read_csv(path1)

3、简述kmeans的一般步骤。

1、随机在图中取k个种子点
2、然后对图中所有点求所有点求到这k个种子点距离,如果点Pi离种子点最近,那么Pi离种子点最近,那么Pi属于Si点群
3、移动种子点到所属‘点群’中心
4、重复2、3,直到没有点可移动

4、找到二维数组np.arange(9).reshape(3,3)每一行中的最大值

array = np.arange(9).reshape(3,3)
array.max(axis=1)

5、主成分分析(PCA)的主要步骤有哪些?

1、去除平均值
2、计算协方差矩阵
3、计算协方差矩阵的特征值和特征向量
4、将特征值从大到小排序
5、保留最上面的k个特征向量
6、将数据转换到上述的k个特征向量的新空间中

6、假设总共有100个病例,真实情况是50个恶性肿瘤,50个良性肿瘤。使用机器学习算法预测后得到的结果如下:

55个是恶性肿瘤(其中45个与实际相符,10个与实际不符);

45个是良性肿瘤(其中40个与实际相符,5个与实际不符);

请计算这个机器学习算法的准确率、精度、召回率三个指标。

TP = 45 FN = 5 P =50
FP = 10 TN = 40 N=50
P’ = 55 N’ = 45 P+N = 100
准确率:(TP+TN) / (P+N) = 0.85
精度:TP / (TP+FP) = 0.818
召回率: TP / P = 0.9

7、输入n, 创建nXn的二维数组, 其边缘为1,内部均为0

z = np.ones((n,n))
z[1:-1,1:-1] = 0

8、填空

from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
X,y = load_digits(return_X_y=True)
from sklearn.model_selection import train_test_split
# 随机选取75%的数据作为训练样本;其余25%的数据作为测试样本。
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=33)
1#将KMeans实例化为对象
 (                     )
2#拟合训练数据
(                       )
3#对测试数据预测
(                        )
print(y_pred)
1、kmeans = KMeans(n_clusters=10)
2、kmeans.fit(X_train)
3、y_pred = kmeans.predict(X_test)

9、用NuSVC()对手写体数字进行识别并评价:

1、导入数据(sklearn.datasets.load_digits)

2、数据拆分25%作为测试集(sklearn.model_selection.train_test_split)

3、数据标准化(sklearn.preprocessing.StandardScaler)

4、训练模型(sklearn.svm.NuSVC)

5、预测数据(predict()方法)

6、评估模型(sklearn.metrics中classification_report()方法)

from sklearn.datasets import load_digits
digits = load_digits()

from sklearn.model_selection import train_test_split
X_test,X_train,y_test,y_train = train_test_split(digits.data,digits.target,test_size=0.25)

from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_test = ss.fit_transform(X_test)
X_train = ss.fit_transform(X_train)

from sklearn.svm import NuSVC
nusvc = NuSVC()
nusvc.fit(X_train,y_train)

y_pred = nusvc.predict(X_test)

from sklearn.metrics import classification_report
print(classification_report(y_test,y_predict))

10、简述层次聚类的一般步骤

1、n个样本看作孤立的节点
2、计算数据集中每对样本间的相似度
3、根据相似度从强到弱连接相对应节点对,形成对应节点,形成树状结构
4、根据实际需求横切树状图,获得簇结构

11、输入n, 创建n个元素的一维数组,形如:[0,n,0,n,0,n,…]

import numpy as np
z = np.zeros(n)
z[1::2] = n

12、运行结果?

sent1 = 'The cat is walking in the bedroom.'
sent2 = 'A dog was running across the kitchen.'
from sklearn.feature_extraction.text import CountVectorizer
count_vec = CountVectorizer()
sentences = [sent1, sent2]
print(count_vec.fit_transform(sentences).toarray())
print(count_vec.get_feature_names())
[[0 1 1 0 1 1 0 0 2 1 0]
 [1 0 0 1 0 0 1 1 1 0 1]]
['across', 'bedroom', 'cat', 'dog', 'in', 'is', 'kitchen', 'running', 'the', 'walking', 'was']

13、将一维数组np.arange(10)转换为2行的二维数组

import numpy as np
array = np.arange(10)reshape(2,5)

14、使用SGDClassifier对乳腺癌数据进行预测并评价,采用默认参数值

1、使用pandas从本地读入数据文件breast-cancer-wisconsin.data

2、将?替换为标准缺失值表示。

3、使用sklearn. model_selection中的train_test_split模块用于分割数据。

4、使用sklearn.preprocessing中的StandardScaler对数据标准化

5、使用sklearn.linear_model中的SGDClassifier训练数据并对测试数据预测

6、使用sklearn.metrics中的classification_report模块对预测结果评价

要求代码运行后效果:

Accuarcy of SGD Classifier: 0.9532163742690059

​ precision recall f1-score support

Benign 0.97 0.95 0.96 100

Malignant 0.93 0.96 0.94 71

accuracy 0.95 171

macro avg 0.95 0.95 0.95 171

weighted avg 0.95 0.95 0.95 171

import pandas as pd
data = pd.read_csv('./breast-cancer-wisconsin.data')
data.replace('?','np.nan',inplace=True)
data.dropna(how='any',inplace=True)

from sklearn. model_selection import train_test_split
X_test,X_train,y_test,y_train = train_test_split(data[1:10],data[10],test_size=0.25,random_state=33)

from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
X_test = ss.transform(X_test)
X_train = ss.fit_transform(X_train)

from sklearn.linear_model import SGDClassifier
sgdc = SGDClassifier()
sgdc.fit(X_train,y_train)

y_pred = sgdc.predict(X_test)

from sklearn.metrics import classification_report
classification_report(y_test,y_pred)

15、基于聚类的异常值检测算法一般思路是什么?

1、聚类算法形成簇
2、计算每个点到聚类中心的距离
3、根据阈值判定该点是不是异常点

16、鸢尾花

使用LogisticRegression类(采用默认参数值)对鸢尾花数据训练,并打印索引【25,75,120】的真实值、预测值、概率估计

1、从sklearn.datasets导入数据

2、使用sklearn. linear_model中的LogisticRegression训练数据并对指定测试数据预测

数据结果示意图:

真实值: [0 1 2]

预测值: [0 1 2]

预测概率估计: [[7.74387849e-01 2.25570742e-01 4.14089912e-05]

[3.58881987e-02 8.29637761e-01 1.34474040e-01]

[5.08108403e-04 2.23925960e-01 7.75565932e-01]]

from sklearn.datasets import load_iris
X,y = load_iris(return_X_y=True)

from sklearn.linear_model import LogisticRegression
logist = LogisticRegression(max_iter=1000)
logist.fit(X,y)
y[[25,75,120]]
logist.predict(X[[25,75,120])
logist.predict_proba(X[[25,75,120]])

17、将数组a = np.arange(10).reshape(2,-1)和数组b = np.repeat(1, 10).reshape(2,-1)垂直堆叠

import numpy as np
a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
np.vstack((a, b))
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值