#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
#生成矩阵大小为50*2的0-100的随机整数
x=np.random.randint(0,100,(50,2))
# In[5]:
#转浮点型
x=np.array(x,dtype=float)
# In[16]:
#均值 标准差
np.mean(x[:,0]),np.std(x[:,0])
np.mean(x[:,1]),np.std(x[:,1])
# In[19]:
#正则化
x[:,0]=(x[:,0]-np.mean(x[:,0]))/np.std(x[:,0])
x[:,1]=(x[:,1]-np.mean(x[:,1]))/np.std(x[:,1])
# In[20]:
#绘图
plt.scatter(x[:,0],x[:,1])
plt.show()
# In[21]:
#正则化后的均值方差
np.mean(x[:,0]),np.std(x[:,0])
# In[24]:
from sklearn import datasets
iris=datasets.load_iris()
X=iris.data
y=iris.target
# In[25]:
#train_test_split用于分割数据集,将数据集按一定比例分割为训练集和测试集
#test_size=0.2,训练集占0.8,测试集占0.2
#random_state=6,随机数种子,不设置则每次生成结果随机
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=6)
# In[28]:
X_train.shape,y_test.shape
# In[31]:
#StandardScaler用于标准化数据特征,均值为0,方差为1
from sklearn.preprocessing import StandardScaler
standscaler=StandardScaler()
standscaler.fit(X_train)#以X_train为基准对数据进行标准化
std_X_train=standscaler.transform(X_train)#数据标准化并赋值
std_X_test=standscaler.transform(X_test)
# In[34]:
#KNeighborsClassifier用于生成k近邻算法模型
#n_neighbors=3,算法中k值为3
from sklearn.neighbors import KNeighborsClassifier
clf=KNeighborsClassifier(n_neighbors=3)
clf.fit(std_X_train,y_train)#训练模型
# In[38]:
#测试训练模型得分
clf.score(std_X_test,y_test)
# In[39]:
#模型训练后对测试集的预测值
clf.predict(std_X_test)
# In[ ]:
Python机器学习入门——2.数据标准化
最新推荐文章于 2023-05-31 23:33:06 发布