Python机器学习入门——2.数据标准化

#!/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[ ]:





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值