回归结果不正确

我是一名机器学习(ML)的初学者,无法弄清楚为什么我的回归结果不正确或无法正确绘图。目前我使用的是从一本书中前面的示例中获取的大部分内容。我正在使用这本书进行学习。如果有人能解释一下成本函数公式的来源就更好了。

import timeimport csvimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitimport tensorflow as tfimport numpy as npdef read_csv(filepath, bucket=7):    days_in_year = 365    freq = {}    for period in range(0, int(days_in_year / bucket)):        freq[period] = 0    with open(filepath, 'r') as csvfile:        csvreader = csv.reader(csvfile)        csvreader.__next__()        for row in csvreader:            if row[0] == '':                continue            t = time.strptime(row[0], "%m/%d/%Y")            if t.tm_year == 2014 and t.tm_yday < (days_in_year-1):                freq[int(t.tm_yday / bucket)] += 1    print("finished reading input")    return freqfreq = read_csv("311_data.csv")x_dataset = list(freq.keys())y_dataset = list(freq.values())print(x_dataset)print(y_dataset)def normalize(data):    y = np.empty(len(data))    count = 0    for x in data:        y[count] = (x-min(data))/(max(data)-min(data))        count += 1    return yx_dataset = normalize(x_dataset)y_dataset = normalize(y_dataset)(x_train, x_test, y_train, y_test) = train_test_split(x_dataset, y_dataset, train_size=0.7, test_size=0.3)learning_rate = 0.01training_epochs = 40num_coeffs = 9reg_lambda = 0.X = tf.placeholder(tf.float32)Y = tf.placeholder(tf.float32)def model(X, w):    terms = []    for i in range(num_coeffs):        term = tf.multiply(w[i], tf.pow(X, i))        terms.append(term)    return tf.add_n(terms)w = tf.Variable([0.] * num_coeffs, name="parameters")y_model = model(X, w)cost = tf.div(tf.add(tf.reduce_sum(tf.square(Y-y_model)), tf.multiply(reg_lambda, tf.reduce_sum(tf.square(w)))),          2*x_train.size)train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)sess = tf.Session()init = tf.global_variables_initializer()sess.run(init)for reg_lambda in np.linspace(0, 1, 100):    for epoch in range(training_epochs):            sess.run(train_op, feed_dict={X: x_train, Y: y_train})    final_cost = sess.run(cost, feed_dict={X: x_test, Y: y_test})    print('reg lambda ', reg_lambda)    print('final cost ', final_cost)w_val = sess.run(w)print(w_val)sess.close()plt.scatter(x_train, y_train)y_learned = 0for i in range(num_coeffs):    y_learned += w_val[i] * np.power(x_train, i)plt.plot(x_train, y_learned, 'r')plt.show()

这是我绘图时的结果:

绘图结果


回答:

看起来你获取的X,Y坐标是正确的,只是绘图时顺序不对。尝试使用plt.scatter而不是plt.plot来只绘制点而不是线,以验证这一点。如果你仍然想要线,你可以按以下方式进行成对排序:

points = zip(x_train, y_learned)points = sorted(points, key=lambda p: p[0])x_plot, y_plot = zip(*points)plt.plot(x_plot, y_plot, 'r')

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注