python - 实现一个基本的神经网络来预测 y = 2x
问题描述
它是一个线性函数。我给它以下输入
input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
output = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
我了解到,没有隐藏层的网络只是一个感知器,基本上是回归。但是让我们说在此之后我想预测 y = x^2 这对于类似的输出将是非线性的。
在张量流中你可以做
from __future__ import absolute_import, division, print_function
import pathlib
import pandas as pd
import seaborn as sns
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
print(tf.__version__)
xs = np.array([2,4,6,8,10,12,14,16,18,20, 22, 24, 26, 28])
ys = np.array([4,8,12,16,20,24,28,32,36,40, 44, 48, 52, 56])
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=[1]),
layers.Dense(64, activation='relu'),
layers.Dense(1)
])
model.compile(loss='mse')
model.fit(xs, ys, epochs = 500)
print(model.predict([30, 31, 32, 33]))
我试图弄清楚从头开始的神经网络如何在相同的输入长度和相同的输出长度下工作。
我目前正在将输入向量乘以随机权重-> vector_h(在初始化函数中执行)
这是我开始的:
import math
def sigmoid_activation(x):
try:
return 1 / (1 + math.exp(-x))
except:
return 0
def sigmoid_derivative(self, x):
return x * (1 - x)
class NeuralNet:
def __init__(self, training_input, training_output, testing_input):
self.training_input = training_input
self.training_output = training_output
self.testing_input = testing_input
self.epoch = 100
self.weight = [ random.uniform(0, 9) for i in range(len(training_input)) ]
def neuron(self):
return sigmoid_activation(sum([ self.training_input[i] * self.weight[i] for i in range(len(self.training_input)) ])) # I am not sure if this is correct.
def run(self):
for iteration in range(self.epoch):
# Not sure how to go from here
pass
几个问题
- 这更像是一个感知器而不是一个神经网络吗?
- 我正在使用激活函数,因此当输出是非线性函数时,它也可以大致预测。
- 是否需要将给定的输入形状更改为 [[1], [2], [3]]
解决方案
推荐阅读
- jpa - 父 ID 未填充到子对象中 - JPA
- html - 在单击下拉列表时调用函数,但在选择 Angular 中的任何选项之前
- python - 如何为多个饼图保持相同的颜色顺序?
- kubernetes - Helm 包含模板
- powershell - PowerShell 作业,写入文件
- javascript - 数据表导出Excel,根据内容自定义行高
- regex - NGINX 基本身份验证,代理内容的位置问题
- objective-c - macOS - 尝试在 NSTextField 上使用自定义 NSFormatter 失败了
- c# - VS2019 - C# - 异常未显示在哪里抛出
- java - 之前如何向spring项目添加参数
/login 及之后 : 没有硬编码?