Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        2年前关闭。
                                                                                            
                
        
我是机器学习和sklearn的新手。
因此,我有以下问题:

我正在尝试进行线性回归,但是我想使用某些.txt文件中的数据。
我有一些数据带有3列的表。

然后,我想知道如何更改以下代码,这是http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html中的示例

然后我在前面的示例中更改了一些代码,并发明了一些数据,这是正确的方法吗?像这样使用一些XY。然后,我还想知道等式中的内容:x_train = x [:2][:2]对我的程序有一些影响。我真的没有得到这部分。

from sklearn import linear_model
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score

#X has to be numpy array not list.

x=([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
y=[5,3,8,3,4,5,5,7,8,9,10]

x_train = x [:2]
x_test = x [2:]

y_train = y[:2]
y_test = y[2:]

regr = linear_model.LinearRegression()
regr.fit (x_train,y_train)

y_pred = regr.predict(x_test)

#coefficient
print('Coefficients: \n', regr.coef_)

#the mean square error
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print('Variance score: %.2f' % r2_score(y_test, y_pred))

plt.scatter(x_test, y_test,  color='black')
plt.plot(x_test, y_pred, color='blue', linewidth=3)
plt.axis([0, 20, 0, 20])
plt.show()


非常感谢!

编辑1

在此网页上获得的帮助下,我尝试编写一些代码,以生成适合自己的数据,但我无法获得正确的匹配,因此,如果有人有时间帮助我更多或告诉我如果我做错了我。

我在获取图片时使用的代码

import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')
#x = data[['col1','col2']]
x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

# define the KFolds
kf = KFold(n_splits=2)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold
#if you want to return other scores than r2, just change the scoring in cross_val_score
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)

for train_index, test_index in kf.split(x):
  print("TRAIN:", train_index, "TEST:", test_index)
  X_train, X_test = x[train_index], x[test_index]
  y_train, y_test = y[train_index], y[test_index]


plt.scatter (X_test, y_test)
plt.show()


我在这里为看起来像我的数据以及我从TRAIN AND TEST machine-learning - 如何在sklearn中使用自己的数据集-Python3-LMLPHP中得到的图像

然后我做了一些合适的程序,但是我不确定它是否正确:

regr.fit (X_train, y_train)
y_pred = regr.predict(X_test)
print(y_pred)
plt.scatter(X_test, y_test,  color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show()


而且我变得完全奇怪。machine-learning - 如何在sklearn中使用自己的数据集-Python3-LMLPHP

我不明白为什么会得到它,如果我使用MINUIT进行操作时,我的健身效果很好。因此,如果有人有帮助我的提示。

为什么显然该程序没有使用我的“ y”数据来进行TRAIN或TEST采样?

我的数据可以在这里获取:https://www.dropbox.com/sh/nbbsc0fqznkwxvt/AAD-u6lM4orJOGrgIyz0o8B9a?dl=0

对我而言,唯一重要的是col1和col3,应忽略col2。然后,我要对该数据进行拟合并提取拟合值。我知道这是一条适合这些数据的线。

谢谢!

最佳答案

首先,您想要拆分数据并使用一部分数据来训练模型,而另一部分来评估模型的主要原因是避免过度拟合。通常,我们使用KFolds或LOO(留出一个)进行交叉验证。

这是一个使用30个样本,3个变量并与KFolds进行交叉验证的示例。

import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model

#create artificial data with 30 lines (samples) and 3 columns (variables)
x = np.random.rand(30,3)

#create the target variable y
y = range(30)

# convert the list to numpy array (this is needed for fit method of sklearn)
y = np.asarray(y)

# define the KFolds (3 folds in this example)
kf = KFold(n_splits=3)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold (here we have 3).
#if you want to return other scores than r2, just change the scoring in cross_val_score.
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)


结果:

在这里,您可以看到每个折叠的模型的r2得分。因此,我们将数据分割了3次,并使用3种不同的训练数据来获得这些值。这是sklearn在cross_val_score方法中自动完成的。

 array([-30.36184326,  -0.4149778 , -28.89110233])


要了解什么是KFold,您可以使用以下方法打印培训和测试索引:

for train_index, test_index in kf.split(x):
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = x[train_index], x[test_index]
   y_train, y_test = y[train_index], y[test_index]


结果:

('TRAIN:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
   17, 18, 19]), 'TEST:', array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]))


现在,您可以看到在第一折中我们使用了示例:10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

接下来,对于第二折,我们使用样本:0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

注意:这些数字是x数据的索引。例如。 2表示第三个样本(行)。在python中,我们从0开始计数。
如您所见,我们在每个折页中都没有使用完全相同的数据(样本)。

希望这可以帮助。

编辑1

回答有关加载txt数据的问题。假设您有一个包含3列的txt文件。前两列是要素,最后一列是y(目标)。

在这种情况下,您可以使用熊猫执行以下操作:

import pandas as pd
import numpy as np

data = pd.read_csv('data.txt')
x = data[['col1','col2']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)


txt在这里:https://ufile.io/eb5xl(选择慢速下载)。

编辑2

这仅用于可视化目的。我不拆分数据。我使用所有数据来拟合模型,然后对同一数据进行预测。然后绘制预测值。

import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_predict
from sklearn import linear_model
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')

x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

regr = linear_model.LinearRegression()
regr.fit(x, y)

y_predicted = regr.predict(x)

plt.scatter(x, y,  color='black')
plt.plot(x, y_predicted, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()


结果:

似乎数据没有遵循线性模式。应该使用其他模型(例如指数拟合)

machine-learning - 如何在sklearn中使用自己的数据集-Python3-LMLPHP

关于machine-learning - 如何在sklearn中使用自己的数据集-Python3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47352526/

10-12 18:11
查看更多