data[data['label'] == i].iloc[:,:-1].shape[0]含义
时间: 2023-10-29 08:07:30 浏览: 46
这段代码中,`data` 是一个 Pandas DataFrame,`data['label']` 是 DataFrame 中名为 `label` 的列,`data['label'] == i` 返回一个布尔类型的 Series,其中 `True` 表示该行所属的类别为 `i`,`False` 表示不是。`data[data['label'] == i]` 通过布尔索引选出所有所属类别为 `i` 的行,`.iloc[:,:-1]` 表示选取这些行的所有列,除了最后一列(也就是标签列),`.shape[0]` 返回选取到的行数。因此,`data[data['label'] == i].iloc[:,:-1].shape[0]` 表示数据集中所属类别为 `i` 的样本数量。
相关问题
def train_test_datasplit(samples): from sklearn.model_selection import train_test_split data = samples.iloc[:, 0:(samples.shape[1] - 1)] label = samples.iloc[:, -1] data_train, data_test, label_train, label_test = train_test_split(data, label, test_size=0.33, random_state=42) return data_train, data_test, label_train, label_test代码讲解
这段代码实现了一个数据集的划分函数,将输入的样本数据进行划分为训练集和测试集,其中:
- `samples`:输入的样本数据,是一个 pandas DataFrame,包含若干行和若干列,其中最后一列为标签数据。
- `train_test_split`:是 scikit-learn 中的一个函数,用于将数据集划分为训练集和测试集,该函数的参数包括:
- `data`:数据集的输入特征,即前面所有列的数据。
- `label`:数据集的输出标签,即最后一列的数据。
- `test_size`:测试集所占比例,默认为 0.33。
- `random_state`:随机数种子,用于控制随机结果的可重复性。
- `data_train`:划分后的训练集输入特征。
- `data_test`:划分后的测试集输入特征。
- `label_train`:划分后的训练集输出标签。
- `label_test`:划分后的测试集输出标签。
该函数的返回值是一个包含训练集和测试集的 4 个元素的元组。
import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=["SimHei"] #单使用会使负号显示错误 plt.rcParams['axes.unicode_minus']=False #把负号正常显示 # 读取北京房价数据 path='data.txt' data=pd.read_csv(path,header=None,names=['mianji','jiage']) # data.head() # data.describe() # 绘制散点图 data.plot(kind='scatter',x='mianji',y='jiage') plt.show() def computeCost(X,y,theta): inner=np.power((X*theta.T),2) return np.sum(inner)/(2*len(X)) data.insert(0,'Ones',1) clos=data.shape[1] X=data.iloc[:,0:clos-1] y=data.iloc[:,clos-1:clos] X=np.array(X.values) y=np.array(y.values) theta=np.array[0,0] computeCost(X,y,theta) def gradientDescent(X,y,theta,alpha,iters): temp=np.array(np.zeros(theta.shape)) parameters=int(theta.ravel().shape[1]) cost=np.zeros(iters) for i in range(iters): error=(X*theta.T)-y for j in range(parameters): term=np.multiply(error,X[:,j]) temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term)) theta=temp cost[i]=computeCost(X,y,theta) return theta,cost alpha=0.01 iters=1000 g,cost=gradientDescent(X,y,theta,alpha,iters) x=np.linspace(data.mianji.min(),data.mianji.max(),100) f=g[0,0]+(g[0,1]*x) fig,ax=plt.subplots(figsize=(12,8)) ax.plot(x,f,'r',label='北京房价') ax.scatter(data.mianji,data.jiage,label='Traning data') ax.legend(loc=4) ax.set_xlabel('房子面积') ax.set_ylabel('房子价格') ax.set_title("北京房价格回归图") plt.show()
在这段代码中,有几个错误:
1. 第一行和第二行之间应该有一个空行。
2. 导入numpy和pandas模块时,应该使用import语句,每个模块之间应该有一个空行。
3. 在第10行和11行中,应该将plt.rcParams的设置放在import语句之后。
4. 在第14行中,应该将data.insert(0,'Ones',1)改为data.insert(0,'Ones',np.ones(len(data))),以便将1插入到整个列中。
5. 在第16行中,应该将clos改为cols,因为该变量代表“列数”。
6. 在第18行中,应该将theta=np.array[0,0]改为theta=np.array([0,0]),以便创建一个2个元素的数组。
7. 在第25行和26行之间应该有一个空行。
8. 在第27行中,应该将parameters=int(theta.ravel().shape[0])改为parameters=int(theta.ravel().shape[1]),因为该数组是一个2x1的数组。
9. 在第36行中,应该将g,cost=gradientDescent(X,y,theta,alpha,iters)改为g,cost=gradientDescent(X,y,theta,alpha,int(iters)),以确保iters是一个整数。
10. 在第38行和39行之间应该有一个空行。
以下是修正后的代码:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ["SimHei"] # 单使用会使负号显示错误
plt.rcParams['axes.unicode_minus'] = False # 把负号正常显示
# 读取北京房价数据
path = 'data.txt'
data = pd.read_csv(path, header=None, names=['mianji', 'jiage'])
# data.head()
# data.describe()
# 绘制散点图
data.plot(kind='scatter', x='mianji', y='jiage')
plt.show()
def computeCost(X, y, theta):
inner = np.power((X * theta.T - y), 2)
return np.sum(inner) / (2 * len(X))
data.insert(0, 'Ones', np.ones(len(data))) # 将1插入到整个列中
cols = data.shape[1]
X = data.iloc[:, 0:cols-1]
y = data.iloc[:, cols-1:cols]
X = np.array(X.values)
y = np.array(y.values)
theta = np.array([0, 0]) # 创建一个2个元素的数组
computeCost(X, y, theta)
def gradientDescent(X, y, theta, alpha, iters):
temp = np.array(np.zeros(theta.shape))
parameters = int(theta.ravel().shape[1])
cost = np.zeros(iters)
for i in range(iters):
error = (X * theta.T) - y
for j in range(parameters):
term = np.multiply(error, X[:, j])
temp[0, j] = theta[0, j] - ((alpha / len(X)) * np.sum(term))
theta = temp
cost[i] = computeCost(X, y, theta)
return theta, cost
alpha = 0.01
iters = 1000
g, cost = gradientDescent(X, y, theta, alpha, int(iters)) # 确保iters是一个整数
x = np.linspace(data.mianji.min(), data.mianji.max(), 100)
f = g[0, 0] + (g[0, 1] * x)
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(x, f, 'r', label='北京房价')
ax.scatter(data.mianji, data.jiage, label='Traning data')
ax.legend(loc=4)
ax.set_xlabel('房子面积')
ax.set_ylabel('房子价格')
ax.set_title("北京房价格回归图")
plt.show()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)