file = "iris.csv" import pandas as pd # 数据读取类库 # header指定文件是否有表头 df = pd.read_csv(file, header = None) # 显示文件前十行 df,head(10) import matplotlib.pyplot as plt import numpy as np # 得到数据前一百行的第五列 y = df.loc[0:100, 4].values print(y) # 将字符串转化为数字 y = np.where(y == 'Iris-setosa', -1, 1) # 抽取数据第0列和第2列 x = df,iloc[0:100, [0, 2]].values # scatter散列点绘图 plt.scatter(x[:50, 0], x[:50, 1], color='red', marker='o', label='setosa') plt.scatter(x[50:100, 0], x[50:100, 1], color='blue', marker='x', label='versicolor') plt.xlabel('花瓣长度') plt.ylabel('花茎长度') plt.legend(loc='upper left') plt.show()
numpy的库 调用里面的函数 where()
panda数据分析库 df = pd.read_csv(file , header = None) df.head(10) 读取10行 df.loc[0:100 , 4].values 读取0到100行的第四列数据 iloc主要使用数字来索引数据,而不能使用字符型的标签来索引数据 而loc则刚好相反,只能使用字符型标签来索引数据,不能使用数字 来索引数据 plt.scatter绘制散点图 plt.scatter(X[:50 , 0] , X[:50 , 1] , color='red' , marker='o') 前50列数据,x轴为0列,y轴为1列数据,画出的点为红圈
file="" import pandas as pd import matplotlib.pyplot as plt import numpy as np df=pd.read_cvs(flie,header=none)//文件第一行即数据第一行 y=df.loc[0:100,4].values//读取数据,将0-100行数据的第四列,作为输出y(vector) y=np.where(y=="",1,-1)//将输出字符串转化成数字 x=df.loc[0:100,[0,2]].values//第0列和第2列作为输入抽取出来 plt.scatter(x[:50,0],x[:50,1],color='red',marker='o',label="xxx") plt.scatter(x[50:100,0],x[50:100,1],color='blue',marker='x',label="yyy") plt.xlabel('lll') plt.ylabel('mmm') plt.legend(loc='upper left')//设置图例属性 plt.show()
数据解析和可视化
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv(file, header=None) y = df.loc[0:100, 4].values y = np.where(y == 'Iris-setosa', -1, 1) X = df.iloc[0:100, [0, 2]].values plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa') plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='versicolor') plt.xlabel('花瓣长度') plt.ylabel('花茎长度') plt.legend(loc='upper left') plt.show()
数据分类(将预测的数据输入到神经网络中,以图形方式绘制)
from matplotlib.colors import ListedColormap def plot_decision_regions(X, y, classifier, resolution=0.02): marker = ('s', 'x', 'o', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() #将x1、x2最大最小值通过arange函数得到的向量,扩展成两个二维矩阵 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) #预测 Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) #ravel还原成单维向量 #绘制 Z= Z.reshape(xx1.shape) #将Z转换成与xx1一样的二维数组 plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) #在两组分类结果中间画分割线-->必须线性可分 plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y==cl, 0], y=X[y==cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)