gpt4 book ai didi

python - 循环填充Python中的矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 05:12:04 25 4
gpt4 key购买 nike

在行中,diabetes_x = diabetes.data[:, np.newaxis, 0]它从这个糖尿病数据结构中选择 20 个特征之一作为向量。该 x 向量的一部分被提供给机器学习功能,另一部分用于测试。

最后,它将这些测试 x 向量提供给预测函数以获得 y_predict=regr.predict(diabetes_x_train)

问题是:如何循环这个,以便获得矩阵而不是向量来填充所有 20 个特征?

例如:

diabetes_xmxn => diabetes_x_train, diabetes_x_testmxn y_predictmxn

这是python代码:

from sklearn import linear_model # Machine Learning tool
import numpy as np # Mathematics and Linear Algebra tool
import pandas as pd # data structure tool
import matplotlib.pyplot as plt # scientific plotting tool
import seaborn as sns # # scientific plotting tool
%matplotlib inline

### Linear Regression example
from sklearn import datasets, linear_model

# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_x = diabetes.data[:, np.newaxis, 0] # change 0 to something else for other features
# Split the data into training/testing sets
diabetes_x_train = diabetes_x[:-20]
diabetes_x_test = diabetes_x[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_x_train, diabetes_y_train)
# Obtain prediction based on previous experience
y_predict=regr.predict(diabetes_x_train)

最佳答案

您可以尝试选择所有 10 个功能(至少我在 Windows 上使用的 sklearn 0.18.1python 2.7 总共有 10 个) :

diabetes_x = diabetes.data[:, range(10)] # select 10 features
# Split the data into training/testing sets
diabetes_x_train = diabetes_x[:-20,:]
print diabetes_x_train.shape
# (422L, 10L)
diabetes_x_test = diabetes_x[-20:,:]
print diabetes_x_test.shape
# (20L, 10L)
# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_x_train, diabetes_y_train)
# Obtain prediction based on previous experience
y_predict=regr.predict(diabetes_x_test)
#print y_predict

plt.plot(range(len(diabetes.target)), diabetes.target, 'r-', label='test')
plt.plot(range(len(diabetes_y_train), len(diabetes.target)), y_predict, 'g-', label='predict')
plt.legend()
plt.show()

enter image description here

关于python - 循环填充Python中的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com