简体   繁体   English

线性回归神经网络 Tensorflow Keras Python 程序

[英]Linear Regression Neural Network Tensorflow Keras Python program

I wrote a small "Linear Regression Neural Network Tensorflow Keras Python program"我写了一个小的“线性回归神经网络 Tensorflow Keras Python 程序”

Input dataset is y = mx + c straight line data.输入数据集是 y = mx + c 直线数据。

Predicted y values are not correct and are giving horizontal line kind of values, instead of a line with some slope.预测的 y 值不正确,并且给出了水平线类型的值,而不是具有一定斜率的线。

I ran this program on Windows laptop with tensorflow, Keras and Jupyter notebook.我在带有 tensorflow、Keras 和 Jupyter notebook 的 Windows 笔记本电脑上运行了这个程序。

What to do to fix this program please?请问如何修复这个程序?

Thanks and best regards, SSJ谢谢和最好的问候,SSJ

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
n2 = 50
count = 20
n4 = n2 + count
p = 100
m = 10
c  = 5
x = np.linspace(n2, n4, p)
y = m * x + c
x
y
plt.scatter(x,y)
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental import preprocessing
x_normalizer = preprocessing.Normalization(input_shape=[1,])
x_normalizer.adapt(x)
x_normalized = x_normalizer(x)
y_normalizer = preprocessing.Normalization(input_shape=[1,])
y_normalizer.adapt(y)
y_normalized = x_normalizer(y)
y_model = tf.keras.Sequential([
    y_normalizer,
    layers.Dense(1)
])
y_model.compile(optimizer='rmsprop', loss='mse', metrics = ['mae'])
y_hist = y_model.fit(x, y, epochs=100, verbose=0, validation_split = 0.2)
hist = pd.DataFrame(y_hist.history)
hist['epoch'] = y_hist.epoch
hist.head()
hist.tail()
xin = [51,53,59,64]
ypred = y_model.predict(xin)
ypred
plt.scatter(x, y)
plt.scatter(xin, ypred, color = 'r')
plt.grid(linestyle = '--')

Use StandardScaler instead of Normalization使用 StandardScaler 而不是 Normalization

Normalizer acts row-wise and StandardScaler column-wise. Normalizer 按行操作,StandardScaler 按列操作。 Normalizer does not remove the mean and scale by deviation but scales the whole row to unit norm. Normalizer 不会删除均值和按偏差缩放,而是将整行缩放到单位范数。

Found here: Difference between StandardScaler and Normalizer在这里找到: StandardScaler 和 Normalizer 之间的区别

This is how you can process the data:这是您处理数据的方式:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from sklearn.preprocessing import StandardScaler
x = np.linspace(50, 70, 100).reshape(-1, 1)
y = 10 * x + 5
x_standard_scaler = StandardScaler().fit(x)
y_standard_scaler = StandardScaler().fit(y)
x_scaled = x_standard_scaler.transform(x)
y_scaled = y_standard_scaler.transform(y)

Remember that you need two separate scalers for x and y so don't use the same object for that.请记住,您需要两个单独的 x 和 y 缩放器,因此不要为此使用相同的对象。 Also if you want to use that scaler to process new data for testing, save the scaler in some variable.此外,如果您想使用该缩放器来处理新数据以进行测试,请将缩放器保存在某个变量中。 A good practice is to not refit the scaler again on test data.一个好的做法是不要在测试数据上再次重新调整定标器。

model = Sequential([
    Dense(1, input_dim=1, activation='linear'),
])
model.compile(optimizer='rmsprop', loss='mse')
history = model.fit(x_scaled, y_scaled, epochs=1000, verbose=0, validation_split = 0.2).history
pd.DataFrame(history).plot()
plt.show()

在此处输入图片说明

As you can see the model is converging.如您所见,模型正在收敛。 Its worth to plot the loss history which helps to tell if your model is learning or not.绘制损失历史有助于判断您的模型是否正在学习是值得的。

x_test = np.linspace(20, 100, 10).reshape(-1, 1)
y_test = 10 * x_test + 5
x_test_scaled = x_standard_scaler.transform(x_test)
y_test_scaled = y_standard_scaler.transform(y_test)

If you have a test data that you want to use for validation or just predict it, remember to use standard scaler again, but without fitting.如果您有要用于验证或只是预测的测试数据,请记住再次使用标准缩放器,但不要拟合。 It should be fitted on train data only in most cases.只有在大多数情况下,它才应该适合火车数据。

y_test_pred_scaled = model.predict(x_test_scaled)
y_test_pred = y_standard_scaler.inverse_transform(y_test_pred_scaled)
plt.scatter(x_test, y_test, s=30, label='true')
plt.scatter(x_test, y_test_pred, s=15, label='pred')
plt.legend()
plt.show()

在此处输入图片说明

If you want to get your prediction rescaled back to its original range use inverse_transform .如果您想让您的预测重新调整回其原始范围,请使用inverse_transform Notice that prediction on x_test after rescaling is very close to y_test .请注意,重新缩放后对x_test预测非常接近y_test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM